blob: 679b500ee61ff4cd2f889411de05899d330e978a [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 \"";
546 SuggestedPredefines +=
547 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
548 SuggestedPredefines += "\"\n";
549 }
550
551 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
552 StringRef File = ExistingPPOpts.MacroIncludes[I];
553 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
554 File)
555 != PPOpts.MacroIncludes.end())
556 continue;
557
558 SuggestedPredefines += "#__include_macros \"";
559 SuggestedPredefines +=
560 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
561 SuggestedPredefines += "\"\n##\n";
562 }
563
564 return false;
565}
566
567bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
568 bool Complain,
569 std::string &SuggestedPredefines) {
570 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
571
572 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000573 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000574 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000575 SuggestedPredefines,
576 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000577}
578
Guy Benyei11169dd2012-12-18 14:30:41 +0000579void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
580 PP.setCounterValue(Value);
581}
582
583//===----------------------------------------------------------------------===//
584// AST reader implementation
585//===----------------------------------------------------------------------===//
586
Nico Weber824285e2014-05-08 04:26:47 +0000587void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
588 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000589 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000590 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000591}
592
593
594
595unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
596 return serialization::ComputeHash(Sel);
597}
598
599
600std::pair<unsigned, unsigned>
601ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000602 using namespace llvm::support;
603 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
604 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000605 return std::make_pair(KeyLen, DataLen);
606}
607
608ASTSelectorLookupTrait::internal_key_type
609ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000610 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000611 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000612 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
613 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
614 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000615 if (N == 0)
616 return SelTable.getNullarySelector(FirstII);
617 else if (N == 1)
618 return SelTable.getUnarySelector(FirstII);
619
620 SmallVector<IdentifierInfo *, 16> Args;
621 Args.push_back(FirstII);
622 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000623 Args.push_back(Reader.getLocalIdentifier(
624 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000625
626 return SelTable.getSelector(N, Args.data());
627}
628
629ASTSelectorLookupTrait::data_type
630ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
631 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000632 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000633
634 data_type Result;
635
Justin Bogner57ba0b22014-03-28 22:03:24 +0000636 Result.ID = Reader.getGlobalSelectorID(
637 F, endian::readNext<uint32_t, little, unaligned>(d));
638 unsigned NumInstanceMethodsAndBits =
639 endian::readNext<uint16_t, little, unaligned>(d);
640 unsigned NumFactoryMethodsAndBits =
641 endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +0000642 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
643 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
644 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
645 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
Guy Benyei11169dd2012-12-18 14:30:41 +0000646
647 // Load instance methods
648 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000649 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
650 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000651 Result.Instance.push_back(Method);
652 }
653
654 // Load factory methods
655 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000656 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
657 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000658 Result.Factory.push_back(Method);
659 }
660
661 return Result;
662}
663
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000664unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
665 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000666}
667
668std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000669ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000670 using namespace llvm::support;
671 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
672 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000673 return std::make_pair(KeyLen, DataLen);
674}
675
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000676ASTIdentifierLookupTraitBase::internal_key_type
677ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000678 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000679 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000680}
681
Douglas Gregordcf25082013-02-11 18:16:18 +0000682/// \brief Whether the given identifier is "interesting".
683static bool isInterestingIdentifier(IdentifierInfo &II) {
684 return II.isPoisoned() ||
685 II.isExtensionToken() ||
686 II.getObjCOrBuiltinID() ||
687 II.hasRevertedTokenIDToIdentifier() ||
688 II.hadMacroDefinition() ||
689 II.getFETokenInfo<void>();
690}
691
Guy Benyei11169dd2012-12-18 14:30:41 +0000692IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
693 const unsigned char* d,
694 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000695 using namespace llvm::support;
696 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000697 bool IsInteresting = RawID & 0x01;
698
699 // Wipe out the "is interesting" bit.
700 RawID = RawID >> 1;
701
702 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
703 if (!IsInteresting) {
704 // For uninteresting identifiers, just build the IdentifierInfo
705 // and associate it with the persistent ID.
706 IdentifierInfo *II = KnownII;
707 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000708 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000709 KnownII = II;
710 }
711 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000712 if (!II->isFromAST()) {
713 bool WasInteresting = isInterestingIdentifier(*II);
714 II->setIsFromAST();
715 if (WasInteresting)
716 II->setChangedSinceDeserialization();
717 }
718 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000719 return II;
720 }
721
Justin Bogner57ba0b22014-03-28 22:03:24 +0000722 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
723 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000724 bool CPlusPlusOperatorKeyword = Bits & 0x01;
725 Bits >>= 1;
726 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
727 Bits >>= 1;
728 bool Poisoned = Bits & 0x01;
729 Bits >>= 1;
730 bool ExtensionToken = Bits & 0x01;
731 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000732 bool hasSubmoduleMacros = Bits & 0x01;
733 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000734 bool hadMacroDefinition = Bits & 0x01;
735 Bits >>= 1;
736
737 assert(Bits == 0 && "Extra bits in the identifier?");
738 DataLen -= 8;
739
740 // Build the IdentifierInfo itself and link the identifier ID with
741 // the new IdentifierInfo.
742 IdentifierInfo *II = KnownII;
743 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000744 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000745 KnownII = II;
746 }
747 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000748 if (!II->isFromAST()) {
749 bool WasInteresting = isInterestingIdentifier(*II);
750 II->setIsFromAST();
751 if (WasInteresting)
752 II->setChangedSinceDeserialization();
753 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000754
755 // Set or check the various bits in the IdentifierInfo structure.
756 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000757 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000758 II->RevertTokenIDToIdentifier();
759 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
760 assert(II->isExtensionToken() == ExtensionToken &&
761 "Incorrect extension token flag");
762 (void)ExtensionToken;
763 if (Poisoned)
764 II->setIsPoisoned(true);
765 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
766 "Incorrect C++ operator keyword flag");
767 (void)CPlusPlusOperatorKeyword;
768
769 // If this identifier is a macro, deserialize the macro
770 // definition.
771 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000772 uint32_t MacroDirectivesOffset =
773 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000774 DataLen -= 4;
775 SmallVector<uint32_t, 8> LocalMacroIDs;
776 if (hasSubmoduleMacros) {
Richard Smithdaa69e02014-07-25 04:40:03 +0000777 while (true) {
778 uint32_t LocalMacroID =
779 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000780 DataLen -= 4;
Richard Smithdaa69e02014-07-25 04:40:03 +0000781 if (LocalMacroID == 0xdeadbeef) break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000782 LocalMacroIDs.push_back(LocalMacroID);
783 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000784 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000785
786 if (F.Kind == MK_Module) {
Richard Smith49f906a2014-03-01 00:08:04 +0000787 // Macro definitions are stored from newest to oldest, so reverse them
788 // before registering them.
789 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000790 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000791 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
792 unsigned Size = 1;
793
794 static const uint32_t HasOverridesFlag = 0x80000000U;
795 if (I + 1 != E && (I[1] & HasOverridesFlag))
796 Size += 1 + (I[1] & ~HasOverridesFlag);
797
798 MacroSizes.push_back(Size);
799 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000800 }
Richard Smith49f906a2014-03-01 00:08:04 +0000801
802 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
803 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
804 SE = MacroSizes.rend();
805 SI != SE; ++SI) {
806 I -= *SI;
807
808 uint32_t LocalMacroID = *I;
Craig Topper00bbdcf2014-06-28 23:22:23 +0000809 ArrayRef<uint32_t> Overrides;
Richard Smith49f906a2014-03-01 00:08:04 +0000810 if (*SI != 1)
811 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
812 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
813 }
814 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000815 } else {
816 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
817 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000818 }
819
820 Reader.SetIdentifierInfo(ID, II);
821
822 // Read all of the declarations visible at global scope with this
823 // name.
824 if (DataLen > 0) {
825 SmallVector<uint32_t, 4> DeclIDs;
826 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000827 DeclIDs.push_back(Reader.getGlobalDeclID(
828 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000829 Reader.SetGloballyVisibleDecls(II, DeclIDs);
830 }
831
832 return II;
833}
834
835unsigned
836ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
837 llvm::FoldingSetNodeID ID;
838 ID.AddInteger(Key.Kind);
839
840 switch (Key.Kind) {
841 case DeclarationName::Identifier:
842 case DeclarationName::CXXLiteralOperatorName:
843 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
844 break;
845 case DeclarationName::ObjCZeroArgSelector:
846 case DeclarationName::ObjCOneArgSelector:
847 case DeclarationName::ObjCMultiArgSelector:
848 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
849 break;
850 case DeclarationName::CXXOperatorName:
851 ID.AddInteger((OverloadedOperatorKind)Key.Data);
852 break;
853 case DeclarationName::CXXConstructorName:
854 case DeclarationName::CXXDestructorName:
855 case DeclarationName::CXXConversionFunctionName:
856 case DeclarationName::CXXUsingDirective:
857 break;
858 }
859
860 return ID.ComputeHash();
861}
862
863ASTDeclContextNameLookupTrait::internal_key_type
864ASTDeclContextNameLookupTrait::GetInternalKey(
865 const external_key_type& Name) const {
866 DeclNameKey Key;
867 Key.Kind = Name.getNameKind();
868 switch (Name.getNameKind()) {
869 case DeclarationName::Identifier:
870 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
871 break;
872 case DeclarationName::ObjCZeroArgSelector:
873 case DeclarationName::ObjCOneArgSelector:
874 case DeclarationName::ObjCMultiArgSelector:
875 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
876 break;
877 case DeclarationName::CXXOperatorName:
878 Key.Data = Name.getCXXOverloadedOperator();
879 break;
880 case DeclarationName::CXXLiteralOperatorName:
881 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
882 break;
883 case DeclarationName::CXXConstructorName:
884 case DeclarationName::CXXDestructorName:
885 case DeclarationName::CXXConversionFunctionName:
886 case DeclarationName::CXXUsingDirective:
887 Key.Data = 0;
888 break;
889 }
890
891 return Key;
892}
893
894std::pair<unsigned, unsigned>
895ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000896 using namespace llvm::support;
897 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
898 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000899 return std::make_pair(KeyLen, DataLen);
900}
901
902ASTDeclContextNameLookupTrait::internal_key_type
903ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000904 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000905
906 DeclNameKey Key;
907 Key.Kind = (DeclarationName::NameKind)*d++;
908 switch (Key.Kind) {
909 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000910 Key.Data = (uint64_t)Reader.getLocalIdentifier(
911 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000912 break;
913 case DeclarationName::ObjCZeroArgSelector:
914 case DeclarationName::ObjCOneArgSelector:
915 case DeclarationName::ObjCMultiArgSelector:
916 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000917 (uint64_t)Reader.getLocalSelector(
918 F, endian::readNext<uint32_t, little, unaligned>(
919 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000920 break;
921 case DeclarationName::CXXOperatorName:
922 Key.Data = *d++; // OverloadedOperatorKind
923 break;
924 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000925 Key.Data = (uint64_t)Reader.getLocalIdentifier(
926 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000927 break;
928 case DeclarationName::CXXConstructorName:
929 case DeclarationName::CXXDestructorName:
930 case DeclarationName::CXXConversionFunctionName:
931 case DeclarationName::CXXUsingDirective:
932 Key.Data = 0;
933 break;
934 }
935
936 return Key;
937}
938
939ASTDeclContextNameLookupTrait::data_type
940ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
941 const unsigned char* d,
942 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000943 using namespace llvm::support;
944 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000945 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
946 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000947 return std::make_pair(Start, Start + NumDecls);
948}
949
950bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000951 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000952 const std::pair<uint64_t, uint64_t> &Offsets,
953 DeclContextInfo &Info) {
954 SavedStreamPosition SavedPosition(Cursor);
955 // First the lexical decls.
956 if (Offsets.first != 0) {
957 Cursor.JumpToBit(Offsets.first);
958
959 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000960 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000961 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000962 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000963 if (RecCode != DECL_CONTEXT_LEXICAL) {
964 Error("Expected lexical block");
965 return true;
966 }
967
Chris Lattner0e6c9402013-01-20 02:38:54 +0000968 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
969 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000970 }
971
972 // Now the lookup table.
973 if (Offsets.second != 0) {
974 Cursor.JumpToBit(Offsets.second);
975
976 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000977 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000978 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000979 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000980 if (RecCode != DECL_CONTEXT_VISIBLE) {
981 Error("Expected visible lookup table block");
982 return true;
983 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000984 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
985 (const unsigned char *)Blob.data() + Record[0],
986 (const unsigned char *)Blob.data() + sizeof(uint32_t),
987 (const unsigned char *)Blob.data(),
988 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +0000989 }
990
991 return false;
992}
993
994void ASTReader::Error(StringRef Msg) {
995 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +0000996 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
997 Diag(diag::note_module_cache_path)
998 << PP.getHeaderSearchInfo().getModuleCachePath();
999 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001000}
1001
1002void ASTReader::Error(unsigned DiagID,
1003 StringRef Arg1, StringRef Arg2) {
1004 if (Diags.isDiagnosticInFlight())
1005 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1006 else
1007 Diag(DiagID) << Arg1 << Arg2;
1008}
1009
1010//===----------------------------------------------------------------------===//
1011// Source Manager Deserialization
1012//===----------------------------------------------------------------------===//
1013
1014/// \brief Read the line table in the source manager block.
1015/// \returns true if there was an error.
1016bool ASTReader::ParseLineTable(ModuleFile &F,
1017 SmallVectorImpl<uint64_t> &Record) {
1018 unsigned Idx = 0;
1019 LineTableInfo &LineTable = SourceMgr.getLineTable();
1020
1021 // Parse the file names
1022 std::map<int, int> FileIDs;
1023 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1024 // Extract the file name
1025 unsigned FilenameLen = Record[Idx++];
1026 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
1027 Idx += FilenameLen;
1028 MaybeAddSystemRootToFilename(F, Filename);
1029 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1030 }
1031
1032 // Parse the line entries
1033 std::vector<LineEntry> Entries;
1034 while (Idx < Record.size()) {
1035 int FID = Record[Idx++];
1036 assert(FID >= 0 && "Serialized line entries for non-local file.");
1037 // Remap FileID from 1-based old view.
1038 FID += F.SLocEntryBaseID - 1;
1039
1040 // Extract the line entries
1041 unsigned NumEntries = Record[Idx++];
1042 assert(NumEntries && "Numentries is 00000");
1043 Entries.clear();
1044 Entries.reserve(NumEntries);
1045 for (unsigned I = 0; I != NumEntries; ++I) {
1046 unsigned FileOffset = Record[Idx++];
1047 unsigned LineNo = Record[Idx++];
1048 int FilenameID = FileIDs[Record[Idx++]];
1049 SrcMgr::CharacteristicKind FileKind
1050 = (SrcMgr::CharacteristicKind)Record[Idx++];
1051 unsigned IncludeOffset = Record[Idx++];
1052 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1053 FileKind, IncludeOffset));
1054 }
1055 LineTable.AddEntry(FileID::get(FID), Entries);
1056 }
1057
1058 return false;
1059}
1060
1061/// \brief Read a source manager block
1062bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1063 using namespace SrcMgr;
1064
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001065 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001066
1067 // Set the source-location entry cursor to the current position in
1068 // the stream. This cursor will be used to read the contents of the
1069 // source manager block initially, and then lazily read
1070 // source-location entries as needed.
1071 SLocEntryCursor = F.Stream;
1072
1073 // The stream itself is going to skip over the source manager block.
1074 if (F.Stream.SkipBlock()) {
1075 Error("malformed block record in AST file");
1076 return true;
1077 }
1078
1079 // Enter the source manager block.
1080 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1081 Error("malformed source manager block record in AST file");
1082 return true;
1083 }
1084
1085 RecordData Record;
1086 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001087 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1088
1089 switch (E.Kind) {
1090 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1091 case llvm::BitstreamEntry::Error:
1092 Error("malformed block record in AST file");
1093 return true;
1094 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001095 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001096 case llvm::BitstreamEntry::Record:
1097 // The interesting case.
1098 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001099 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001100
Guy Benyei11169dd2012-12-18 14:30:41 +00001101 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001102 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001103 StringRef Blob;
1104 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001105 default: // Default behavior: ignore.
1106 break;
1107
1108 case SM_SLOC_FILE_ENTRY:
1109 case SM_SLOC_BUFFER_ENTRY:
1110 case SM_SLOC_EXPANSION_ENTRY:
1111 // Once we hit one of the source location entries, we're done.
1112 return false;
1113 }
1114 }
1115}
1116
1117/// \brief If a header file is not found at the path that we expect it to be
1118/// and the PCH file was moved from its original location, try to resolve the
1119/// file by assuming that header+PCH were moved together and the header is in
1120/// the same place relative to the PCH.
1121static std::string
1122resolveFileRelativeToOriginalDir(const std::string &Filename,
1123 const std::string &OriginalDir,
1124 const std::string &CurrDir) {
1125 assert(OriginalDir != CurrDir &&
1126 "No point trying to resolve the file if the PCH dir didn't change");
1127 using namespace llvm::sys;
1128 SmallString<128> filePath(Filename);
1129 fs::make_absolute(filePath);
1130 assert(path::is_absolute(OriginalDir));
1131 SmallString<128> currPCHPath(CurrDir);
1132
1133 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1134 fileDirE = path::end(path::parent_path(filePath));
1135 path::const_iterator origDirI = path::begin(OriginalDir),
1136 origDirE = path::end(OriginalDir);
1137 // Skip the common path components from filePath and OriginalDir.
1138 while (fileDirI != fileDirE && origDirI != origDirE &&
1139 *fileDirI == *origDirI) {
1140 ++fileDirI;
1141 ++origDirI;
1142 }
1143 for (; origDirI != origDirE; ++origDirI)
1144 path::append(currPCHPath, "..");
1145 path::append(currPCHPath, fileDirI, fileDirE);
1146 path::append(currPCHPath, path::filename(Filename));
1147 return currPCHPath.str();
1148}
1149
1150bool ASTReader::ReadSLocEntry(int ID) {
1151 if (ID == 0)
1152 return false;
1153
1154 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1155 Error("source location entry ID out-of-range for AST file");
1156 return true;
1157 }
1158
1159 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1160 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001161 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001162 unsigned BaseOffset = F->SLocEntryBaseOffset;
1163
1164 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001165 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1166 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001167 Error("incorrectly-formatted source location entry in AST file");
1168 return true;
1169 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001170
Guy Benyei11169dd2012-12-18 14:30:41 +00001171 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001172 StringRef Blob;
1173 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001174 default:
1175 Error("incorrectly-formatted source location entry in AST file");
1176 return true;
1177
1178 case SM_SLOC_FILE_ENTRY: {
1179 // We will detect whether a file changed and return 'Failure' for it, but
1180 // we will also try to fail gracefully by setting up the SLocEntry.
1181 unsigned InputID = Record[4];
1182 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001183 const FileEntry *File = IF.getFile();
1184 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001185
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001186 // Note that we only check if a File was returned. If it was out-of-date
1187 // we have complained but we will continue creating a FileID to recover
1188 // gracefully.
1189 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001190 return true;
1191
1192 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1193 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1194 // This is the module's main file.
1195 IncludeLoc = getImportLocation(F);
1196 }
1197 SrcMgr::CharacteristicKind
1198 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1199 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1200 ID, BaseOffset + Record[0]);
1201 SrcMgr::FileInfo &FileInfo =
1202 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1203 FileInfo.NumCreatedFIDs = Record[5];
1204 if (Record[3])
1205 FileInfo.setHasLineDirectives();
1206
1207 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1208 unsigned NumFileDecls = Record[7];
1209 if (NumFileDecls) {
1210 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1211 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1212 NumFileDecls));
1213 }
1214
1215 const SrcMgr::ContentCache *ContentCache
1216 = SourceMgr.getOrCreateContentCache(File,
1217 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1218 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1219 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1220 unsigned Code = SLocEntryCursor.ReadCode();
1221 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001222 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001223
1224 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1225 Error("AST record has invalid code");
1226 return true;
1227 }
1228
1229 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001230 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00001231 SourceMgr.overrideFileContents(File, Buffer);
1232 }
1233
1234 break;
1235 }
1236
1237 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001238 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001239 unsigned Offset = Record[0];
1240 SrcMgr::CharacteristicKind
1241 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1242 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1243 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
1244 IncludeLoc = getImportLocation(F);
1245 }
1246 unsigned Code = SLocEntryCursor.ReadCode();
1247 Record.clear();
1248 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001249 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001250
1251 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1252 Error("AST record has invalid code");
1253 return true;
1254 }
1255
1256 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001257 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
Alp Toker6ac2cd02014-05-16 17:23:01 +00001258 SourceMgr.createFileID(Buffer, FileCharacter, ID, BaseOffset + Offset,
1259 IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001260 break;
1261 }
1262
1263 case SM_SLOC_EXPANSION_ENTRY: {
1264 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1265 SourceMgr.createExpansionLoc(SpellingLoc,
1266 ReadSourceLocation(*F, Record[2]),
1267 ReadSourceLocation(*F, Record[3]),
1268 Record[4],
1269 ID,
1270 BaseOffset + Record[0]);
1271 break;
1272 }
1273 }
1274
1275 return false;
1276}
1277
1278std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1279 if (ID == 0)
1280 return std::make_pair(SourceLocation(), "");
1281
1282 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1283 Error("source location entry ID out-of-range for AST file");
1284 return std::make_pair(SourceLocation(), "");
1285 }
1286
1287 // Find which module file this entry lands in.
1288 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1289 if (M->Kind != MK_Module)
1290 return std::make_pair(SourceLocation(), "");
1291
1292 // FIXME: Can we map this down to a particular submodule? That would be
1293 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001294 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001295}
1296
1297/// \brief Find the location where the module F is imported.
1298SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1299 if (F->ImportLoc.isValid())
1300 return F->ImportLoc;
1301
1302 // Otherwise we have a PCH. It's considered to be "imported" at the first
1303 // location of its includer.
1304 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001305 // Main file is the importer.
1306 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1307 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001308 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001309 return F->ImportedBy[0]->FirstLoc;
1310}
1311
1312/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1313/// specified cursor. Read the abbreviations that are at the top of the block
1314/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001315bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001316 if (Cursor.EnterSubBlock(BlockID)) {
1317 Error("malformed block record in AST file");
1318 return Failure;
1319 }
1320
1321 while (true) {
1322 uint64_t Offset = Cursor.GetCurrentBitNo();
1323 unsigned Code = Cursor.ReadCode();
1324
1325 // We expect all abbrevs to be at the start of the block.
1326 if (Code != llvm::bitc::DEFINE_ABBREV) {
1327 Cursor.JumpToBit(Offset);
1328 return false;
1329 }
1330 Cursor.ReadAbbrevRecord();
1331 }
1332}
1333
Richard Smithe40f2ba2013-08-07 21:41:30 +00001334Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001335 unsigned &Idx) {
1336 Token Tok;
1337 Tok.startToken();
1338 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1339 Tok.setLength(Record[Idx++]);
1340 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1341 Tok.setIdentifierInfo(II);
1342 Tok.setKind((tok::TokenKind)Record[Idx++]);
1343 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1344 return Tok;
1345}
1346
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001347MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001348 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001349
1350 // Keep track of where we are in the stream, then jump back there
1351 // after reading this macro.
1352 SavedStreamPosition SavedPosition(Stream);
1353
1354 Stream.JumpToBit(Offset);
1355 RecordData Record;
1356 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001357 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001358
Guy Benyei11169dd2012-12-18 14:30:41 +00001359 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001360 // Advance to the next record, but if we get to the end of the block, don't
1361 // pop it (removing all the abbreviations from the cursor) since we want to
1362 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001363 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001364 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1365
1366 switch (Entry.Kind) {
1367 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1368 case llvm::BitstreamEntry::Error:
1369 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001370 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001371 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001372 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001373 case llvm::BitstreamEntry::Record:
1374 // The interesting case.
1375 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001376 }
1377
1378 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001379 Record.clear();
1380 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001381 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001382 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001383 case PP_MACRO_DIRECTIVE_HISTORY:
1384 return Macro;
1385
Guy Benyei11169dd2012-12-18 14:30:41 +00001386 case PP_MACRO_OBJECT_LIKE:
1387 case PP_MACRO_FUNCTION_LIKE: {
1388 // If we already have a macro, that means that we've hit the end
1389 // of the definition of the macro we were looking for. We're
1390 // done.
1391 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001392 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001393
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001394 unsigned NextIndex = 1; // Skip identifier ID.
1395 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001396 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001397 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001398 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001399 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001400 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001401
Guy Benyei11169dd2012-12-18 14:30:41 +00001402 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1403 // Decode function-like macro info.
1404 bool isC99VarArgs = Record[NextIndex++];
1405 bool isGNUVarArgs = Record[NextIndex++];
1406 bool hasCommaPasting = Record[NextIndex++];
1407 MacroArgs.clear();
1408 unsigned NumArgs = Record[NextIndex++];
1409 for (unsigned i = 0; i != NumArgs; ++i)
1410 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1411
1412 // Install function-like macro info.
1413 MI->setIsFunctionLike();
1414 if (isC99VarArgs) MI->setIsC99Varargs();
1415 if (isGNUVarArgs) MI->setIsGNUVarargs();
1416 if (hasCommaPasting) MI->setHasCommaPasting();
1417 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1418 PP.getPreprocessorAllocator());
1419 }
1420
Guy Benyei11169dd2012-12-18 14:30:41 +00001421 // Remember that we saw this macro last so that we add the tokens that
1422 // form its body to it.
1423 Macro = MI;
1424
1425 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1426 Record[NextIndex]) {
1427 // We have a macro definition. Register the association
1428 PreprocessedEntityID
1429 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1430 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001431 PreprocessingRecord::PPEntityID
1432 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1433 MacroDefinition *PPDef =
1434 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1435 if (PPDef)
1436 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001437 }
1438
1439 ++NumMacrosRead;
1440 break;
1441 }
1442
1443 case PP_TOKEN: {
1444 // If we see a TOKEN before a PP_MACRO_*, then the file is
1445 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001446 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001447
John McCallf413f5e2013-05-03 00:10:13 +00001448 unsigned Idx = 0;
1449 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001450 Macro->AddTokenToBody(Tok);
1451 break;
1452 }
1453 }
1454 }
1455}
1456
1457PreprocessedEntityID
1458ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1459 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1460 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1461 assert(I != M.PreprocessedEntityRemap.end()
1462 && "Invalid index into preprocessed entity index remap");
1463
1464 return LocalID + I->second;
1465}
1466
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001467unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1468 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001469}
1470
1471HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001472HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1473 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1474 FE->getName() };
1475 return ikey;
1476}
Guy Benyei11169dd2012-12-18 14:30:41 +00001477
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001478bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1479 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001480 return false;
1481
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001482 if (strcmp(a.Filename, b.Filename) == 0)
1483 return true;
1484
Guy Benyei11169dd2012-12-18 14:30:41 +00001485 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001486 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001487 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1488 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001489 return (FEA && FEA == FEB);
Guy Benyei11169dd2012-12-18 14:30:41 +00001490}
1491
1492std::pair<unsigned, unsigned>
1493HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001494 using namespace llvm::support;
1495 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001496 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001497 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001498}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001499
1500HeaderFileInfoTrait::internal_key_type
1501HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001502 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001503 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001504 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1505 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001506 ikey.Filename = (const char *)d;
1507 return ikey;
1508}
1509
Guy Benyei11169dd2012-12-18 14:30:41 +00001510HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001511HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001512 unsigned DataLen) {
1513 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001514 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001515 HeaderFileInfo HFI;
1516 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001517 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1518 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001519 HFI.isImport = (Flags >> 5) & 0x01;
1520 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1521 HFI.DirInfo = (Flags >> 2) & 0x03;
1522 HFI.Resolved = (Flags >> 1) & 0x01;
1523 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001524 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1525 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1526 M, endian::readNext<uint32_t, little, unaligned>(d));
1527 if (unsigned FrameworkOffset =
1528 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001529 // The framework offset is 1 greater than the actual offset,
1530 // since 0 is used as an indicator for "no framework name".
1531 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1532 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1533 }
1534
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001535 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001536 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001537 if (LocalSMID) {
1538 // This header is part of a module. Associate it with the module to enable
1539 // implicit module import.
1540 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1541 Module *Mod = Reader.getSubmodule(GlobalSMID);
1542 HFI.isModuleHeader = true;
1543 FileManager &FileMgr = Reader.getFileManager();
1544 ModuleMap &ModMap =
1545 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001546 ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001547 }
1548 }
1549
Guy Benyei11169dd2012-12-18 14:30:41 +00001550 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1551 (void)End;
1552
1553 // This HeaderFileInfo was externally loaded.
1554 HFI.External = true;
1555 return HFI;
1556}
1557
Richard Smith49f906a2014-03-01 00:08:04 +00001558void
1559ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1560 GlobalMacroID GMacID,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001561 ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001562 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Craig Toppera13603a2014-05-22 05:54:18 +00001563 SubmoduleID *OverrideData = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001564 if (!Overrides.empty()) {
1565 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1566 OverrideData[0] = Overrides.size();
1567 for (unsigned I = 0; I != Overrides.size(); ++I)
1568 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1569 }
1570 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001571}
1572
1573void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1574 ModuleFile *M,
1575 uint64_t MacroDirectivesOffset) {
1576 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1577 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001578}
1579
1580void ASTReader::ReadDefinedMacros() {
1581 // Note that we are loading defined macros.
1582 Deserializing Macros(this);
1583
1584 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1585 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001586 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001587
1588 // If there was no preprocessor block, skip this file.
1589 if (!MacroCursor.getBitStreamReader())
1590 continue;
1591
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001592 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001593 Cursor.JumpToBit((*I)->MacroStartOffset);
1594
1595 RecordData Record;
1596 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001597 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1598
1599 switch (E.Kind) {
1600 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1601 case llvm::BitstreamEntry::Error:
1602 Error("malformed block record in AST file");
1603 return;
1604 case llvm::BitstreamEntry::EndBlock:
1605 goto NextCursor;
1606
1607 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001608 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001609 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001610 default: // Default behavior: ignore.
1611 break;
1612
1613 case PP_MACRO_OBJECT_LIKE:
1614 case PP_MACRO_FUNCTION_LIKE:
1615 getLocalIdentifier(**I, Record[0]);
1616 break;
1617
1618 case PP_TOKEN:
1619 // Ignore tokens.
1620 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001621 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001622 break;
1623 }
1624 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001625 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001626 }
1627}
1628
1629namespace {
1630 /// \brief Visitor class used to look up identifirs in an AST file.
1631 class IdentifierLookupVisitor {
1632 StringRef Name;
1633 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001634 unsigned &NumIdentifierLookups;
1635 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001636 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001637
Guy Benyei11169dd2012-12-18 14:30:41 +00001638 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001639 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1640 unsigned &NumIdentifierLookups,
1641 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001642 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001643 NumIdentifierLookups(NumIdentifierLookups),
1644 NumIdentifierLookupHits(NumIdentifierLookupHits),
1645 Found()
1646 {
1647 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001648
1649 static bool visit(ModuleFile &M, void *UserData) {
1650 IdentifierLookupVisitor *This
1651 = static_cast<IdentifierLookupVisitor *>(UserData);
1652
1653 // If we've already searched this module file, skip it now.
1654 if (M.Generation <= This->PriorGeneration)
1655 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001656
Guy Benyei11169dd2012-12-18 14:30:41 +00001657 ASTIdentifierLookupTable *IdTable
1658 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1659 if (!IdTable)
1660 return false;
1661
1662 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1663 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001664 ++This->NumIdentifierLookups;
1665 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001666 if (Pos == IdTable->end())
1667 return false;
1668
1669 // Dereferencing the iterator has the effect of building the
1670 // IdentifierInfo node and populating it with the various
1671 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001672 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001673 This->Found = *Pos;
1674 return true;
1675 }
1676
1677 // \brief Retrieve the identifier info found within the module
1678 // files.
1679 IdentifierInfo *getIdentifierInfo() const { return Found; }
1680 };
1681}
1682
1683void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1684 // Note that we are loading an identifier.
1685 Deserializing AnIdentifier(this);
1686
1687 unsigned PriorGeneration = 0;
1688 if (getContext().getLangOpts().Modules)
1689 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001690
1691 // If there is a global index, look there first to determine which modules
1692 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001693 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001694 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001695 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001696 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1697 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001698 }
1699 }
1700
Douglas Gregor7211ac12013-01-25 23:32:03 +00001701 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001702 NumIdentifierLookups,
1703 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001704 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001705 markIdentifierUpToDate(&II);
1706}
1707
1708void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1709 if (!II)
1710 return;
1711
1712 II->setOutOfDate(false);
1713
1714 // Update the generation for this identifier.
1715 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001716 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001717}
1718
Richard Smith49f906a2014-03-01 00:08:04 +00001719struct ASTReader::ModuleMacroInfo {
1720 SubmoduleID SubModID;
1721 MacroInfo *MI;
1722 SubmoduleID *Overrides;
1723 // FIXME: Remove this.
1724 ModuleFile *F;
1725
1726 bool isDefine() const { return MI; }
1727
1728 SubmoduleID getSubmoduleID() const { return SubModID; }
1729
Craig Topper00bbdcf2014-06-28 23:22:23 +00001730 ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
Richard Smith49f906a2014-03-01 00:08:04 +00001731 if (!Overrides)
Craig Topper00bbdcf2014-06-28 23:22:23 +00001732 return None;
Richard Smith49f906a2014-03-01 00:08:04 +00001733 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1734 }
1735
Richard Smithdaa69e02014-07-25 04:40:03 +00001736 MacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
Richard Smith49f906a2014-03-01 00:08:04 +00001737 if (!MI)
Richard Smithdaa69e02014-07-25 04:40:03 +00001738 return PP.AllocateUndefMacroDirective(ImportLoc, SubModID,
1739 getOverriddenSubmodules());
1740 return PP.AllocateDefMacroDirective(MI, ImportLoc, SubModID,
1741 getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00001742 }
1743};
1744
1745ASTReader::ModuleMacroInfo *
1746ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1747 ModuleMacroInfo Info;
1748
1749 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1750 if (ID & 1) {
1751 // Macro undefinition.
1752 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
Craig Toppera13603a2014-05-22 05:54:18 +00001753 Info.MI = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001754 } else {
1755 // Macro definition.
1756 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1757 assert(GMacID);
1758
1759 // If this macro has already been loaded, don't do so again.
1760 // FIXME: This is highly dubious. Multiple macro definitions can have the
1761 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1762 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
Craig Toppera13603a2014-05-22 05:54:18 +00001763 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001764
1765 Info.MI = getMacro(GMacID);
1766 Info.SubModID = Info.MI->getOwningModuleID();
1767 }
1768 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1769 Info.F = PMInfo.M;
1770
1771 return new (Context) ModuleMacroInfo(Info);
1772}
1773
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001774void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1775 const PendingMacroInfo &PMInfo) {
1776 assert(II);
1777
1778 if (PMInfo.M->Kind != MK_Module) {
1779 installPCHMacroDirectives(II, *PMInfo.M,
1780 PMInfo.PCHMacroData.MacroDirectivesOffset);
1781 return;
1782 }
Richard Smith49f906a2014-03-01 00:08:04 +00001783
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001784 // Module Macro.
1785
Richard Smith49f906a2014-03-01 00:08:04 +00001786 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1787 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001788 return;
1789
Richard Smith49f906a2014-03-01 00:08:04 +00001790 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1791 if (Owner && Owner->NameVisibility == Module::Hidden) {
1792 // Macros in the owning module are hidden. Just remember this macro to
1793 // install if we make this module visible.
1794 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1795 } else {
Richard Smithdaa69e02014-07-25 04:40:03 +00001796 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001797 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001798}
1799
1800void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1801 ModuleFile &M, uint64_t Offset) {
1802 assert(M.Kind != MK_Module);
1803
1804 BitstreamCursor &Cursor = M.MacroCursor;
1805 SavedStreamPosition SavedPosition(Cursor);
1806 Cursor.JumpToBit(Offset);
1807
1808 llvm::BitstreamEntry Entry =
1809 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1810 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1811 Error("malformed block record in AST file");
1812 return;
1813 }
1814
1815 RecordData Record;
1816 PreprocessorRecordTypes RecType =
1817 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1818 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1819 Error("malformed block record in AST file");
1820 return;
1821 }
1822
1823 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001824 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001825 unsigned Idx = 0, N = Record.size();
1826 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001827 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001828 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001829 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1830 switch (K) {
1831 case MacroDirective::MD_Define: {
1832 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1833 MacroInfo *MI = getMacro(GMacID);
Richard Smithdaa69e02014-07-25 04:40:03 +00001834 SubmoduleID ImportedFrom = Record[Idx++];
1835 bool IsAmbiguous = Record[Idx++];
1836 llvm::SmallVector<unsigned, 4> Overrides;
1837 if (ImportedFrom) {
1838 Overrides.insert(Overrides.end(),
1839 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1840 Idx += Overrides.size() + 1;
1841 }
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001842 DefMacroDirective *DefMD =
Richard Smithdaa69e02014-07-25 04:40:03 +00001843 PP.AllocateDefMacroDirective(MI, Loc, ImportedFrom, Overrides);
1844 DefMD->setAmbiguous(IsAmbiguous);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001845 MD = DefMD;
1846 break;
1847 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001848 case MacroDirective::MD_Undefine: {
1849 SubmoduleID ImportedFrom = Record[Idx++];
1850 llvm::SmallVector<unsigned, 4> Overrides;
1851 if (ImportedFrom) {
1852 Overrides.insert(Overrides.end(),
1853 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1854 Idx += Overrides.size() + 1;
1855 }
1856 MD = PP.AllocateUndefMacroDirective(Loc, ImportedFrom, Overrides);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001857 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001858 }
1859 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001860 bool isPublic = Record[Idx++];
1861 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1862 break;
1863 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001864
1865 if (!Latest)
1866 Latest = MD;
1867 if (Earliest)
1868 Earliest->setPrevious(MD);
1869 Earliest = MD;
1870 }
1871
1872 PP.setLoadedMacroDirective(II, Latest);
1873}
1874
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001875/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001876/// modules.
1877static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001878 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001879 assert(PrevMI && NewMI);
Craig Toppera13603a2014-05-22 05:54:18 +00001880 Module *PrevOwner = nullptr;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001881 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1882 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001883 SourceManager &SrcMgr = Reader.getSourceManager();
1884 bool PrevInSystem
1885 = PrevOwner? PrevOwner->IsSystem
1886 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1887 bool NewInSystem
1888 = NewOwner? NewOwner->IsSystem
1889 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1890 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001891 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001892 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001893}
1894
Richard Smith49f906a2014-03-01 00:08:04 +00001895void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001896 SourceLocation ImportLoc,
Richard Smith49f906a2014-03-01 00:08:04 +00001897 AmbiguousMacros &Ambig,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001898 ArrayRef<SubmoduleID> Overrides) {
Richard Smith49f906a2014-03-01 00:08:04 +00001899 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1900 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001901
Richard Smith49f906a2014-03-01 00:08:04 +00001902 // If this macro is not yet visible, remove it from the hidden names list.
1903 Module *Owner = getSubmodule(OwnerID);
1904 HiddenNames &Hidden = HiddenNamesMap[Owner];
1905 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1906 if (HI != Hidden.HiddenMacros.end()) {
Richard Smithdaa69e02014-07-25 04:40:03 +00001907 // Register the macro now so we don't lose it when we re-export.
1908 PP.appendMacroDirective(II, HI->second->import(PP, ImportLoc));
1909
Richard Smith9d100862014-03-06 03:16:27 +00001910 auto SubOverrides = HI->second->getOverriddenSubmodules();
Richard Smith49f906a2014-03-01 00:08:04 +00001911 Hidden.HiddenMacros.erase(HI);
Richard Smithdaa69e02014-07-25 04:40:03 +00001912 removeOverriddenMacros(II, ImportLoc, Ambig, SubOverrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001913 }
1914
1915 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001916 Ambig.erase(
1917 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1918 return MD->getInfo()->getOwningModuleID() == OwnerID;
1919 }),
1920 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001921 }
1922}
1923
1924ASTReader::AmbiguousMacros *
1925ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001926 SourceLocation ImportLoc,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001927 ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001928 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001929 if (!Prev && Overrides.empty())
Craig Toppera13603a2014-05-22 05:54:18 +00001930 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001931
Craig Toppera13603a2014-05-22 05:54:18 +00001932 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective()
1933 : nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001934 if (PrevDef && PrevDef->isAmbiguous()) {
1935 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1936 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1937 Ambig.push_back(PrevDef);
1938
Richard Smithdaa69e02014-07-25 04:40:03 +00001939 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001940
1941 if (!Ambig.empty())
1942 return &Ambig;
1943
1944 AmbiguousMacroDefs.erase(II);
1945 } else {
1946 // There's no ambiguity yet. Maybe we're introducing one.
Benjamin Kramer834652a2014-05-03 18:44:26 +00001947 AmbiguousMacros Ambig;
Richard Smith49f906a2014-03-01 00:08:04 +00001948 if (PrevDef)
1949 Ambig.push_back(PrevDef);
1950
Richard Smithdaa69e02014-07-25 04:40:03 +00001951 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001952
1953 if (!Ambig.empty()) {
1954 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
Benjamin Kramer834652a2014-05-03 18:44:26 +00001955 std::swap(Result, Ambig);
Richard Smith49f906a2014-03-01 00:08:04 +00001956 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001957 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001958 }
Richard Smith49f906a2014-03-01 00:08:04 +00001959
1960 // We ended up with no ambiguity.
Craig Toppera13603a2014-05-22 05:54:18 +00001961 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001962}
1963
1964void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
Richard Smithdaa69e02014-07-25 04:40:03 +00001965 Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00001966 assert(II && Owner);
1967
1968 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
Richard Smithdaa69e02014-07-25 04:40:03 +00001969 if (ImportLoc.isInvalid()) {
Richard Smith49f906a2014-03-01 00:08:04 +00001970 // FIXME: If we made macros from this module visible but didn't provide a
1971 // source location for the import, we don't have a location for the macro.
1972 // Use the location at which the containing module file was first imported
1973 // for now.
1974 ImportLoc = MMI->F->DirectImportLoc;
Richard Smith56be7542014-03-21 00:33:59 +00001975 assert(ImportLoc.isValid() && "no import location for a visible macro?");
Richard Smith49f906a2014-03-01 00:08:04 +00001976 }
1977
Benjamin Kramer834652a2014-05-03 18:44:26 +00001978 AmbiguousMacros *Prev =
Richard Smithdaa69e02014-07-25 04:40:03 +00001979 removeOverriddenMacros(II, ImportLoc, MMI->getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00001980
Richard Smith49f906a2014-03-01 00:08:04 +00001981 // Create a synthetic macro definition corresponding to the import (or null
1982 // if this was an undefinition of the macro).
Richard Smithdaa69e02014-07-25 04:40:03 +00001983 MacroDirective *Imported = MMI->import(PP, ImportLoc);
1984 DefMacroDirective *MD = dyn_cast<DefMacroDirective>(Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00001985
1986 // If there's no ambiguity, just install the macro.
1987 if (!Prev) {
Richard Smithdaa69e02014-07-25 04:40:03 +00001988 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00001989 return;
1990 }
1991 assert(!Prev->empty());
1992
1993 if (!MD) {
1994 // We imported a #undef that didn't remove all prior definitions. The most
1995 // recent prior definition remains, and we install it in the place of the
Richard Smithdaa69e02014-07-25 04:40:03 +00001996 // imported directive, as if by a local #pragma pop_macro.
Richard Smith49f906a2014-03-01 00:08:04 +00001997 MacroInfo *NewMI = Prev->back()->getInfo();
1998 Prev->pop_back();
Richard Smithdaa69e02014-07-25 04:40:03 +00001999 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc);
2000
2001 // Install our #undef first so that we don't lose track of it. We'll replace
2002 // this with whichever macro definition ends up winning.
2003 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002004 }
2005
2006 // We're introducing a macro definition that creates or adds to an ambiguity.
2007 // We can resolve that ambiguity if this macro is token-for-token identical to
2008 // all of the existing definitions.
2009 MacroInfo *NewMI = MD->getInfo();
2010 assert(NewMI && "macro definition with no MacroInfo?");
2011 while (!Prev->empty()) {
2012 MacroInfo *PrevMI = Prev->back()->getInfo();
2013 assert(PrevMI && "macro definition with no MacroInfo?");
2014
2015 // Before marking the macros as ambiguous, check if this is a case where
2016 // both macros are in system headers. If so, we trust that the system
2017 // did not get it wrong. This also handles cases where Clang's own
2018 // headers have a different spelling of certain system macros:
2019 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
2020 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
2021 //
2022 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
2023 // overrides the system limits.h's macros, so there's no conflict here.
2024 if (NewMI != PrevMI &&
2025 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
2026 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
2027 break;
2028
2029 // The previous definition is the same as this one (or both are defined in
2030 // system modules so we can assume they're equivalent); we don't need to
2031 // track it any more.
2032 Prev->pop_back();
2033 }
2034
2035 if (!Prev->empty())
2036 MD->setAmbiguous(true);
2037
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002038 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002039}
2040
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002041ASTReader::InputFileInfo
2042ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002043 // Go find this input file.
2044 BitstreamCursor &Cursor = F.InputFilesCursor;
2045 SavedStreamPosition SavedPosition(Cursor);
2046 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2047
2048 unsigned Code = Cursor.ReadCode();
2049 RecordData Record;
2050 StringRef Blob;
2051
2052 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2053 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2054 "invalid record type for input file");
2055 (void)Result;
2056
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002057 std::string Filename;
2058 off_t StoredSize;
2059 time_t StoredTime;
2060 bool Overridden;
2061
Ben Langmuir198c1682014-03-07 07:27:49 +00002062 assert(Record[0] == ID && "Bogus stored ID or offset");
2063 StoredSize = static_cast<off_t>(Record[1]);
2064 StoredTime = static_cast<time_t>(Record[2]);
2065 Overridden = static_cast<bool>(Record[3]);
2066 Filename = Blob;
2067 MaybeAddSystemRootToFilename(F, Filename);
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002068
Hans Wennborg73945142014-03-14 17:45:06 +00002069 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
2070 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002071}
2072
2073std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002074 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00002075}
2076
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002077InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002078 // If this ID is bogus, just return an empty input file.
2079 if (ID == 0 || ID > F.InputFilesLoaded.size())
2080 return InputFile();
2081
2082 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002083 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002084 return F.InputFilesLoaded[ID-1];
2085
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002086 if (F.InputFilesLoaded[ID-1].isNotFound())
2087 return InputFile();
2088
Guy Benyei11169dd2012-12-18 14:30:41 +00002089 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002090 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002091 SavedStreamPosition SavedPosition(Cursor);
2092 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2093
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002094 InputFileInfo FI = readInputFileInfo(F, ID);
2095 off_t StoredSize = FI.StoredSize;
2096 time_t StoredTime = FI.StoredTime;
2097 bool Overridden = FI.Overridden;
2098 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002099
Ben Langmuir198c1682014-03-07 07:27:49 +00002100 const FileEntry *File
2101 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
2102 : FileMgr.getFile(Filename, /*OpenFile=*/false);
2103
2104 // If we didn't find the file, resolve it relative to the
2105 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002106 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002107 F.OriginalDir != CurrentDir) {
2108 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2109 F.OriginalDir,
2110 CurrentDir);
2111 if (!Resolved.empty())
2112 File = FileMgr.getFile(Resolved);
2113 }
2114
2115 // For an overridden file, create a virtual file with the stored
2116 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00002117 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002118 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2119 }
2120
Craig Toppera13603a2014-05-22 05:54:18 +00002121 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002122 if (Complain) {
2123 std::string ErrorStr = "could not find file '";
2124 ErrorStr += Filename;
2125 ErrorStr += "' referenced by AST file";
2126 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00002127 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002128 // Record that we didn't find the file.
2129 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2130 return InputFile();
2131 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002132
Ben Langmuir198c1682014-03-07 07:27:49 +00002133 // Check if there was a request to override the contents of the file
2134 // that was part of the precompiled header. Overridding such a file
2135 // can lead to problems when lexing using the source locations from the
2136 // PCH.
2137 SourceManager &SM = getSourceManager();
2138 if (!Overridden && SM.isFileOverridden(File)) {
2139 if (Complain)
2140 Error(diag::err_fe_pch_file_overridden, Filename);
2141 // After emitting the diagnostic, recover by disabling the override so
2142 // that the original file will be used.
2143 SM.disableFileContentsOverride(File);
2144 // The FileEntry is a virtual file entry with the size of the contents
2145 // that would override the original contents. Set it to the original's
2146 // size/time.
2147 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2148 StoredSize, StoredTime);
2149 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002150
Ben Langmuir198c1682014-03-07 07:27:49 +00002151 bool IsOutOfDate = false;
2152
2153 // For an overridden file, there is nothing to validate.
2154 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei11169dd2012-12-18 14:30:41 +00002155#if !defined(LLVM_ON_WIN32)
Ben Langmuir198c1682014-03-07 07:27:49 +00002156 // In our regression testing, the Windows file system seems to
2157 // have inconsistent modification times that sometimes
2158 // erroneously trigger this error-handling path.
2159 || StoredTime != File->getModificationTime()
Guy Benyei11169dd2012-12-18 14:30:41 +00002160#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002161 )) {
2162 if (Complain) {
2163 // Build a list of the PCH imports that got us here (in reverse).
2164 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2165 while (ImportStack.back()->ImportedBy.size() > 0)
2166 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002167
Ben Langmuir198c1682014-03-07 07:27:49 +00002168 // The top-level PCH is stale.
2169 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2170 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002171
Ben Langmuir198c1682014-03-07 07:27:49 +00002172 // Print the import stack.
2173 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2174 Diag(diag::note_pch_required_by)
2175 << Filename << ImportStack[0]->FileName;
2176 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002177 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002178 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002179 }
2180
Ben Langmuir198c1682014-03-07 07:27:49 +00002181 if (!Diags.isDiagnosticInFlight())
2182 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002183 }
2184
Ben Langmuir198c1682014-03-07 07:27:49 +00002185 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002186 }
2187
Ben Langmuir198c1682014-03-07 07:27:49 +00002188 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2189
2190 // Note that we've loaded this input file.
2191 F.InputFilesLoaded[ID-1] = IF;
2192 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002193}
2194
2195const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
2196 ModuleFile &M = ModuleMgr.getPrimaryModule();
2197 std::string Filename = filenameStrRef;
2198 MaybeAddSystemRootToFilename(M, Filename);
2199 const FileEntry *File = FileMgr.getFile(Filename);
Craig Toppera13603a2014-05-22 05:54:18 +00002200 if (File == nullptr && !M.OriginalDir.empty() && !CurrentDir.empty() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002201 M.OriginalDir != CurrentDir) {
2202 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
2203 M.OriginalDir,
2204 CurrentDir);
2205 if (!resolved.empty())
2206 File = FileMgr.getFile(resolved);
2207 }
2208
2209 return File;
2210}
2211
2212/// \brief If we are loading a relocatable PCH file, and the filename is
2213/// not an absolute path, add the system root to the beginning of the file
2214/// name.
2215void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
2216 std::string &Filename) {
2217 // If this is not a relocatable PCH file, there's nothing to do.
2218 if (!M.RelocatablePCH)
2219 return;
2220
2221 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2222 return;
2223
2224 if (isysroot.empty()) {
2225 // If no system root was given, default to '/'
2226 Filename.insert(Filename.begin(), '/');
2227 return;
2228 }
2229
2230 unsigned Length = isysroot.size();
2231 if (isysroot[Length - 1] != '/')
2232 Filename.insert(Filename.begin(), '/');
2233
2234 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
2235}
2236
2237ASTReader::ASTReadResult
2238ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002239 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002240 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002241 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002242 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002243
2244 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2245 Error("malformed block record in AST file");
2246 return Failure;
2247 }
2248
2249 // Read all of the records and blocks in the control block.
2250 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002251 while (1) {
2252 llvm::BitstreamEntry Entry = Stream.advance();
2253
2254 switch (Entry.Kind) {
2255 case llvm::BitstreamEntry::Error:
2256 Error("malformed block record in AST file");
2257 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002258 case llvm::BitstreamEntry::EndBlock: {
2259 // Validate input files.
2260 const HeaderSearchOptions &HSOpts =
2261 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002262
2263 // All user input files reside at the index range [0, Record[1]), and
2264 // system input files reside at [Record[1], Record[0]).
2265 // Record is the one from INPUT_FILE_OFFSETS.
2266 unsigned NumInputs = Record[0];
2267 unsigned NumUserInputs = Record[1];
2268
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002269 if (!DisableValidation &&
Ben Langmuir1e258222014-04-08 15:36:28 +00002270 (ValidateSystemInputs || !HSOpts.ModulesValidateOncePerBuildSession ||
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002271 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002272 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002273
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002274 // If we are reading a module, we will create a verification timestamp,
2275 // so we verify all input files. Otherwise, verify only user input
2276 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002277
2278 unsigned N = NumUserInputs;
2279 if (ValidateSystemInputs ||
Ben Langmuircb69b572014-03-07 06:40:32 +00002280 (HSOpts.ModulesValidateOncePerBuildSession && F.Kind == MK_Module))
2281 N = NumInputs;
2282
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002283 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002284 InputFile IF = getInputFile(F, I+1, Complain);
2285 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002286 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002287 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002288 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002289
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002290 if (Listener)
2291 Listener->visitModuleFile(F.FileName);
2292
Ben Langmuircb69b572014-03-07 06:40:32 +00002293 if (Listener && Listener->needsInputFileVisitation()) {
2294 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2295 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002296 for (unsigned I = 0; I < N; ++I) {
2297 bool IsSystem = I >= NumUserInputs;
2298 InputFileInfo FI = readInputFileInfo(F, I+1);
2299 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2300 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002301 }
2302
Guy Benyei11169dd2012-12-18 14:30:41 +00002303 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002304 }
2305
Chris Lattnere7b154b2013-01-19 21:39:22 +00002306 case llvm::BitstreamEntry::SubBlock:
2307 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002308 case INPUT_FILES_BLOCK_ID:
2309 F.InputFilesCursor = Stream;
2310 if (Stream.SkipBlock() || // Skip with the main cursor
2311 // Read the abbreviations
2312 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2313 Error("malformed block record in AST file");
2314 return Failure;
2315 }
2316 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002317
Guy Benyei11169dd2012-12-18 14:30:41 +00002318 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002319 if (Stream.SkipBlock()) {
2320 Error("malformed block record in AST file");
2321 return Failure;
2322 }
2323 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002324 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002325
2326 case llvm::BitstreamEntry::Record:
2327 // The interesting case.
2328 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002329 }
2330
2331 // Read and process a record.
2332 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002333 StringRef Blob;
2334 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002335 case METADATA: {
2336 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2337 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002338 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2339 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002340 return VersionMismatch;
2341 }
2342
2343 bool hasErrors = Record[5];
2344 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2345 Diag(diag::err_pch_with_compiler_errors);
2346 return HadErrors;
2347 }
2348
2349 F.RelocatablePCH = Record[4];
2350
2351 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002352 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002353 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2354 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002355 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002356 return VersionMismatch;
2357 }
2358 break;
2359 }
2360
2361 case IMPORTS: {
2362 // Load each of the imported PCH files.
2363 unsigned Idx = 0, N = Record.size();
2364 while (Idx < N) {
2365 // Read information about the AST file.
2366 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2367 // The import location will be the local one for now; we will adjust
2368 // all import locations of module imports after the global source
2369 // location info are setup.
2370 SourceLocation ImportLoc =
2371 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002372 off_t StoredSize = (off_t)Record[Idx++];
2373 time_t StoredModTime = (time_t)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002374 unsigned Length = Record[Idx++];
2375 SmallString<128> ImportedFile(Record.begin() + Idx,
2376 Record.begin() + Idx + Length);
2377 Idx += Length;
2378
2379 // Load the AST file.
2380 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00002381 StoredSize, StoredModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00002382 ClientLoadCapabilities)) {
2383 case Failure: return Failure;
2384 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002385 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002386 case OutOfDate: return OutOfDate;
2387 case VersionMismatch: return VersionMismatch;
2388 case ConfigurationMismatch: return ConfigurationMismatch;
2389 case HadErrors: return HadErrors;
2390 case Success: break;
2391 }
2392 }
2393 break;
2394 }
2395
2396 case LANGUAGE_OPTIONS: {
2397 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2398 if (Listener && &F == *ModuleMgr.begin() &&
2399 ParseLanguageOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002400 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002401 return ConfigurationMismatch;
2402 break;
2403 }
2404
2405 case TARGET_OPTIONS: {
2406 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2407 if (Listener && &F == *ModuleMgr.begin() &&
2408 ParseTargetOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002409 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002410 return ConfigurationMismatch;
2411 break;
2412 }
2413
2414 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002415 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002416 if (Listener && &F == *ModuleMgr.begin() &&
2417 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002418 !DisableValidation)
2419 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002420 break;
2421 }
2422
2423 case FILE_SYSTEM_OPTIONS: {
2424 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2425 if (Listener && &F == *ModuleMgr.begin() &&
2426 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002427 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002428 return ConfigurationMismatch;
2429 break;
2430 }
2431
2432 case HEADER_SEARCH_OPTIONS: {
2433 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2434 if (Listener && &F == *ModuleMgr.begin() &&
2435 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002436 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002437 return ConfigurationMismatch;
2438 break;
2439 }
2440
2441 case PREPROCESSOR_OPTIONS: {
2442 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2443 if (Listener && &F == *ModuleMgr.begin() &&
2444 ParsePreprocessorOptions(Record, Complain, *Listener,
2445 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002446 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002447 return ConfigurationMismatch;
2448 break;
2449 }
2450
2451 case ORIGINAL_FILE:
2452 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002453 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002454 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2455 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
2456 break;
2457
2458 case ORIGINAL_FILE_ID:
2459 F.OriginalSourceFileID = FileID::get(Record[0]);
2460 break;
2461
2462 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002463 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002464 break;
2465
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002466 case MODULE_NAME:
2467 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002468 if (Listener)
2469 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002470 break;
2471
2472 case MODULE_MAP_FILE:
2473 F.ModuleMapPath = Blob;
2474
2475 // Try to resolve ModuleName in the current header search context and
2476 // verify that it is found in the same module map file as we saved. If the
2477 // top-level AST file is a main file, skip this check because there is no
2478 // usable header search context.
2479 assert(!F.ModuleName.empty() &&
2480 "MODULE_NAME should come before MOUDLE_MAP_FILE");
2481 if (F.Kind == MK_Module &&
2482 (*ModuleMgr.begin())->Kind != MK_MainFile) {
2483 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2484 if (!M) {
2485 assert(ImportedBy && "top-level import should be verified");
2486 if ((ClientLoadCapabilities & ARR_Missing) == 0)
2487 Diag(diag::err_imported_module_not_found)
2488 << F.ModuleName << ImportedBy->FileName;
2489 return Missing;
2490 }
2491
2492 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
2493 if (StoredModMap == nullptr || StoredModMap != M->ModuleMap) {
2494 assert(M->ModuleMap && "found module is missing module map file");
2495 assert(M->Name == F.ModuleName && "found module with different name");
2496 assert(ImportedBy && "top-level import should be verified");
2497 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2498 Diag(diag::err_imported_module_modmap_changed)
2499 << F.ModuleName << ImportedBy->FileName
2500 << M->ModuleMap->getName() << F.ModuleMapPath;
2501 return OutOfDate;
2502 }
2503 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002504
2505 if (Listener)
2506 Listener->ReadModuleMapFile(F.ModuleMapPath);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002507 break;
2508
Guy Benyei11169dd2012-12-18 14:30:41 +00002509 case INPUT_FILE_OFFSETS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002510 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002511 F.InputFilesLoaded.resize(Record[0]);
2512 break;
2513 }
2514 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002515}
2516
Ben Langmuir2c9af442014-04-10 17:57:43 +00002517ASTReader::ASTReadResult
2518ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002519 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002520
2521 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2522 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002523 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002524 }
2525
2526 // Read all of the records and blocks for the AST file.
2527 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002528 while (1) {
2529 llvm::BitstreamEntry Entry = Stream.advance();
2530
2531 switch (Entry.Kind) {
2532 case llvm::BitstreamEntry::Error:
2533 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002534 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002535 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002536 // Outside of C++, we do not store a lookup map for the translation unit.
2537 // Instead, mark it as needing a lookup map to be built if this module
2538 // contains any declarations lexically within it (which it always does!).
2539 // This usually has no cost, since we very rarely need the lookup map for
2540 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002541 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002542 if (DC->hasExternalLexicalStorage() &&
2543 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002544 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002545
Ben Langmuir2c9af442014-04-10 17:57:43 +00002546 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002547 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002548 case llvm::BitstreamEntry::SubBlock:
2549 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002550 case DECLTYPES_BLOCK_ID:
2551 // We lazily load the decls block, but we want to set up the
2552 // DeclsCursor cursor to point into it. Clone our current bitcode
2553 // cursor to it, enter the block and read the abbrevs in that block.
2554 // With the main cursor, we just skip over it.
2555 F.DeclsCursor = Stream;
2556 if (Stream.SkipBlock() || // Skip with the main cursor.
2557 // Read the abbrevs.
2558 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2559 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002560 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002561 }
2562 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002563
Guy Benyei11169dd2012-12-18 14:30:41 +00002564 case PREPROCESSOR_BLOCK_ID:
2565 F.MacroCursor = Stream;
2566 if (!PP.getExternalSource())
2567 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002568
Guy Benyei11169dd2012-12-18 14:30:41 +00002569 if (Stream.SkipBlock() ||
2570 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2571 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002572 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002573 }
2574 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2575 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002576
Guy Benyei11169dd2012-12-18 14:30:41 +00002577 case PREPROCESSOR_DETAIL_BLOCK_ID:
2578 F.PreprocessorDetailCursor = Stream;
2579 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002580 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002581 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002582 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002583 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002584 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002585 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002586 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2587
Guy Benyei11169dd2012-12-18 14:30:41 +00002588 if (!PP.getPreprocessingRecord())
2589 PP.createPreprocessingRecord();
2590 if (!PP.getPreprocessingRecord()->getExternalSource())
2591 PP.getPreprocessingRecord()->SetExternalSource(*this);
2592 break;
2593
2594 case SOURCE_MANAGER_BLOCK_ID:
2595 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002596 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002597 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002598
Guy Benyei11169dd2012-12-18 14:30:41 +00002599 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002600 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2601 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002602 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002603
Guy Benyei11169dd2012-12-18 14:30:41 +00002604 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002605 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002606 if (Stream.SkipBlock() ||
2607 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2608 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002609 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002610 }
2611 CommentsCursors.push_back(std::make_pair(C, &F));
2612 break;
2613 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002614
Guy Benyei11169dd2012-12-18 14:30:41 +00002615 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002616 if (Stream.SkipBlock()) {
2617 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002618 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002619 }
2620 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002621 }
2622 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002623
2624 case llvm::BitstreamEntry::Record:
2625 // The interesting case.
2626 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002627 }
2628
2629 // Read and process a record.
2630 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002631 StringRef Blob;
2632 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002633 default: // Default behavior: ignore.
2634 break;
2635
2636 case TYPE_OFFSET: {
2637 if (F.LocalNumTypes != 0) {
2638 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002639 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002640 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002641 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002642 F.LocalNumTypes = Record[0];
2643 unsigned LocalBaseTypeIndex = Record[1];
2644 F.BaseTypeIndex = getTotalNumTypes();
2645
2646 if (F.LocalNumTypes > 0) {
2647 // Introduce the global -> local mapping for types within this module.
2648 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2649
2650 // Introduce the local -> global mapping for types within this module.
2651 F.TypeRemap.insertOrReplace(
2652 std::make_pair(LocalBaseTypeIndex,
2653 F.BaseTypeIndex - LocalBaseTypeIndex));
2654
2655 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2656 }
2657 break;
2658 }
2659
2660 case DECL_OFFSET: {
2661 if (F.LocalNumDecls != 0) {
2662 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002663 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002664 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002665 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002666 F.LocalNumDecls = Record[0];
2667 unsigned LocalBaseDeclID = Record[1];
2668 F.BaseDeclID = getTotalNumDecls();
2669
2670 if (F.LocalNumDecls > 0) {
2671 // Introduce the global -> local mapping for declarations within this
2672 // module.
2673 GlobalDeclMap.insert(
2674 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2675
2676 // Introduce the local -> global mapping for declarations within this
2677 // module.
2678 F.DeclRemap.insertOrReplace(
2679 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2680
2681 // Introduce the global -> local mapping for declarations within this
2682 // module.
2683 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2684
2685 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2686 }
2687 break;
2688 }
2689
2690 case TU_UPDATE_LEXICAL: {
2691 DeclContext *TU = Context.getTranslationUnitDecl();
2692 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002693 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002694 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002695 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002696 TU->setHasExternalLexicalStorage(true);
2697 break;
2698 }
2699
2700 case UPDATE_VISIBLE: {
2701 unsigned Idx = 0;
2702 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2703 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002704 ASTDeclContextNameLookupTable::Create(
2705 (const unsigned char *)Blob.data() + Record[Idx++],
2706 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2707 (const unsigned char *)Blob.data(),
2708 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002709 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002710 auto *DC = cast<DeclContext>(D);
2711 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002712 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
Richard Smithcd45dbc2014-04-19 03:48:30 +00002713 // FIXME: There should never be an existing lookup table.
Richard Smith52e3fba2014-03-11 07:17:35 +00002714 delete LookupTable;
2715 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002716 } else
2717 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2718 break;
2719 }
2720
2721 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002722 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002723 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002724 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2725 (const unsigned char *)F.IdentifierTableData + Record[0],
2726 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2727 (const unsigned char *)F.IdentifierTableData,
2728 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002729
2730 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2731 }
2732 break;
2733
2734 case IDENTIFIER_OFFSET: {
2735 if (F.LocalNumIdentifiers != 0) {
2736 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002737 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002738 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002739 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002740 F.LocalNumIdentifiers = Record[0];
2741 unsigned LocalBaseIdentifierID = Record[1];
2742 F.BaseIdentifierID = getTotalNumIdentifiers();
2743
2744 if (F.LocalNumIdentifiers > 0) {
2745 // Introduce the global -> local mapping for identifiers within this
2746 // module.
2747 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2748 &F));
2749
2750 // Introduce the local -> global mapping for identifiers within this
2751 // module.
2752 F.IdentifierRemap.insertOrReplace(
2753 std::make_pair(LocalBaseIdentifierID,
2754 F.BaseIdentifierID - LocalBaseIdentifierID));
2755
2756 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2757 + F.LocalNumIdentifiers);
2758 }
2759 break;
2760 }
2761
Ben Langmuir332aafe2014-01-31 01:06:56 +00002762 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002763 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002764 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002765 break;
2766
2767 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002768 if (SpecialTypes.empty()) {
2769 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2770 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2771 break;
2772 }
2773
2774 if (SpecialTypes.size() != Record.size()) {
2775 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002776 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002777 }
2778
2779 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2780 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2781 if (!SpecialTypes[I])
2782 SpecialTypes[I] = ID;
2783 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2784 // merge step?
2785 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002786 break;
2787
2788 case STATISTICS:
2789 TotalNumStatements += Record[0];
2790 TotalNumMacros += Record[1];
2791 TotalLexicalDeclContexts += Record[2];
2792 TotalVisibleDeclContexts += Record[3];
2793 break;
2794
2795 case UNUSED_FILESCOPED_DECLS:
2796 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2797 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2798 break;
2799
2800 case DELEGATING_CTORS:
2801 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2802 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2803 break;
2804
2805 case WEAK_UNDECLARED_IDENTIFIERS:
2806 if (Record.size() % 4 != 0) {
2807 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002808 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002809 }
2810
2811 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2812 // files. This isn't the way to do it :)
2813 WeakUndeclaredIdentifiers.clear();
2814
2815 // Translate the weak, undeclared identifiers into global IDs.
2816 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2817 WeakUndeclaredIdentifiers.push_back(
2818 getGlobalIdentifierID(F, Record[I++]));
2819 WeakUndeclaredIdentifiers.push_back(
2820 getGlobalIdentifierID(F, Record[I++]));
2821 WeakUndeclaredIdentifiers.push_back(
2822 ReadSourceLocation(F, Record, I).getRawEncoding());
2823 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2824 }
2825 break;
2826
Richard Smith78165b52013-01-10 23:43:47 +00002827 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002828 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith78165b52013-01-10 23:43:47 +00002829 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002830 break;
2831
2832 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002833 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002834 F.LocalNumSelectors = Record[0];
2835 unsigned LocalBaseSelectorID = Record[1];
2836 F.BaseSelectorID = getTotalNumSelectors();
2837
2838 if (F.LocalNumSelectors > 0) {
2839 // Introduce the global -> local mapping for selectors within this
2840 // module.
2841 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2842
2843 // Introduce the local -> global mapping for selectors within this
2844 // module.
2845 F.SelectorRemap.insertOrReplace(
2846 std::make_pair(LocalBaseSelectorID,
2847 F.BaseSelectorID - LocalBaseSelectorID));
2848
2849 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2850 }
2851 break;
2852 }
2853
2854 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002855 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002856 if (Record[0])
2857 F.SelectorLookupTable
2858 = ASTSelectorLookupTable::Create(
2859 F.SelectorLookupTableData + Record[0],
2860 F.SelectorLookupTableData,
2861 ASTSelectorLookupTrait(*this, F));
2862 TotalNumMethodPoolEntries += Record[1];
2863 break;
2864
2865 case REFERENCED_SELECTOR_POOL:
2866 if (!Record.empty()) {
2867 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2868 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2869 Record[Idx++]));
2870 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2871 getRawEncoding());
2872 }
2873 }
2874 break;
2875
2876 case PP_COUNTER_VALUE:
2877 if (!Record.empty() && Listener)
2878 Listener->ReadCounter(F, Record[0]);
2879 break;
2880
2881 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002882 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002883 F.NumFileSortedDecls = Record[0];
2884 break;
2885
2886 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002887 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002888 F.LocalNumSLocEntries = Record[0];
2889 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002890 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Guy Benyei11169dd2012-12-18 14:30:41 +00002891 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2892 SLocSpaceSize);
2893 // Make our entry in the range map. BaseID is negative and growing, so
2894 // we invert it. Because we invert it, though, we need the other end of
2895 // the range.
2896 unsigned RangeStart =
2897 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2898 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2899 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2900
2901 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2902 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2903 GlobalSLocOffsetMap.insert(
2904 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2905 - SLocSpaceSize,&F));
2906
2907 // Initialize the remapping table.
2908 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002909 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002910 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002911 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002912 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2913
2914 TotalNumSLocEntries += F.LocalNumSLocEntries;
2915 break;
2916 }
2917
2918 case MODULE_OFFSET_MAP: {
2919 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002920 const unsigned char *Data = (const unsigned char*)Blob.data();
2921 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002922
2923 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2924 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2925 F.SLocRemap.insert(std::make_pair(0U, 0));
2926 F.SLocRemap.insert(std::make_pair(2U, 1));
2927 }
2928
Guy Benyei11169dd2012-12-18 14:30:41 +00002929 // Continuous range maps we may be updating in our module.
2930 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2931 ContinuousRangeMap<uint32_t, int, 2>::Builder
2932 IdentifierRemap(F.IdentifierRemap);
2933 ContinuousRangeMap<uint32_t, int, 2>::Builder
2934 MacroRemap(F.MacroRemap);
2935 ContinuousRangeMap<uint32_t, int, 2>::Builder
2936 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2937 ContinuousRangeMap<uint32_t, int, 2>::Builder
2938 SubmoduleRemap(F.SubmoduleRemap);
2939 ContinuousRangeMap<uint32_t, int, 2>::Builder
2940 SelectorRemap(F.SelectorRemap);
2941 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2942 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2943
2944 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002945 using namespace llvm::support;
2946 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002947 StringRef Name = StringRef((const char*)Data, Len);
2948 Data += Len;
2949 ModuleFile *OM = ModuleMgr.lookup(Name);
2950 if (!OM) {
2951 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002952 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002953 }
2954
Justin Bogner57ba0b22014-03-28 22:03:24 +00002955 uint32_t SLocOffset =
2956 endian::readNext<uint32_t, little, unaligned>(Data);
2957 uint32_t IdentifierIDOffset =
2958 endian::readNext<uint32_t, little, unaligned>(Data);
2959 uint32_t MacroIDOffset =
2960 endian::readNext<uint32_t, little, unaligned>(Data);
2961 uint32_t PreprocessedEntityIDOffset =
2962 endian::readNext<uint32_t, little, unaligned>(Data);
2963 uint32_t SubmoduleIDOffset =
2964 endian::readNext<uint32_t, little, unaligned>(Data);
2965 uint32_t SelectorIDOffset =
2966 endian::readNext<uint32_t, little, unaligned>(Data);
2967 uint32_t DeclIDOffset =
2968 endian::readNext<uint32_t, little, unaligned>(Data);
2969 uint32_t TypeIndexOffset =
2970 endian::readNext<uint32_t, little, unaligned>(Data);
2971
Guy Benyei11169dd2012-12-18 14:30:41 +00002972 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2973 SLocRemap.insert(std::make_pair(SLocOffset,
2974 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2975 IdentifierRemap.insert(
2976 std::make_pair(IdentifierIDOffset,
2977 OM->BaseIdentifierID - IdentifierIDOffset));
2978 MacroRemap.insert(std::make_pair(MacroIDOffset,
2979 OM->BaseMacroID - MacroIDOffset));
2980 PreprocessedEntityRemap.insert(
2981 std::make_pair(PreprocessedEntityIDOffset,
2982 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2983 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2984 OM->BaseSubmoduleID - SubmoduleIDOffset));
2985 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2986 OM->BaseSelectorID - SelectorIDOffset));
2987 DeclRemap.insert(std::make_pair(DeclIDOffset,
2988 OM->BaseDeclID - DeclIDOffset));
2989
2990 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2991 OM->BaseTypeIndex - TypeIndexOffset));
2992
2993 // Global -> local mappings.
2994 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2995 }
2996 break;
2997 }
2998
2999 case SOURCE_MANAGER_LINE_TABLE:
3000 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003001 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003002 break;
3003
3004 case SOURCE_LOCATION_PRELOADS: {
3005 // Need to transform from the local view (1-based IDs) to the global view,
3006 // which is based off F.SLocEntryBaseID.
3007 if (!F.PreloadSLocEntries.empty()) {
3008 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003009 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003010 }
3011
3012 F.PreloadSLocEntries.swap(Record);
3013 break;
3014 }
3015
3016 case EXT_VECTOR_DECLS:
3017 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3018 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3019 break;
3020
3021 case VTABLE_USES:
3022 if (Record.size() % 3 != 0) {
3023 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003024 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003025 }
3026
3027 // Later tables overwrite earlier ones.
3028 // FIXME: Modules will have some trouble with this. This is clearly not
3029 // the right way to do this.
3030 VTableUses.clear();
3031
3032 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3033 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3034 VTableUses.push_back(
3035 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3036 VTableUses.push_back(Record[Idx++]);
3037 }
3038 break;
3039
3040 case DYNAMIC_CLASSES:
3041 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3042 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
3043 break;
3044
3045 case PENDING_IMPLICIT_INSTANTIATIONS:
3046 if (PendingInstantiations.size() % 2 != 0) {
3047 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003048 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003049 }
3050
3051 if (Record.size() % 2 != 0) {
3052 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003053 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003054 }
3055
3056 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3057 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3058 PendingInstantiations.push_back(
3059 ReadSourceLocation(F, Record, I).getRawEncoding());
3060 }
3061 break;
3062
3063 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00003064 if (Record.size() != 2) {
3065 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003066 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003067 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003068 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3069 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3070 break;
3071
3072 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003073 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3074 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3075 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003076
3077 unsigned LocalBasePreprocessedEntityID = Record[0];
3078
3079 unsigned StartingID;
3080 if (!PP.getPreprocessingRecord())
3081 PP.createPreprocessingRecord();
3082 if (!PP.getPreprocessingRecord()->getExternalSource())
3083 PP.getPreprocessingRecord()->SetExternalSource(*this);
3084 StartingID
3085 = PP.getPreprocessingRecord()
3086 ->allocateLoadedEntities(F.NumPreprocessedEntities);
3087 F.BasePreprocessedEntityID = StartingID;
3088
3089 if (F.NumPreprocessedEntities > 0) {
3090 // Introduce the global -> local mapping for preprocessed entities in
3091 // this module.
3092 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3093
3094 // Introduce the local -> global mapping for preprocessed entities in
3095 // this module.
3096 F.PreprocessedEntityRemap.insertOrReplace(
3097 std::make_pair(LocalBasePreprocessedEntityID,
3098 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3099 }
3100
3101 break;
3102 }
3103
3104 case DECL_UPDATE_OFFSETS: {
3105 if (Record.size() % 2 != 0) {
3106 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003107 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003108 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003109 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3110 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3111 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3112
3113 // If we've already loaded the decl, perform the updates when we finish
3114 // loading this block.
3115 if (Decl *D = GetExistingDecl(ID))
3116 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3117 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003118 break;
3119 }
3120
3121 case DECL_REPLACEMENTS: {
3122 if (Record.size() % 3 != 0) {
3123 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003124 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003125 }
3126 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3127 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3128 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3129 break;
3130 }
3131
3132 case OBJC_CATEGORIES_MAP: {
3133 if (F.LocalNumObjCCategoriesInMap != 0) {
3134 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003135 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003136 }
3137
3138 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003139 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003140 break;
3141 }
3142
3143 case OBJC_CATEGORIES:
3144 F.ObjCCategories.swap(Record);
3145 break;
3146
3147 case CXX_BASE_SPECIFIER_OFFSETS: {
3148 if (F.LocalNumCXXBaseSpecifiers != 0) {
3149 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003150 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003151 }
3152
3153 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003154 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003155 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
3156 break;
3157 }
3158
3159 case DIAG_PRAGMA_MAPPINGS:
3160 if (F.PragmaDiagMappings.empty())
3161 F.PragmaDiagMappings.swap(Record);
3162 else
3163 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3164 Record.begin(), Record.end());
3165 break;
3166
3167 case CUDA_SPECIAL_DECL_REFS:
3168 // Later tables overwrite earlier ones.
3169 // FIXME: Modules will have trouble with this.
3170 CUDASpecialDeclRefs.clear();
3171 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3172 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3173 break;
3174
3175 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003176 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003177 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003178 if (Record[0]) {
3179 F.HeaderFileInfoTable
3180 = HeaderFileInfoLookupTable::Create(
3181 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3182 (const unsigned char *)F.HeaderFileInfoTableData,
3183 HeaderFileInfoTrait(*this, F,
3184 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003185 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003186
3187 PP.getHeaderSearchInfo().SetExternalSource(this);
3188 if (!PP.getHeaderSearchInfo().getExternalLookup())
3189 PP.getHeaderSearchInfo().SetExternalLookup(this);
3190 }
3191 break;
3192 }
3193
3194 case FP_PRAGMA_OPTIONS:
3195 // Later tables overwrite earlier ones.
3196 FPPragmaOptions.swap(Record);
3197 break;
3198
3199 case OPENCL_EXTENSIONS:
3200 // Later tables overwrite earlier ones.
3201 OpenCLExtensions.swap(Record);
3202 break;
3203
3204 case TENTATIVE_DEFINITIONS:
3205 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3206 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3207 break;
3208
3209 case KNOWN_NAMESPACES:
3210 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3211 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3212 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003213
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003214 case UNDEFINED_BUT_USED:
3215 if (UndefinedButUsed.size() % 2 != 0) {
3216 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003217 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003218 }
3219
3220 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003221 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003222 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003223 }
3224 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003225 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3226 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003227 ReadSourceLocation(F, Record, I).getRawEncoding());
3228 }
3229 break;
3230
Guy Benyei11169dd2012-12-18 14:30:41 +00003231 case IMPORTED_MODULES: {
3232 if (F.Kind != MK_Module) {
3233 // If we aren't loading a module (which has its own exports), make
3234 // all of the imported modules visible.
3235 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003236 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3237 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3238 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3239 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003240 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003241 }
3242 }
3243 break;
3244 }
3245
3246 case LOCAL_REDECLARATIONS: {
3247 F.RedeclarationChains.swap(Record);
3248 break;
3249 }
3250
3251 case LOCAL_REDECLARATIONS_MAP: {
3252 if (F.LocalNumRedeclarationsInMap != 0) {
3253 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003254 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003255 }
3256
3257 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003258 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003259 break;
3260 }
3261
3262 case MERGED_DECLARATIONS: {
3263 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3264 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3265 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3266 for (unsigned N = Record[Idx++]; N > 0; --N)
3267 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3268 }
3269 break;
3270 }
3271
3272 case MACRO_OFFSET: {
3273 if (F.LocalNumMacros != 0) {
3274 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003275 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003276 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003277 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003278 F.LocalNumMacros = Record[0];
3279 unsigned LocalBaseMacroID = Record[1];
3280 F.BaseMacroID = getTotalNumMacros();
3281
3282 if (F.LocalNumMacros > 0) {
3283 // Introduce the global -> local mapping for macros within this module.
3284 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3285
3286 // Introduce the local -> global mapping for macros within this module.
3287 F.MacroRemap.insertOrReplace(
3288 std::make_pair(LocalBaseMacroID,
3289 F.BaseMacroID - LocalBaseMacroID));
3290
3291 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3292 }
3293 break;
3294 }
3295
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003296 case MACRO_TABLE: {
3297 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00003298 break;
3299 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00003300
3301 case LATE_PARSED_TEMPLATE: {
3302 LateParsedTemplates.append(Record.begin(), Record.end());
3303 break;
3304 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003305
3306 case OPTIMIZE_PRAGMA_OPTIONS:
3307 if (Record.size() != 1) {
3308 Error("invalid pragma optimize record");
3309 return Failure;
3310 }
3311 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3312 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003313 }
3314 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003315}
3316
Douglas Gregorc1489562013-02-12 23:36:21 +00003317/// \brief Move the given method to the back of the global list of methods.
3318static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3319 // Find the entry for this selector in the method pool.
3320 Sema::GlobalMethodPool::iterator Known
3321 = S.MethodPool.find(Method->getSelector());
3322 if (Known == S.MethodPool.end())
3323 return;
3324
3325 // Retrieve the appropriate method list.
3326 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3327 : Known->second.second;
3328 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003329 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003330 if (!Found) {
3331 if (List->Method == Method) {
3332 Found = true;
3333 } else {
3334 // Keep searching.
3335 continue;
3336 }
3337 }
3338
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003339 if (List->getNext())
3340 List->Method = List->getNext()->Method;
Douglas Gregorc1489562013-02-12 23:36:21 +00003341 else
3342 List->Method = Method;
3343 }
3344}
3345
Richard Smithe657bbd2014-07-18 22:13:40 +00003346void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner,
3347 bool FromFinalization) {
3348 // FIXME: Only do this if Owner->NameVisibility == AllVisible.
Richard Smith57721ac2014-07-21 04:10:40 +00003349 for (Decl *D : Names.HiddenDecls) {
Richard Smith49f906a2014-03-01 00:08:04 +00003350 bool wasHidden = D->Hidden;
3351 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003352
Richard Smith49f906a2014-03-01 00:08:04 +00003353 if (wasHidden && SemaObj) {
3354 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3355 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003356 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003357 }
3358 }
Richard Smith49f906a2014-03-01 00:08:04 +00003359
Richard Smithe657bbd2014-07-18 22:13:40 +00003360 assert((FromFinalization || Owner->NameVisibility >= Module::MacrosVisible) &&
3361 "nothing to make visible?");
Richard Smithdaa69e02014-07-25 04:40:03 +00003362 for (const auto &Macro : Names.HiddenMacros) {
3363 if (FromFinalization)
3364 PP.appendMacroDirective(Macro.first,
3365 Macro.second->import(PP, SourceLocation()));
3366 else
3367 installImportedMacro(Macro.first, Macro.second, Owner);
3368 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003369}
3370
Richard Smith49f906a2014-03-01 00:08:04 +00003371void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003372 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003373 SourceLocation ImportLoc,
3374 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003375 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003376 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003377 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003378 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003379 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003380
3381 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003382 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003383 // there is nothing more to do.
3384 continue;
3385 }
Richard Smith49f906a2014-03-01 00:08:04 +00003386
Guy Benyei11169dd2012-12-18 14:30:41 +00003387 if (!Mod->isAvailable()) {
3388 // Modules that aren't available cannot be made visible.
3389 continue;
3390 }
3391
3392 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003393 if (NameVisibility >= Module::MacrosVisible &&
3394 Mod->NameVisibility < Module::MacrosVisible)
3395 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003396 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003397
Guy Benyei11169dd2012-12-18 14:30:41 +00003398 // If we've already deserialized any names from this module,
3399 // mark them as visible.
3400 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3401 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003402 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003403 HiddenNamesMap.erase(Hidden);
Richard Smith57721ac2014-07-21 04:10:40 +00003404 makeNamesVisible(HiddenNames.second, HiddenNames.first,
3405 /*FromFinalization*/false);
3406 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3407 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003408 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003409
Guy Benyei11169dd2012-12-18 14:30:41 +00003410 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003411 SmallVector<Module *, 16> Exports;
3412 Mod->getExportedModules(Exports);
3413 for (SmallVectorImpl<Module *>::iterator
3414 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3415 Module *Exported = *I;
3416 if (Visited.insert(Exported))
3417 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003418 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003419
3420 // Detect any conflicts.
3421 if (Complain) {
3422 assert(ImportLoc.isValid() && "Missing import location");
3423 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3424 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3425 Diag(ImportLoc, diag::warn_module_conflict)
3426 << Mod->getFullModuleName()
3427 << Mod->Conflicts[I].Other->getFullModuleName()
3428 << Mod->Conflicts[I].Message;
3429 // FIXME: Need note where the other module was imported.
3430 }
3431 }
3432 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003433 }
3434}
3435
Douglas Gregore060e572013-01-25 01:03:03 +00003436bool ASTReader::loadGlobalIndex() {
3437 if (GlobalIndex)
3438 return false;
3439
3440 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3441 !Context.getLangOpts().Modules)
3442 return true;
3443
3444 // Try to load the global index.
3445 TriedLoadingGlobalIndex = true;
3446 StringRef ModuleCachePath
3447 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3448 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003449 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003450 if (!Result.first)
3451 return true;
3452
3453 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003454 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003455 return false;
3456}
3457
3458bool ASTReader::isGlobalIndexUnavailable() const {
3459 return Context.getLangOpts().Modules && UseGlobalIndex &&
3460 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3461}
3462
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003463static void updateModuleTimestamp(ModuleFile &MF) {
3464 // Overwrite the timestamp file contents so that file's mtime changes.
3465 std::string TimestampFilename = MF.getTimestampFilename();
3466 std::string ErrorInfo;
Rafael Espindola04a13be2014-02-24 15:06:52 +00003467 llvm::raw_fd_ostream OS(TimestampFilename.c_str(), ErrorInfo,
Rafael Espindola4fbd3732014-02-24 18:20:21 +00003468 llvm::sys::fs::F_Text);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003469 if (!ErrorInfo.empty())
3470 return;
3471 OS << "Timestamp file\n";
3472}
3473
Guy Benyei11169dd2012-12-18 14:30:41 +00003474ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3475 ModuleKind Type,
3476 SourceLocation ImportLoc,
3477 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003478 llvm::SaveAndRestore<SourceLocation>
3479 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3480
Richard Smithd1c46742014-04-30 02:24:17 +00003481 // Defer any pending actions until we get to the end of reading the AST file.
3482 Deserializing AnASTFile(this);
3483
Guy Benyei11169dd2012-12-18 14:30:41 +00003484 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003485 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003486
3487 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003488 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003489 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003490 /*ImportedBy=*/nullptr, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003491 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003492 ClientLoadCapabilities)) {
3493 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003494 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003495 case OutOfDate:
3496 case VersionMismatch:
3497 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003498 case HadErrors: {
3499 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3500 for (const ImportedModule &IM : Loaded)
3501 LoadedSet.insert(IM.Mod);
3502
Douglas Gregor7029ce12013-03-19 00:28:20 +00003503 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003504 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003505 Context.getLangOpts().Modules
3506 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003507 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003508
3509 // If we find that any modules are unusable, the global index is going
3510 // to be out-of-date. Just remove it.
3511 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003512 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003513 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003514 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003515 case Success:
3516 break;
3517 }
3518
3519 // Here comes stuff that we only do once the entire chain is loaded.
3520
3521 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003522 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3523 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003524 M != MEnd; ++M) {
3525 ModuleFile &F = *M->Mod;
3526
3527 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003528 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3529 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003530
3531 // Once read, set the ModuleFile bit base offset and update the size in
3532 // bits of all files we've seen.
3533 F.GlobalBitOffset = TotalModulesSizeInBits;
3534 TotalModulesSizeInBits += F.SizeInBits;
3535 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3536
3537 // Preload SLocEntries.
3538 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3539 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3540 // Load it through the SourceManager and don't call ReadSLocEntry()
3541 // directly because the entry may have already been loaded in which case
3542 // calling ReadSLocEntry() directly would trigger an assertion in
3543 // SourceManager.
3544 SourceMgr.getLoadedSLocEntryByID(Index);
3545 }
3546 }
3547
Douglas Gregor603cd862013-03-22 18:50:14 +00003548 // Setup the import locations and notify the module manager that we've
3549 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003550 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3551 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003552 M != MEnd; ++M) {
3553 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003554
3555 ModuleMgr.moduleFileAccepted(&F);
3556
3557 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003558 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003559 if (!M->ImportedBy)
3560 F.ImportLoc = M->ImportLoc;
3561 else
3562 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3563 M->ImportLoc.getRawEncoding());
3564 }
3565
3566 // Mark all of the identifiers in the identifier table as being out of date,
3567 // so that various accessors know to check the loaded modules when the
3568 // identifier is used.
3569 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3570 IdEnd = PP.getIdentifierTable().end();
3571 Id != IdEnd; ++Id)
3572 Id->second->setOutOfDate(true);
3573
3574 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003575 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3576 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003577 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3578 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003579
3580 switch (Unresolved.Kind) {
3581 case UnresolvedModuleRef::Conflict:
3582 if (ResolvedMod) {
3583 Module::Conflict Conflict;
3584 Conflict.Other = ResolvedMod;
3585 Conflict.Message = Unresolved.String.str();
3586 Unresolved.Mod->Conflicts.push_back(Conflict);
3587 }
3588 continue;
3589
3590 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003591 if (ResolvedMod)
3592 Unresolved.Mod->Imports.push_back(ResolvedMod);
3593 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003594
Douglas Gregorfb912652013-03-20 21:10:35 +00003595 case UnresolvedModuleRef::Export:
3596 if (ResolvedMod || Unresolved.IsWildcard)
3597 Unresolved.Mod->Exports.push_back(
3598 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3599 continue;
3600 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003601 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003602 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003603
3604 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3605 // Might be unnecessary as use declarations are only used to build the
3606 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003607
3608 InitializeContext();
3609
Richard Smith3d8e97e2013-10-18 06:54:39 +00003610 if (SemaObj)
3611 UpdateSema();
3612
Guy Benyei11169dd2012-12-18 14:30:41 +00003613 if (DeserializationListener)
3614 DeserializationListener->ReaderInitialized(this);
3615
3616 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3617 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3618 PrimaryModule.OriginalSourceFileID
3619 = FileID::get(PrimaryModule.SLocEntryBaseID
3620 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3621
3622 // If this AST file is a precompiled preamble, then set the
3623 // preamble file ID of the source manager to the file source file
3624 // from which the preamble was built.
3625 if (Type == MK_Preamble) {
3626 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3627 } else if (Type == MK_MainFile) {
3628 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3629 }
3630 }
3631
3632 // For any Objective-C class definitions we have already loaded, make sure
3633 // that we load any additional categories.
3634 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3635 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3636 ObjCClassesLoaded[I],
3637 PreviousGeneration);
3638 }
Douglas Gregore060e572013-01-25 01:03:03 +00003639
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003640 if (PP.getHeaderSearchInfo()
3641 .getHeaderSearchOpts()
3642 .ModulesValidateOncePerBuildSession) {
3643 // Now we are certain that the module and all modules it depends on are
3644 // up to date. Create or update timestamp files for modules that are
3645 // located in the module cache (not for PCH files that could be anywhere
3646 // in the filesystem).
3647 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3648 ImportedModule &M = Loaded[I];
3649 if (M.Mod->Kind == MK_Module) {
3650 updateModuleTimestamp(*M.Mod);
3651 }
3652 }
3653 }
3654
Guy Benyei11169dd2012-12-18 14:30:41 +00003655 return Success;
3656}
3657
3658ASTReader::ASTReadResult
3659ASTReader::ReadASTCore(StringRef FileName,
3660 ModuleKind Type,
3661 SourceLocation ImportLoc,
3662 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003663 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003664 off_t ExpectedSize, time_t ExpectedModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00003665 unsigned ClientLoadCapabilities) {
3666 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003667 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003668 ModuleManager::AddModuleResult AddResult
3669 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003670 getGeneration(), ExpectedSize, ExpectedModTime,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003671 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003672
Douglas Gregor7029ce12013-03-19 00:28:20 +00003673 switch (AddResult) {
3674 case ModuleManager::AlreadyLoaded:
3675 return Success;
3676
3677 case ModuleManager::NewlyLoaded:
3678 // Load module file below.
3679 break;
3680
3681 case ModuleManager::Missing:
3682 // The module file was missing; if the client handle handle, that, return
3683 // it.
3684 if (ClientLoadCapabilities & ARR_Missing)
3685 return Missing;
3686
3687 // Otherwise, return an error.
3688 {
3689 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3690 + ErrorStr;
3691 Error(Msg);
3692 }
3693 return Failure;
3694
3695 case ModuleManager::OutOfDate:
3696 // We couldn't load the module file because it is out-of-date. If the
3697 // client can handle out-of-date, return it.
3698 if (ClientLoadCapabilities & ARR_OutOfDate)
3699 return OutOfDate;
3700
3701 // Otherwise, return an error.
3702 {
3703 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3704 + ErrorStr;
3705 Error(Msg);
3706 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003707 return Failure;
3708 }
3709
Douglas Gregor7029ce12013-03-19 00:28:20 +00003710 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003711
3712 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3713 // module?
3714 if (FileName != "-") {
3715 CurrentDir = llvm::sys::path::parent_path(FileName);
3716 if (CurrentDir.empty()) CurrentDir = ".";
3717 }
3718
3719 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003720 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003721 Stream.init(F.StreamFile);
3722 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3723
3724 // Sniff for the signature.
3725 if (Stream.Read(8) != 'C' ||
3726 Stream.Read(8) != 'P' ||
3727 Stream.Read(8) != 'C' ||
3728 Stream.Read(8) != 'H') {
3729 Diag(diag::err_not_a_pch_file) << FileName;
3730 return Failure;
3731 }
3732
3733 // This is used for compatibility with older PCH formats.
3734 bool HaveReadControlBlock = false;
3735
Chris Lattnerefa77172013-01-20 00:00:22 +00003736 while (1) {
3737 llvm::BitstreamEntry Entry = Stream.advance();
3738
3739 switch (Entry.Kind) {
3740 case llvm::BitstreamEntry::Error:
3741 case llvm::BitstreamEntry::EndBlock:
3742 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003743 Error("invalid record at top-level of AST file");
3744 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003745
3746 case llvm::BitstreamEntry::SubBlock:
3747 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003748 }
3749
Guy Benyei11169dd2012-12-18 14:30:41 +00003750 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003751 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003752 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3753 if (Stream.ReadBlockInfoBlock()) {
3754 Error("malformed BlockInfoBlock in AST file");
3755 return Failure;
3756 }
3757 break;
3758 case CONTROL_BLOCK_ID:
3759 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003760 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003761 case Success:
3762 break;
3763
3764 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003765 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003766 case OutOfDate: return OutOfDate;
3767 case VersionMismatch: return VersionMismatch;
3768 case ConfigurationMismatch: return ConfigurationMismatch;
3769 case HadErrors: return HadErrors;
3770 }
3771 break;
3772 case AST_BLOCK_ID:
3773 if (!HaveReadControlBlock) {
3774 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003775 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003776 return VersionMismatch;
3777 }
3778
3779 // Record that we've loaded this module.
3780 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3781 return Success;
3782
3783 default:
3784 if (Stream.SkipBlock()) {
3785 Error("malformed block record in AST file");
3786 return Failure;
3787 }
3788 break;
3789 }
3790 }
3791
3792 return Success;
3793}
3794
3795void ASTReader::InitializeContext() {
3796 // If there's a listener, notify them that we "read" the translation unit.
3797 if (DeserializationListener)
3798 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3799 Context.getTranslationUnitDecl());
3800
Guy Benyei11169dd2012-12-18 14:30:41 +00003801 // FIXME: Find a better way to deal with collisions between these
3802 // built-in types. Right now, we just ignore the problem.
3803
3804 // Load the special types.
3805 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3806 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3807 if (!Context.CFConstantStringTypeDecl)
3808 Context.setCFConstantStringType(GetType(String));
3809 }
3810
3811 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3812 QualType FileType = GetType(File);
3813 if (FileType.isNull()) {
3814 Error("FILE type is NULL");
3815 return;
3816 }
3817
3818 if (!Context.FILEDecl) {
3819 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3820 Context.setFILEDecl(Typedef->getDecl());
3821 else {
3822 const TagType *Tag = FileType->getAs<TagType>();
3823 if (!Tag) {
3824 Error("Invalid FILE type in AST file");
3825 return;
3826 }
3827 Context.setFILEDecl(Tag->getDecl());
3828 }
3829 }
3830 }
3831
3832 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3833 QualType Jmp_bufType = GetType(Jmp_buf);
3834 if (Jmp_bufType.isNull()) {
3835 Error("jmp_buf type is NULL");
3836 return;
3837 }
3838
3839 if (!Context.jmp_bufDecl) {
3840 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3841 Context.setjmp_bufDecl(Typedef->getDecl());
3842 else {
3843 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3844 if (!Tag) {
3845 Error("Invalid jmp_buf type in AST file");
3846 return;
3847 }
3848 Context.setjmp_bufDecl(Tag->getDecl());
3849 }
3850 }
3851 }
3852
3853 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3854 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3855 if (Sigjmp_bufType.isNull()) {
3856 Error("sigjmp_buf type is NULL");
3857 return;
3858 }
3859
3860 if (!Context.sigjmp_bufDecl) {
3861 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3862 Context.setsigjmp_bufDecl(Typedef->getDecl());
3863 else {
3864 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3865 assert(Tag && "Invalid sigjmp_buf type in AST file");
3866 Context.setsigjmp_bufDecl(Tag->getDecl());
3867 }
3868 }
3869 }
3870
3871 if (unsigned ObjCIdRedef
3872 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3873 if (Context.ObjCIdRedefinitionType.isNull())
3874 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3875 }
3876
3877 if (unsigned ObjCClassRedef
3878 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3879 if (Context.ObjCClassRedefinitionType.isNull())
3880 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3881 }
3882
3883 if (unsigned ObjCSelRedef
3884 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3885 if (Context.ObjCSelRedefinitionType.isNull())
3886 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3887 }
3888
3889 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3890 QualType Ucontext_tType = GetType(Ucontext_t);
3891 if (Ucontext_tType.isNull()) {
3892 Error("ucontext_t type is NULL");
3893 return;
3894 }
3895
3896 if (!Context.ucontext_tDecl) {
3897 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3898 Context.setucontext_tDecl(Typedef->getDecl());
3899 else {
3900 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3901 assert(Tag && "Invalid ucontext_t type in AST file");
3902 Context.setucontext_tDecl(Tag->getDecl());
3903 }
3904 }
3905 }
3906 }
3907
3908 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3909
3910 // If there were any CUDA special declarations, deserialize them.
3911 if (!CUDASpecialDeclRefs.empty()) {
3912 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3913 Context.setcudaConfigureCallDecl(
3914 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3915 }
Richard Smith56be7542014-03-21 00:33:59 +00003916
Guy Benyei11169dd2012-12-18 14:30:41 +00003917 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00003918 // FIXME: This does not make macro-only imports visible again. It also doesn't
3919 // make #includes mapped to module imports visible.
3920 for (auto &Import : ImportedModules) {
3921 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003922 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00003923 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00003924 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00003925 }
3926 ImportedModules.clear();
3927}
3928
3929void ASTReader::finalizeForWriting() {
Richard Smith57721ac2014-07-21 04:10:40 +00003930 while (!HiddenNamesMap.empty()) {
3931 auto HiddenNames = std::move(*HiddenNamesMap.begin());
3932 HiddenNamesMap.erase(HiddenNamesMap.begin());
3933 makeNamesVisible(HiddenNames.second, HiddenNames.first,
3934 /*FromFinalization*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00003935 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003936}
3937
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003938/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3939/// cursor into the start of the given block ID, returning false on success and
3940/// true on failure.
3941static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003942 while (1) {
3943 llvm::BitstreamEntry Entry = Cursor.advance();
3944 switch (Entry.Kind) {
3945 case llvm::BitstreamEntry::Error:
3946 case llvm::BitstreamEntry::EndBlock:
3947 return true;
3948
3949 case llvm::BitstreamEntry::Record:
3950 // Ignore top-level records.
3951 Cursor.skipRecord(Entry.ID);
3952 break;
3953
3954 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003955 if (Entry.ID == BlockID) {
3956 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003957 return true;
3958 // Found it!
3959 return false;
3960 }
3961
3962 if (Cursor.SkipBlock())
3963 return true;
3964 }
3965 }
3966}
3967
Guy Benyei11169dd2012-12-18 14:30:41 +00003968/// \brief Retrieve the name of the original source file name
3969/// directly from the AST file, without actually loading the AST
3970/// file.
3971std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3972 FileManager &FileMgr,
3973 DiagnosticsEngine &Diags) {
3974 // Open the AST file.
3975 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003976 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00003977 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3978 if (!Buffer) {
3979 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3980 return std::string();
3981 }
3982
3983 // Initialize the stream
3984 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003985 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003986 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3987 (const unsigned char *)Buffer->getBufferEnd());
3988 Stream.init(StreamFile);
3989
3990 // Sniff for the signature.
3991 if (Stream.Read(8) != 'C' ||
3992 Stream.Read(8) != 'P' ||
3993 Stream.Read(8) != 'C' ||
3994 Stream.Read(8) != 'H') {
3995 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3996 return std::string();
3997 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003998
Chris Lattnere7b154b2013-01-19 21:39:22 +00003999 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004000 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004001 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4002 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004003 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004004
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004005 // Scan for ORIGINAL_FILE inside the control block.
4006 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004007 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004008 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004009 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4010 return std::string();
4011
4012 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4013 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4014 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004015 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004016
Guy Benyei11169dd2012-12-18 14:30:41 +00004017 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004018 StringRef Blob;
4019 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4020 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004021 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004022}
4023
4024namespace {
4025 class SimplePCHValidator : public ASTReaderListener {
4026 const LangOptions &ExistingLangOpts;
4027 const TargetOptions &ExistingTargetOpts;
4028 const PreprocessorOptions &ExistingPPOpts;
4029 FileManager &FileMgr;
4030
4031 public:
4032 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4033 const TargetOptions &ExistingTargetOpts,
4034 const PreprocessorOptions &ExistingPPOpts,
4035 FileManager &FileMgr)
4036 : ExistingLangOpts(ExistingLangOpts),
4037 ExistingTargetOpts(ExistingTargetOpts),
4038 ExistingPPOpts(ExistingPPOpts),
4039 FileMgr(FileMgr)
4040 {
4041 }
4042
Craig Topper3e89dfe2014-03-13 02:13:41 +00004043 bool ReadLanguageOptions(const LangOptions &LangOpts,
4044 bool Complain) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004045 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004046 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004047 bool ReadTargetOptions(const TargetOptions &TargetOpts,
4048 bool Complain) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004049 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004050 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004051 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4052 bool Complain,
4053 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004054 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004055 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004056 }
4057 };
4058}
4059
4060bool ASTReader::readASTFileControlBlock(StringRef Filename,
4061 FileManager &FileMgr,
4062 ASTReaderListener &Listener) {
4063 // Open the AST file.
4064 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004065 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00004066 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
4067 if (!Buffer) {
4068 return true;
4069 }
4070
4071 // Initialize the stream
4072 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004073 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00004074 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
4075 (const unsigned char *)Buffer->getBufferEnd());
4076 Stream.init(StreamFile);
4077
4078 // Sniff for the signature.
4079 if (Stream.Read(8) != 'C' ||
4080 Stream.Read(8) != 'P' ||
4081 Stream.Read(8) != 'C' ||
4082 Stream.Read(8) != 'H') {
4083 return true;
4084 }
4085
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004086 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004087 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004088 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004089
4090 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004091 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004092 BitstreamCursor InputFilesCursor;
4093 if (NeedsInputFiles) {
4094 InputFilesCursor = Stream;
4095 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4096 return true;
4097
4098 // Read the abbreviations
4099 while (true) {
4100 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4101 unsigned Code = InputFilesCursor.ReadCode();
4102
4103 // We expect all abbrevs to be at the start of the block.
4104 if (Code != llvm::bitc::DEFINE_ABBREV) {
4105 InputFilesCursor.JumpToBit(Offset);
4106 break;
4107 }
4108 InputFilesCursor.ReadAbbrevRecord();
4109 }
4110 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004111
4112 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004113 RecordData Record;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004114 while (1) {
4115 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4116 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4117 return false;
4118
4119 if (Entry.Kind != llvm::BitstreamEntry::Record)
4120 return true;
4121
Guy Benyei11169dd2012-12-18 14:30:41 +00004122 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004123 StringRef Blob;
4124 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004125 switch ((ControlRecordTypes)RecCode) {
4126 case METADATA: {
4127 if (Record[0] != VERSION_MAJOR)
4128 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004129
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004130 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004131 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004132
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004133 break;
4134 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004135 case MODULE_NAME:
4136 Listener.ReadModuleName(Blob);
4137 break;
4138 case MODULE_MAP_FILE:
4139 Listener.ReadModuleMapFile(Blob);
4140 break;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004141 case LANGUAGE_OPTIONS:
4142 if (ParseLanguageOptions(Record, false, Listener))
4143 return true;
4144 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004145
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004146 case TARGET_OPTIONS:
4147 if (ParseTargetOptions(Record, false, Listener))
4148 return true;
4149 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004150
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004151 case DIAGNOSTIC_OPTIONS:
4152 if (ParseDiagnosticOptions(Record, false, Listener))
4153 return true;
4154 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004155
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004156 case FILE_SYSTEM_OPTIONS:
4157 if (ParseFileSystemOptions(Record, false, Listener))
4158 return true;
4159 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004160
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004161 case HEADER_SEARCH_OPTIONS:
4162 if (ParseHeaderSearchOptions(Record, false, Listener))
4163 return true;
4164 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004165
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004166 case PREPROCESSOR_OPTIONS: {
4167 std::string IgnoredSuggestedPredefines;
4168 if (ParsePreprocessorOptions(Record, false, Listener,
4169 IgnoredSuggestedPredefines))
4170 return true;
4171 break;
4172 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004173
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004174 case INPUT_FILE_OFFSETS: {
4175 if (!NeedsInputFiles)
4176 break;
4177
4178 unsigned NumInputFiles = Record[0];
4179 unsigned NumUserFiles = Record[1];
4180 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
4181 for (unsigned I = 0; I != NumInputFiles; ++I) {
4182 // Go find this input file.
4183 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004184
4185 if (isSystemFile && !NeedsSystemInputFiles)
4186 break; // the rest are system input files
4187
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004188 BitstreamCursor &Cursor = InputFilesCursor;
4189 SavedStreamPosition SavedPosition(Cursor);
4190 Cursor.JumpToBit(InputFileOffs[I]);
4191
4192 unsigned Code = Cursor.ReadCode();
4193 RecordData Record;
4194 StringRef Blob;
4195 bool shouldContinue = false;
4196 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4197 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004198 bool Overridden = static_cast<bool>(Record[3]);
4199 shouldContinue = Listener.visitInputFile(Blob, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004200 break;
4201 }
4202 if (!shouldContinue)
4203 break;
4204 }
4205 break;
4206 }
4207
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004208 default:
4209 // No other validation to perform.
4210 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004211 }
4212 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004213}
4214
4215
4216bool ASTReader::isAcceptableASTFile(StringRef Filename,
4217 FileManager &FileMgr,
4218 const LangOptions &LangOpts,
4219 const TargetOptions &TargetOpts,
4220 const PreprocessorOptions &PPOpts) {
4221 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
4222 return !readASTFileControlBlock(Filename, FileMgr, validator);
4223}
4224
Ben Langmuir2c9af442014-04-10 17:57:43 +00004225ASTReader::ASTReadResult
4226ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004227 // Enter the submodule block.
4228 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4229 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004230 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004231 }
4232
4233 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4234 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004235 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004236 RecordData Record;
4237 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004238 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4239
4240 switch (Entry.Kind) {
4241 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4242 case llvm::BitstreamEntry::Error:
4243 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004244 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004245 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004246 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004247 case llvm::BitstreamEntry::Record:
4248 // The interesting case.
4249 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004250 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004251
Guy Benyei11169dd2012-12-18 14:30:41 +00004252 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004253 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004254 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004255 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004256 default: // Default behavior: ignore.
4257 break;
4258
4259 case SUBMODULE_DEFINITION: {
4260 if (First) {
4261 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004262 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004263 }
4264
Douglas Gregor8d932422013-03-20 03:59:18 +00004265 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004266 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004267 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004268 }
4269
Chris Lattner0e6c9402013-01-20 02:38:54 +00004270 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004271 unsigned Idx = 0;
4272 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4273 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4274 bool IsFramework = Record[Idx++];
4275 bool IsExplicit = Record[Idx++];
4276 bool IsSystem = Record[Idx++];
4277 bool IsExternC = Record[Idx++];
4278 bool InferSubmodules = Record[Idx++];
4279 bool InferExplicitSubmodules = Record[Idx++];
4280 bool InferExportWildcard = Record[Idx++];
4281 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004282
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004283 Module *ParentModule = nullptr;
4284 const FileEntry *ModuleMap = nullptr;
4285 if (Parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004286 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004287 ModuleMap = ParentModule->ModuleMap;
4288 }
4289
4290 if (!F.ModuleMapPath.empty())
4291 ModuleMap = FileMgr.getFile(F.ModuleMapPath);
4292
Guy Benyei11169dd2012-12-18 14:30:41 +00004293 // Retrieve this (sub)module from the module map, creating it if
4294 // necessary.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004295 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, ModuleMap,
Guy Benyei11169dd2012-12-18 14:30:41 +00004296 IsFramework,
4297 IsExplicit).first;
4298 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4299 if (GlobalIndex >= SubmodulesLoaded.size() ||
4300 SubmodulesLoaded[GlobalIndex]) {
4301 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004302 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004303 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004304
Douglas Gregor7029ce12013-03-19 00:28:20 +00004305 if (!ParentModule) {
4306 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4307 if (CurFile != F.File) {
4308 if (!Diags.isDiagnosticInFlight()) {
4309 Diag(diag::err_module_file_conflict)
4310 << CurrentModule->getTopLevelModuleName()
4311 << CurFile->getName()
4312 << F.File->getName();
4313 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004314 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004315 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004316 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004317
4318 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004319 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004320
Guy Benyei11169dd2012-12-18 14:30:41 +00004321 CurrentModule->IsFromModuleFile = true;
4322 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004323 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004324 CurrentModule->InferSubmodules = InferSubmodules;
4325 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4326 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004327 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004328 if (DeserializationListener)
4329 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4330
4331 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004332
Douglas Gregorfb912652013-03-20 21:10:35 +00004333 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004334 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004335 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004336 CurrentModule->UnresolvedConflicts.clear();
4337 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004338 break;
4339 }
4340
4341 case SUBMODULE_UMBRELLA_HEADER: {
4342 if (First) {
4343 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004344 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004345 }
4346
4347 if (!CurrentModule)
4348 break;
4349
Chris Lattner0e6c9402013-01-20 02:38:54 +00004350 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004351 if (!CurrentModule->getUmbrellaHeader())
4352 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4353 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004354 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4355 Error("mismatched umbrella headers in submodule");
4356 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004357 }
4358 }
4359 break;
4360 }
4361
4362 case SUBMODULE_HEADER: {
4363 if (First) {
4364 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004365 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004366 }
4367
4368 if (!CurrentModule)
4369 break;
4370
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004371 // We lazily associate headers with their modules via the HeaderInfoTable.
4372 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4373 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004374 break;
4375 }
4376
4377 case SUBMODULE_EXCLUDED_HEADER: {
4378 if (First) {
4379 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004380 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004381 }
4382
4383 if (!CurrentModule)
4384 break;
4385
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004386 // We lazily associate headers with their modules via the HeaderInfoTable.
4387 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4388 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004389 break;
4390 }
4391
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004392 case SUBMODULE_PRIVATE_HEADER: {
4393 if (First) {
4394 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004395 return Failure;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004396 }
4397
4398 if (!CurrentModule)
4399 break;
4400
4401 // We lazily associate headers with their modules via the HeaderInfoTable.
4402 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4403 // of complete filenames or remove it entirely.
4404 break;
4405 }
4406
Guy Benyei11169dd2012-12-18 14:30:41 +00004407 case SUBMODULE_TOPHEADER: {
4408 if (First) {
4409 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004410 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004411 }
4412
4413 if (!CurrentModule)
4414 break;
4415
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004416 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004417 break;
4418 }
4419
4420 case SUBMODULE_UMBRELLA_DIR: {
4421 if (First) {
4422 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004423 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004424 }
4425
4426 if (!CurrentModule)
4427 break;
4428
Guy Benyei11169dd2012-12-18 14:30:41 +00004429 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004430 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004431 if (!CurrentModule->getUmbrellaDir())
4432 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4433 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004434 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4435 Error("mismatched umbrella directories in submodule");
4436 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004437 }
4438 }
4439 break;
4440 }
4441
4442 case SUBMODULE_METADATA: {
4443 if (!First) {
4444 Error("submodule metadata record not at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004445 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004446 }
4447 First = false;
4448
4449 F.BaseSubmoduleID = getTotalNumSubmodules();
4450 F.LocalNumSubmodules = Record[0];
4451 unsigned LocalBaseSubmoduleID = Record[1];
4452 if (F.LocalNumSubmodules > 0) {
4453 // Introduce the global -> local mapping for submodules within this
4454 // module.
4455 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4456
4457 // Introduce the local -> global mapping for submodules within this
4458 // module.
4459 F.SubmoduleRemap.insertOrReplace(
4460 std::make_pair(LocalBaseSubmoduleID,
4461 F.BaseSubmoduleID - LocalBaseSubmoduleID));
4462
4463 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4464 }
4465 break;
4466 }
4467
4468 case SUBMODULE_IMPORTS: {
4469 if (First) {
4470 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004471 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004472 }
4473
4474 if (!CurrentModule)
4475 break;
4476
4477 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004478 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004479 Unresolved.File = &F;
4480 Unresolved.Mod = CurrentModule;
4481 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004482 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004483 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004484 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004485 }
4486 break;
4487 }
4488
4489 case SUBMODULE_EXPORTS: {
4490 if (First) {
4491 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004492 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004493 }
4494
4495 if (!CurrentModule)
4496 break;
4497
4498 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004499 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004500 Unresolved.File = &F;
4501 Unresolved.Mod = CurrentModule;
4502 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004503 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004504 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004505 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004506 }
4507
4508 // Once we've loaded the set of exports, there's no reason to keep
4509 // the parsed, unresolved exports around.
4510 CurrentModule->UnresolvedExports.clear();
4511 break;
4512 }
4513 case SUBMODULE_REQUIRES: {
4514 if (First) {
4515 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004516 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004517 }
4518
4519 if (!CurrentModule)
4520 break;
4521
Richard Smitha3feee22013-10-28 22:18:19 +00004522 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004523 Context.getTargetInfo());
4524 break;
4525 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004526
4527 case SUBMODULE_LINK_LIBRARY:
4528 if (First) {
4529 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004530 return Failure;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004531 }
4532
4533 if (!CurrentModule)
4534 break;
4535
4536 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004537 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004538 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004539
4540 case SUBMODULE_CONFIG_MACRO:
4541 if (First) {
4542 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004543 return Failure;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004544 }
4545
4546 if (!CurrentModule)
4547 break;
4548
4549 CurrentModule->ConfigMacros.push_back(Blob.str());
4550 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004551
4552 case SUBMODULE_CONFLICT: {
4553 if (First) {
4554 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004555 return Failure;
Douglas Gregorfb912652013-03-20 21:10:35 +00004556 }
4557
4558 if (!CurrentModule)
4559 break;
4560
4561 UnresolvedModuleRef Unresolved;
4562 Unresolved.File = &F;
4563 Unresolved.Mod = CurrentModule;
4564 Unresolved.ID = Record[0];
4565 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4566 Unresolved.IsWildcard = false;
4567 Unresolved.String = Blob;
4568 UnresolvedModuleRefs.push_back(Unresolved);
4569 break;
4570 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004571 }
4572 }
4573}
4574
4575/// \brief Parse the record that corresponds to a LangOptions data
4576/// structure.
4577///
4578/// This routine parses the language options from the AST file and then gives
4579/// them to the AST listener if one is set.
4580///
4581/// \returns true if the listener deems the file unacceptable, false otherwise.
4582bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4583 bool Complain,
4584 ASTReaderListener &Listener) {
4585 LangOptions LangOpts;
4586 unsigned Idx = 0;
4587#define LANGOPT(Name, Bits, Default, Description) \
4588 LangOpts.Name = Record[Idx++];
4589#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4590 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4591#include "clang/Basic/LangOptions.def"
Will Dietzf54319c2013-01-18 11:30:38 +00004592#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
4593#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004594
4595 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4596 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4597 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4598
4599 unsigned Length = Record[Idx++];
4600 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4601 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004602
4603 Idx += Length;
4604
4605 // Comment options.
4606 for (unsigned N = Record[Idx++]; N; --N) {
4607 LangOpts.CommentOpts.BlockCommandNames.push_back(
4608 ReadString(Record, Idx));
4609 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004610 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004611
Guy Benyei11169dd2012-12-18 14:30:41 +00004612 return Listener.ReadLanguageOptions(LangOpts, Complain);
4613}
4614
4615bool ASTReader::ParseTargetOptions(const RecordData &Record,
4616 bool Complain,
4617 ASTReaderListener &Listener) {
4618 unsigned Idx = 0;
4619 TargetOptions TargetOpts;
4620 TargetOpts.Triple = ReadString(Record, Idx);
4621 TargetOpts.CPU = ReadString(Record, Idx);
4622 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004623 for (unsigned N = Record[Idx++]; N; --N) {
4624 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4625 }
4626 for (unsigned N = Record[Idx++]; N; --N) {
4627 TargetOpts.Features.push_back(ReadString(Record, Idx));
4628 }
4629
4630 return Listener.ReadTargetOptions(TargetOpts, Complain);
4631}
4632
4633bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4634 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004635 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004636 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004637#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004638#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004639 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004640#include "clang/Basic/DiagnosticOptions.def"
4641
4642 for (unsigned N = Record[Idx++]; N; --N) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004643 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004644 }
4645
4646 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4647}
4648
4649bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4650 ASTReaderListener &Listener) {
4651 FileSystemOptions FSOpts;
4652 unsigned Idx = 0;
4653 FSOpts.WorkingDir = ReadString(Record, Idx);
4654 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4655}
4656
4657bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4658 bool Complain,
4659 ASTReaderListener &Listener) {
4660 HeaderSearchOptions HSOpts;
4661 unsigned Idx = 0;
4662 HSOpts.Sysroot = ReadString(Record, Idx);
4663
4664 // Include entries.
4665 for (unsigned N = Record[Idx++]; N; --N) {
4666 std::string Path = ReadString(Record, Idx);
4667 frontend::IncludeDirGroup Group
4668 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004669 bool IsFramework = Record[Idx++];
4670 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004671 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004672 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004673 }
4674
4675 // System header prefixes.
4676 for (unsigned N = Record[Idx++]; N; --N) {
4677 std::string Prefix = ReadString(Record, Idx);
4678 bool IsSystemHeader = Record[Idx++];
4679 HSOpts.SystemHeaderPrefixes.push_back(
4680 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4681 }
4682
4683 HSOpts.ResourceDir = ReadString(Record, Idx);
4684 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004685 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004686 HSOpts.DisableModuleHash = Record[Idx++];
4687 HSOpts.UseBuiltinIncludes = Record[Idx++];
4688 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4689 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4690 HSOpts.UseLibcxx = Record[Idx++];
4691
4692 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4693}
4694
4695bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4696 bool Complain,
4697 ASTReaderListener &Listener,
4698 std::string &SuggestedPredefines) {
4699 PreprocessorOptions PPOpts;
4700 unsigned Idx = 0;
4701
4702 // Macro definitions/undefs
4703 for (unsigned N = Record[Idx++]; N; --N) {
4704 std::string Macro = ReadString(Record, Idx);
4705 bool IsUndef = Record[Idx++];
4706 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4707 }
4708
4709 // Includes
4710 for (unsigned N = Record[Idx++]; N; --N) {
4711 PPOpts.Includes.push_back(ReadString(Record, Idx));
4712 }
4713
4714 // Macro Includes
4715 for (unsigned N = Record[Idx++]; N; --N) {
4716 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4717 }
4718
4719 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004720 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004721 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4722 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4723 PPOpts.ObjCXXARCStandardLibrary =
4724 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4725 SuggestedPredefines.clear();
4726 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4727 SuggestedPredefines);
4728}
4729
4730std::pair<ModuleFile *, unsigned>
4731ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4732 GlobalPreprocessedEntityMapType::iterator
4733 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4734 assert(I != GlobalPreprocessedEntityMap.end() &&
4735 "Corrupted global preprocessed entity map");
4736 ModuleFile *M = I->second;
4737 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4738 return std::make_pair(M, LocalIndex);
4739}
4740
4741std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4742ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4743 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4744 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4745 Mod.NumPreprocessedEntities);
4746
4747 return std::make_pair(PreprocessingRecord::iterator(),
4748 PreprocessingRecord::iterator());
4749}
4750
4751std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4752ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4753 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4754 ModuleDeclIterator(this, &Mod,
4755 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4756}
4757
4758PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4759 PreprocessedEntityID PPID = Index+1;
4760 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4761 ModuleFile &M = *PPInfo.first;
4762 unsigned LocalIndex = PPInfo.second;
4763 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4764
Guy Benyei11169dd2012-12-18 14:30:41 +00004765 if (!PP.getPreprocessingRecord()) {
4766 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004767 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004768 }
4769
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004770 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4771 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4772
4773 llvm::BitstreamEntry Entry =
4774 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4775 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004776 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004777
Guy Benyei11169dd2012-12-18 14:30:41 +00004778 // Read the record.
4779 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4780 ReadSourceLocation(M, PPOffs.End));
4781 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004782 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004783 RecordData Record;
4784 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004785 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4786 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004787 switch (RecType) {
4788 case PPD_MACRO_EXPANSION: {
4789 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004790 IdentifierInfo *Name = nullptr;
4791 MacroDefinition *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004792 if (isBuiltin)
4793 Name = getLocalIdentifier(M, Record[1]);
4794 else {
4795 PreprocessedEntityID
4796 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4797 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4798 }
4799
4800 MacroExpansion *ME;
4801 if (isBuiltin)
4802 ME = new (PPRec) MacroExpansion(Name, Range);
4803 else
4804 ME = new (PPRec) MacroExpansion(Def, Range);
4805
4806 return ME;
4807 }
4808
4809 case PPD_MACRO_DEFINITION: {
4810 // Decode the identifier info and then check again; if the macro is
4811 // still defined and associated with the identifier,
4812 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4813 MacroDefinition *MD
4814 = new (PPRec) MacroDefinition(II, Range);
4815
4816 if (DeserializationListener)
4817 DeserializationListener->MacroDefinitionRead(PPID, MD);
4818
4819 return MD;
4820 }
4821
4822 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004823 const char *FullFileNameStart = Blob.data() + Record[0];
4824 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004825 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004826 if (!FullFileName.empty())
4827 File = PP.getFileManager().getFile(FullFileName);
4828
4829 // FIXME: Stable encoding
4830 InclusionDirective::InclusionKind Kind
4831 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4832 InclusionDirective *ID
4833 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004834 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004835 Record[1], Record[3],
4836 File,
4837 Range);
4838 return ID;
4839 }
4840 }
4841
4842 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4843}
4844
4845/// \brief \arg SLocMapI points at a chunk of a module that contains no
4846/// preprocessed entities or the entities it contains are not the ones we are
4847/// looking for. Find the next module that contains entities and return the ID
4848/// of the first entry.
4849PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4850 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4851 ++SLocMapI;
4852 for (GlobalSLocOffsetMapType::const_iterator
4853 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4854 ModuleFile &M = *SLocMapI->second;
4855 if (M.NumPreprocessedEntities)
4856 return M.BasePreprocessedEntityID;
4857 }
4858
4859 return getTotalNumPreprocessedEntities();
4860}
4861
4862namespace {
4863
4864template <unsigned PPEntityOffset::*PPLoc>
4865struct PPEntityComp {
4866 const ASTReader &Reader;
4867 ModuleFile &M;
4868
4869 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4870
4871 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4872 SourceLocation LHS = getLoc(L);
4873 SourceLocation RHS = getLoc(R);
4874 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4875 }
4876
4877 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4878 SourceLocation LHS = getLoc(L);
4879 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4880 }
4881
4882 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4883 SourceLocation RHS = getLoc(R);
4884 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4885 }
4886
4887 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4888 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4889 }
4890};
4891
4892}
4893
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004894PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4895 bool EndsAfter) const {
4896 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004897 return getTotalNumPreprocessedEntities();
4898
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004899 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4900 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004901 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4902 "Corrupted global sloc offset map");
4903
4904 if (SLocMapI->second->NumPreprocessedEntities == 0)
4905 return findNextPreprocessedEntity(SLocMapI);
4906
4907 ModuleFile &M = *SLocMapI->second;
4908 typedef const PPEntityOffset *pp_iterator;
4909 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4910 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4911
4912 size_t Count = M.NumPreprocessedEntities;
4913 size_t Half;
4914 pp_iterator First = pp_begin;
4915 pp_iterator PPI;
4916
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004917 if (EndsAfter) {
4918 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4919 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4920 } else {
4921 // Do a binary search manually instead of using std::lower_bound because
4922 // The end locations of entities may be unordered (when a macro expansion
4923 // is inside another macro argument), but for this case it is not important
4924 // whether we get the first macro expansion or its containing macro.
4925 while (Count > 0) {
4926 Half = Count / 2;
4927 PPI = First;
4928 std::advance(PPI, Half);
4929 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4930 Loc)) {
4931 First = PPI;
4932 ++First;
4933 Count = Count - Half - 1;
4934 } else
4935 Count = Half;
4936 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004937 }
4938
4939 if (PPI == pp_end)
4940 return findNextPreprocessedEntity(SLocMapI);
4941
4942 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4943}
4944
Guy Benyei11169dd2012-12-18 14:30:41 +00004945/// \brief Returns a pair of [Begin, End) indices of preallocated
4946/// preprocessed entities that \arg Range encompasses.
4947std::pair<unsigned, unsigned>
4948 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4949 if (Range.isInvalid())
4950 return std::make_pair(0,0);
4951 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4952
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004953 PreprocessedEntityID BeginID =
4954 findPreprocessedEntity(Range.getBegin(), false);
4955 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004956 return std::make_pair(BeginID, EndID);
4957}
4958
4959/// \brief Optionally returns true or false if the preallocated preprocessed
4960/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004961Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004962 FileID FID) {
4963 if (FID.isInvalid())
4964 return false;
4965
4966 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4967 ModuleFile &M = *PPInfo.first;
4968 unsigned LocalIndex = PPInfo.second;
4969 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4970
4971 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4972 if (Loc.isInvalid())
4973 return false;
4974
4975 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4976 return true;
4977 else
4978 return false;
4979}
4980
4981namespace {
4982 /// \brief Visitor used to search for information about a header file.
4983 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004984 const FileEntry *FE;
4985
David Blaikie05785d12013-02-20 22:23:23 +00004986 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004987
4988 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004989 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4990 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004991
4992 static bool visit(ModuleFile &M, void *UserData) {
4993 HeaderFileInfoVisitor *This
4994 = static_cast<HeaderFileInfoVisitor *>(UserData);
4995
Guy Benyei11169dd2012-12-18 14:30:41 +00004996 HeaderFileInfoLookupTable *Table
4997 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4998 if (!Table)
4999 return false;
5000
5001 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00005002 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005003 if (Pos == Table->end())
5004 return false;
5005
5006 This->HFI = *Pos;
5007 return true;
5008 }
5009
David Blaikie05785d12013-02-20 22:23:23 +00005010 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005011 };
5012}
5013
5014HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005015 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005016 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005017 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005018 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005019
5020 return HeaderFileInfo();
5021}
5022
5023void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5024 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005025 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005026 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5027 ModuleFile &F = *(*I);
5028 unsigned Idx = 0;
5029 DiagStates.clear();
5030 assert(!Diag.DiagStates.empty());
5031 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5032 while (Idx < F.PragmaDiagMappings.size()) {
5033 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5034 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5035 if (DiagStateID != 0) {
5036 Diag.DiagStatePoints.push_back(
5037 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5038 FullSourceLoc(Loc, SourceMgr)));
5039 continue;
5040 }
5041
5042 assert(DiagStateID == 0);
5043 // A new DiagState was created here.
5044 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5045 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5046 DiagStates.push_back(NewState);
5047 Diag.DiagStatePoints.push_back(
5048 DiagnosticsEngine::DiagStatePoint(NewState,
5049 FullSourceLoc(Loc, SourceMgr)));
5050 while (1) {
5051 assert(Idx < F.PragmaDiagMappings.size() &&
5052 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5053 if (Idx >= F.PragmaDiagMappings.size()) {
5054 break; // Something is messed up but at least avoid infinite loop in
5055 // release build.
5056 }
5057 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5058 if (DiagID == (unsigned)-1) {
5059 break; // no more diag/map pairs for this location.
5060 }
Alp Tokerc726c362014-06-10 09:31:37 +00005061 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5062 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5063 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005064 }
5065 }
5066 }
5067}
5068
5069/// \brief Get the correct cursor and offset for loading a type.
5070ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5071 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5072 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5073 ModuleFile *M = I->second;
5074 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5075}
5076
5077/// \brief Read and return the type with the given index..
5078///
5079/// The index is the type ID, shifted and minus the number of predefs. This
5080/// routine actually reads the record corresponding to the type at the given
5081/// location. It is a helper routine for GetType, which deals with reading type
5082/// IDs.
5083QualType ASTReader::readTypeRecord(unsigned Index) {
5084 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005085 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005086
5087 // Keep track of where we are in the stream, then jump back there
5088 // after reading this type.
5089 SavedStreamPosition SavedPosition(DeclsCursor);
5090
5091 ReadingKindTracker ReadingKind(Read_Type, *this);
5092
5093 // Note that we are loading a type record.
5094 Deserializing AType(this);
5095
5096 unsigned Idx = 0;
5097 DeclsCursor.JumpToBit(Loc.Offset);
5098 RecordData Record;
5099 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005100 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005101 case TYPE_EXT_QUAL: {
5102 if (Record.size() != 2) {
5103 Error("Incorrect encoding of extended qualifier type");
5104 return QualType();
5105 }
5106 QualType Base = readType(*Loc.F, Record, Idx);
5107 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5108 return Context.getQualifiedType(Base, Quals);
5109 }
5110
5111 case TYPE_COMPLEX: {
5112 if (Record.size() != 1) {
5113 Error("Incorrect encoding of complex type");
5114 return QualType();
5115 }
5116 QualType ElemType = readType(*Loc.F, Record, Idx);
5117 return Context.getComplexType(ElemType);
5118 }
5119
5120 case TYPE_POINTER: {
5121 if (Record.size() != 1) {
5122 Error("Incorrect encoding of pointer type");
5123 return QualType();
5124 }
5125 QualType PointeeType = readType(*Loc.F, Record, Idx);
5126 return Context.getPointerType(PointeeType);
5127 }
5128
Reid Kleckner8a365022013-06-24 17:51:48 +00005129 case TYPE_DECAYED: {
5130 if (Record.size() != 1) {
5131 Error("Incorrect encoding of decayed type");
5132 return QualType();
5133 }
5134 QualType OriginalType = readType(*Loc.F, Record, Idx);
5135 QualType DT = Context.getAdjustedParameterType(OriginalType);
5136 if (!isa<DecayedType>(DT))
5137 Error("Decayed type does not decay");
5138 return DT;
5139 }
5140
Reid Kleckner0503a872013-12-05 01:23:43 +00005141 case TYPE_ADJUSTED: {
5142 if (Record.size() != 2) {
5143 Error("Incorrect encoding of adjusted type");
5144 return QualType();
5145 }
5146 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5147 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5148 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5149 }
5150
Guy Benyei11169dd2012-12-18 14:30:41 +00005151 case TYPE_BLOCK_POINTER: {
5152 if (Record.size() != 1) {
5153 Error("Incorrect encoding of block pointer type");
5154 return QualType();
5155 }
5156 QualType PointeeType = readType(*Loc.F, Record, Idx);
5157 return Context.getBlockPointerType(PointeeType);
5158 }
5159
5160 case TYPE_LVALUE_REFERENCE: {
5161 if (Record.size() != 2) {
5162 Error("Incorrect encoding of lvalue reference type");
5163 return QualType();
5164 }
5165 QualType PointeeType = readType(*Loc.F, Record, Idx);
5166 return Context.getLValueReferenceType(PointeeType, Record[1]);
5167 }
5168
5169 case TYPE_RVALUE_REFERENCE: {
5170 if (Record.size() != 1) {
5171 Error("Incorrect encoding of rvalue reference type");
5172 return QualType();
5173 }
5174 QualType PointeeType = readType(*Loc.F, Record, Idx);
5175 return Context.getRValueReferenceType(PointeeType);
5176 }
5177
5178 case TYPE_MEMBER_POINTER: {
5179 if (Record.size() != 2) {
5180 Error("Incorrect encoding of member pointer type");
5181 return QualType();
5182 }
5183 QualType PointeeType = readType(*Loc.F, Record, Idx);
5184 QualType ClassType = readType(*Loc.F, Record, Idx);
5185 if (PointeeType.isNull() || ClassType.isNull())
5186 return QualType();
5187
5188 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5189 }
5190
5191 case TYPE_CONSTANT_ARRAY: {
5192 QualType ElementType = readType(*Loc.F, Record, Idx);
5193 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5194 unsigned IndexTypeQuals = Record[2];
5195 unsigned Idx = 3;
5196 llvm::APInt Size = ReadAPInt(Record, Idx);
5197 return Context.getConstantArrayType(ElementType, Size,
5198 ASM, IndexTypeQuals);
5199 }
5200
5201 case TYPE_INCOMPLETE_ARRAY: {
5202 QualType ElementType = readType(*Loc.F, Record, Idx);
5203 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5204 unsigned IndexTypeQuals = Record[2];
5205 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5206 }
5207
5208 case TYPE_VARIABLE_ARRAY: {
5209 QualType ElementType = readType(*Loc.F, Record, Idx);
5210 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5211 unsigned IndexTypeQuals = Record[2];
5212 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5213 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5214 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5215 ASM, IndexTypeQuals,
5216 SourceRange(LBLoc, RBLoc));
5217 }
5218
5219 case TYPE_VECTOR: {
5220 if (Record.size() != 3) {
5221 Error("incorrect encoding of vector type in AST file");
5222 return QualType();
5223 }
5224
5225 QualType ElementType = readType(*Loc.F, Record, Idx);
5226 unsigned NumElements = Record[1];
5227 unsigned VecKind = Record[2];
5228 return Context.getVectorType(ElementType, NumElements,
5229 (VectorType::VectorKind)VecKind);
5230 }
5231
5232 case TYPE_EXT_VECTOR: {
5233 if (Record.size() != 3) {
5234 Error("incorrect encoding of extended vector type in AST file");
5235 return QualType();
5236 }
5237
5238 QualType ElementType = readType(*Loc.F, Record, Idx);
5239 unsigned NumElements = Record[1];
5240 return Context.getExtVectorType(ElementType, NumElements);
5241 }
5242
5243 case TYPE_FUNCTION_NO_PROTO: {
5244 if (Record.size() != 6) {
5245 Error("incorrect encoding of no-proto function type");
5246 return QualType();
5247 }
5248 QualType ResultType = readType(*Loc.F, Record, Idx);
5249 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5250 (CallingConv)Record[4], Record[5]);
5251 return Context.getFunctionNoProtoType(ResultType, Info);
5252 }
5253
5254 case TYPE_FUNCTION_PROTO: {
5255 QualType ResultType = readType(*Loc.F, Record, Idx);
5256
5257 FunctionProtoType::ExtProtoInfo EPI;
5258 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5259 /*hasregparm*/ Record[2],
5260 /*regparm*/ Record[3],
5261 static_cast<CallingConv>(Record[4]),
5262 /*produces*/ Record[5]);
5263
5264 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005265
5266 EPI.Variadic = Record[Idx++];
5267 EPI.HasTrailingReturn = Record[Idx++];
5268 EPI.TypeQuals = Record[Idx++];
5269 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005270 SmallVector<QualType, 8> ExceptionStorage;
5271 readExceptionSpec(*Loc.F, ExceptionStorage, EPI, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005272
5273 unsigned NumParams = Record[Idx++];
5274 SmallVector<QualType, 16> ParamTypes;
5275 for (unsigned I = 0; I != NumParams; ++I)
5276 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5277
Jordan Rose5c382722013-03-08 21:51:21 +00005278 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005279 }
5280
5281 case TYPE_UNRESOLVED_USING: {
5282 unsigned Idx = 0;
5283 return Context.getTypeDeclType(
5284 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5285 }
5286
5287 case TYPE_TYPEDEF: {
5288 if (Record.size() != 2) {
5289 Error("incorrect encoding of typedef type");
5290 return QualType();
5291 }
5292 unsigned Idx = 0;
5293 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5294 QualType Canonical = readType(*Loc.F, Record, Idx);
5295 if (!Canonical.isNull())
5296 Canonical = Context.getCanonicalType(Canonical);
5297 return Context.getTypedefType(Decl, Canonical);
5298 }
5299
5300 case TYPE_TYPEOF_EXPR:
5301 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5302
5303 case TYPE_TYPEOF: {
5304 if (Record.size() != 1) {
5305 Error("incorrect encoding of typeof(type) in AST file");
5306 return QualType();
5307 }
5308 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5309 return Context.getTypeOfType(UnderlyingType);
5310 }
5311
5312 case TYPE_DECLTYPE: {
5313 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5314 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5315 }
5316
5317 case TYPE_UNARY_TRANSFORM: {
5318 QualType BaseType = readType(*Loc.F, Record, Idx);
5319 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5320 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5321 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5322 }
5323
Richard Smith74aeef52013-04-26 16:15:35 +00005324 case TYPE_AUTO: {
5325 QualType Deduced = readType(*Loc.F, Record, Idx);
5326 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005327 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005328 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005329 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005330
5331 case TYPE_RECORD: {
5332 if (Record.size() != 2) {
5333 Error("incorrect encoding of record type");
5334 return QualType();
5335 }
5336 unsigned Idx = 0;
5337 bool IsDependent = Record[Idx++];
5338 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5339 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5340 QualType T = Context.getRecordType(RD);
5341 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5342 return T;
5343 }
5344
5345 case TYPE_ENUM: {
5346 if (Record.size() != 2) {
5347 Error("incorrect encoding of enum type");
5348 return QualType();
5349 }
5350 unsigned Idx = 0;
5351 bool IsDependent = Record[Idx++];
5352 QualType T
5353 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5354 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5355 return T;
5356 }
5357
5358 case TYPE_ATTRIBUTED: {
5359 if (Record.size() != 3) {
5360 Error("incorrect encoding of attributed type");
5361 return QualType();
5362 }
5363 QualType modifiedType = readType(*Loc.F, Record, Idx);
5364 QualType equivalentType = readType(*Loc.F, Record, Idx);
5365 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5366 return Context.getAttributedType(kind, modifiedType, equivalentType);
5367 }
5368
5369 case TYPE_PAREN: {
5370 if (Record.size() != 1) {
5371 Error("incorrect encoding of paren type");
5372 return QualType();
5373 }
5374 QualType InnerType = readType(*Loc.F, Record, Idx);
5375 return Context.getParenType(InnerType);
5376 }
5377
5378 case TYPE_PACK_EXPANSION: {
5379 if (Record.size() != 2) {
5380 Error("incorrect encoding of pack expansion type");
5381 return QualType();
5382 }
5383 QualType Pattern = readType(*Loc.F, Record, Idx);
5384 if (Pattern.isNull())
5385 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005386 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005387 if (Record[1])
5388 NumExpansions = Record[1] - 1;
5389 return Context.getPackExpansionType(Pattern, NumExpansions);
5390 }
5391
5392 case TYPE_ELABORATED: {
5393 unsigned Idx = 0;
5394 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5395 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5396 QualType NamedType = readType(*Loc.F, Record, Idx);
5397 return Context.getElaboratedType(Keyword, NNS, NamedType);
5398 }
5399
5400 case TYPE_OBJC_INTERFACE: {
5401 unsigned Idx = 0;
5402 ObjCInterfaceDecl *ItfD
5403 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5404 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5405 }
5406
5407 case TYPE_OBJC_OBJECT: {
5408 unsigned Idx = 0;
5409 QualType Base = readType(*Loc.F, Record, Idx);
5410 unsigned NumProtos = Record[Idx++];
5411 SmallVector<ObjCProtocolDecl*, 4> Protos;
5412 for (unsigned I = 0; I != NumProtos; ++I)
5413 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5414 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5415 }
5416
5417 case TYPE_OBJC_OBJECT_POINTER: {
5418 unsigned Idx = 0;
5419 QualType Pointee = readType(*Loc.F, Record, Idx);
5420 return Context.getObjCObjectPointerType(Pointee);
5421 }
5422
5423 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5424 unsigned Idx = 0;
5425 QualType Parm = readType(*Loc.F, Record, Idx);
5426 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005427 return Context.getSubstTemplateTypeParmType(
5428 cast<TemplateTypeParmType>(Parm),
5429 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005430 }
5431
5432 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5433 unsigned Idx = 0;
5434 QualType Parm = readType(*Loc.F, Record, Idx);
5435 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5436 return Context.getSubstTemplateTypeParmPackType(
5437 cast<TemplateTypeParmType>(Parm),
5438 ArgPack);
5439 }
5440
5441 case TYPE_INJECTED_CLASS_NAME: {
5442 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5443 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5444 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5445 // for AST reading, too much interdependencies.
Richard Smithf17fdbd2014-04-24 02:25:27 +00005446 const Type *T;
5447 if (const Type *Existing = D->getTypeForDecl())
5448 T = Existing;
5449 else if (auto *Prev = D->getPreviousDecl())
5450 T = Prev->getTypeForDecl();
5451 else
5452 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
5453 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005454 }
5455
5456 case TYPE_TEMPLATE_TYPE_PARM: {
5457 unsigned Idx = 0;
5458 unsigned Depth = Record[Idx++];
5459 unsigned Index = Record[Idx++];
5460 bool Pack = Record[Idx++];
5461 TemplateTypeParmDecl *D
5462 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5463 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5464 }
5465
5466 case TYPE_DEPENDENT_NAME: {
5467 unsigned Idx = 0;
5468 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5469 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5470 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5471 QualType Canon = readType(*Loc.F, Record, Idx);
5472 if (!Canon.isNull())
5473 Canon = Context.getCanonicalType(Canon);
5474 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5475 }
5476
5477 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5478 unsigned Idx = 0;
5479 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5480 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5481 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5482 unsigned NumArgs = Record[Idx++];
5483 SmallVector<TemplateArgument, 8> Args;
5484 Args.reserve(NumArgs);
5485 while (NumArgs--)
5486 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5487 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5488 Args.size(), Args.data());
5489 }
5490
5491 case TYPE_DEPENDENT_SIZED_ARRAY: {
5492 unsigned Idx = 0;
5493
5494 // ArrayType
5495 QualType ElementType = readType(*Loc.F, Record, Idx);
5496 ArrayType::ArraySizeModifier ASM
5497 = (ArrayType::ArraySizeModifier)Record[Idx++];
5498 unsigned IndexTypeQuals = Record[Idx++];
5499
5500 // DependentSizedArrayType
5501 Expr *NumElts = ReadExpr(*Loc.F);
5502 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5503
5504 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5505 IndexTypeQuals, Brackets);
5506 }
5507
5508 case TYPE_TEMPLATE_SPECIALIZATION: {
5509 unsigned Idx = 0;
5510 bool IsDependent = Record[Idx++];
5511 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5512 SmallVector<TemplateArgument, 8> Args;
5513 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5514 QualType Underlying = readType(*Loc.F, Record, Idx);
5515 QualType T;
5516 if (Underlying.isNull())
5517 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5518 Args.size());
5519 else
5520 T = Context.getTemplateSpecializationType(Name, Args.data(),
5521 Args.size(), Underlying);
5522 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5523 return T;
5524 }
5525
5526 case TYPE_ATOMIC: {
5527 if (Record.size() != 1) {
5528 Error("Incorrect encoding of atomic type");
5529 return QualType();
5530 }
5531 QualType ValueType = readType(*Loc.F, Record, Idx);
5532 return Context.getAtomicType(ValueType);
5533 }
5534 }
5535 llvm_unreachable("Invalid TypeCode!");
5536}
5537
Richard Smith564417a2014-03-20 21:47:22 +00005538void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5539 SmallVectorImpl<QualType> &Exceptions,
5540 FunctionProtoType::ExtProtoInfo &EPI,
5541 const RecordData &Record, unsigned &Idx) {
5542 ExceptionSpecificationType EST =
5543 static_cast<ExceptionSpecificationType>(Record[Idx++]);
5544 EPI.ExceptionSpecType = EST;
5545 if (EST == EST_Dynamic) {
5546 EPI.NumExceptions = Record[Idx++];
5547 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
5548 Exceptions.push_back(readType(ModuleFile, Record, Idx));
5549 EPI.Exceptions = Exceptions.data();
5550 } else if (EST == EST_ComputedNoexcept) {
5551 EPI.NoexceptExpr = ReadExpr(ModuleFile);
5552 } else if (EST == EST_Uninstantiated) {
5553 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5554 EPI.ExceptionSpecTemplate =
5555 ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5556 } else if (EST == EST_Unevaluated) {
5557 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5558 }
5559}
5560
Guy Benyei11169dd2012-12-18 14:30:41 +00005561class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5562 ASTReader &Reader;
5563 ModuleFile &F;
5564 const ASTReader::RecordData &Record;
5565 unsigned &Idx;
5566
5567 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5568 unsigned &I) {
5569 return Reader.ReadSourceLocation(F, R, I);
5570 }
5571
5572 template<typename T>
5573 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5574 return Reader.ReadDeclAs<T>(F, Record, Idx);
5575 }
5576
5577public:
5578 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5579 const ASTReader::RecordData &Record, unsigned &Idx)
5580 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5581 { }
5582
5583 // We want compile-time assurance that we've enumerated all of
5584 // these, so unfortunately we have to declare them first, then
5585 // define them out-of-line.
5586#define ABSTRACT_TYPELOC(CLASS, PARENT)
5587#define TYPELOC(CLASS, PARENT) \
5588 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5589#include "clang/AST/TypeLocNodes.def"
5590
5591 void VisitFunctionTypeLoc(FunctionTypeLoc);
5592 void VisitArrayTypeLoc(ArrayTypeLoc);
5593};
5594
5595void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5596 // nothing to do
5597}
5598void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5599 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5600 if (TL.needsExtraLocalData()) {
5601 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5602 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5603 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5604 TL.setModeAttr(Record[Idx++]);
5605 }
5606}
5607void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5608 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5609}
5610void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5611 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5612}
Reid Kleckner8a365022013-06-24 17:51:48 +00005613void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5614 // nothing to do
5615}
Reid Kleckner0503a872013-12-05 01:23:43 +00005616void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5617 // nothing to do
5618}
Guy Benyei11169dd2012-12-18 14:30:41 +00005619void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5620 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5621}
5622void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5623 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5624}
5625void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5626 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5627}
5628void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5629 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5630 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5631}
5632void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5633 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5634 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5635 if (Record[Idx++])
5636 TL.setSizeExpr(Reader.ReadExpr(F));
5637 else
Craig Toppera13603a2014-05-22 05:54:18 +00005638 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005639}
5640void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5641 VisitArrayTypeLoc(TL);
5642}
5643void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5644 VisitArrayTypeLoc(TL);
5645}
5646void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5647 VisitArrayTypeLoc(TL);
5648}
5649void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5650 DependentSizedArrayTypeLoc TL) {
5651 VisitArrayTypeLoc(TL);
5652}
5653void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5654 DependentSizedExtVectorTypeLoc TL) {
5655 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5656}
5657void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5658 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5659}
5660void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5661 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5662}
5663void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5664 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5665 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5666 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5667 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005668 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5669 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005670 }
5671}
5672void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5673 VisitFunctionTypeLoc(TL);
5674}
5675void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5676 VisitFunctionTypeLoc(TL);
5677}
5678void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5679 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5680}
5681void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5682 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5683}
5684void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5685 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5686 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5687 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5688}
5689void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5690 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5691 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5692 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5693 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5694}
5695void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5696 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5697}
5698void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5699 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5700 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5701 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5702 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5703}
5704void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5705 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5706}
5707void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5708 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5709}
5710void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5711 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5712}
5713void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5714 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5715 if (TL.hasAttrOperand()) {
5716 SourceRange range;
5717 range.setBegin(ReadSourceLocation(Record, Idx));
5718 range.setEnd(ReadSourceLocation(Record, Idx));
5719 TL.setAttrOperandParensRange(range);
5720 }
5721 if (TL.hasAttrExprOperand()) {
5722 if (Record[Idx++])
5723 TL.setAttrExprOperand(Reader.ReadExpr(F));
5724 else
Craig Toppera13603a2014-05-22 05:54:18 +00005725 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005726 } else if (TL.hasAttrEnumOperand())
5727 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5728}
5729void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5730 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5731}
5732void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5733 SubstTemplateTypeParmTypeLoc TL) {
5734 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5735}
5736void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5737 SubstTemplateTypeParmPackTypeLoc TL) {
5738 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5739}
5740void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5741 TemplateSpecializationTypeLoc TL) {
5742 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5743 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5744 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5745 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5746 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5747 TL.setArgLocInfo(i,
5748 Reader.GetTemplateArgumentLocInfo(F,
5749 TL.getTypePtr()->getArg(i).getKind(),
5750 Record, Idx));
5751}
5752void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5753 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5754 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5755}
5756void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5757 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5758 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5759}
5760void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5761 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5762}
5763void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5764 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5765 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5766 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5767}
5768void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5769 DependentTemplateSpecializationTypeLoc TL) {
5770 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5771 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5772 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5773 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5774 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5775 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5776 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5777 TL.setArgLocInfo(I,
5778 Reader.GetTemplateArgumentLocInfo(F,
5779 TL.getTypePtr()->getArg(I).getKind(),
5780 Record, Idx));
5781}
5782void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5783 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5784}
5785void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5786 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5787}
5788void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5789 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5790 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5791 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5792 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5793 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5794}
5795void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5796 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5797}
5798void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5799 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5800 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5801 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5802}
5803
5804TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5805 const RecordData &Record,
5806 unsigned &Idx) {
5807 QualType InfoTy = readType(F, Record, Idx);
5808 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005809 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005810
5811 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5812 TypeLocReader TLR(*this, F, Record, Idx);
5813 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5814 TLR.Visit(TL);
5815 return TInfo;
5816}
5817
5818QualType ASTReader::GetType(TypeID ID) {
5819 unsigned FastQuals = ID & Qualifiers::FastMask;
5820 unsigned Index = ID >> Qualifiers::FastWidth;
5821
5822 if (Index < NUM_PREDEF_TYPE_IDS) {
5823 QualType T;
5824 switch ((PredefinedTypeIDs)Index) {
5825 case PREDEF_TYPE_NULL_ID: return QualType();
5826 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5827 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5828
5829 case PREDEF_TYPE_CHAR_U_ID:
5830 case PREDEF_TYPE_CHAR_S_ID:
5831 // FIXME: Check that the signedness of CharTy is correct!
5832 T = Context.CharTy;
5833 break;
5834
5835 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5836 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5837 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5838 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5839 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5840 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5841 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5842 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5843 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5844 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5845 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5846 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5847 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5848 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5849 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5850 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5851 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5852 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5853 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5854 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5855 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5856 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5857 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5858 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5859 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5860 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5861 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5862 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005863 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5864 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5865 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5866 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5867 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5868 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005869 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005870 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005871 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5872
5873 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5874 T = Context.getAutoRRefDeductType();
5875 break;
5876
5877 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5878 T = Context.ARCUnbridgedCastTy;
5879 break;
5880
5881 case PREDEF_TYPE_VA_LIST_TAG:
5882 T = Context.getVaListTagType();
5883 break;
5884
5885 case PREDEF_TYPE_BUILTIN_FN:
5886 T = Context.BuiltinFnTy;
5887 break;
5888 }
5889
5890 assert(!T.isNull() && "Unknown predefined type");
5891 return T.withFastQualifiers(FastQuals);
5892 }
5893
5894 Index -= NUM_PREDEF_TYPE_IDS;
5895 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5896 if (TypesLoaded[Index].isNull()) {
5897 TypesLoaded[Index] = readTypeRecord(Index);
5898 if (TypesLoaded[Index].isNull())
5899 return QualType();
5900
5901 TypesLoaded[Index]->setFromAST();
5902 if (DeserializationListener)
5903 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5904 TypesLoaded[Index]);
5905 }
5906
5907 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5908}
5909
5910QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5911 return GetType(getGlobalTypeID(F, LocalID));
5912}
5913
5914serialization::TypeID
5915ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5916 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5917 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5918
5919 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5920 return LocalID;
5921
5922 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5923 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5924 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5925
5926 unsigned GlobalIndex = LocalIndex + I->second;
5927 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5928}
5929
5930TemplateArgumentLocInfo
5931ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5932 TemplateArgument::ArgKind Kind,
5933 const RecordData &Record,
5934 unsigned &Index) {
5935 switch (Kind) {
5936 case TemplateArgument::Expression:
5937 return ReadExpr(F);
5938 case TemplateArgument::Type:
5939 return GetTypeSourceInfo(F, Record, Index);
5940 case TemplateArgument::Template: {
5941 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5942 Index);
5943 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5944 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5945 SourceLocation());
5946 }
5947 case TemplateArgument::TemplateExpansion: {
5948 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5949 Index);
5950 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5951 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5952 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5953 EllipsisLoc);
5954 }
5955 case TemplateArgument::Null:
5956 case TemplateArgument::Integral:
5957 case TemplateArgument::Declaration:
5958 case TemplateArgument::NullPtr:
5959 case TemplateArgument::Pack:
5960 // FIXME: Is this right?
5961 return TemplateArgumentLocInfo();
5962 }
5963 llvm_unreachable("unexpected template argument loc");
5964}
5965
5966TemplateArgumentLoc
5967ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5968 const RecordData &Record, unsigned &Index) {
5969 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5970
5971 if (Arg.getKind() == TemplateArgument::Expression) {
5972 if (Record[Index++]) // bool InfoHasSameExpr.
5973 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5974 }
5975 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5976 Record, Index));
5977}
5978
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005979const ASTTemplateArgumentListInfo*
5980ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5981 const RecordData &Record,
5982 unsigned &Index) {
5983 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5984 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5985 unsigned NumArgsAsWritten = Record[Index++];
5986 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5987 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5988 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5989 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5990}
5991
Guy Benyei11169dd2012-12-18 14:30:41 +00005992Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5993 return GetDecl(ID);
5994}
5995
Richard Smith053f6c62014-05-16 23:01:30 +00005996void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005997 if (NumCurrentElementsDeserializing) {
5998 // We arrange to not care about the complete redeclaration chain while we're
5999 // deserializing. Just remember that the AST has marked this one as complete
6000 // but that it's not actually complete yet, so we know we still need to
6001 // complete it later.
6002 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6003 return;
6004 }
6005
Richard Smith053f6c62014-05-16 23:01:30 +00006006 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6007
6008 // Recursively ensure that the decl context itself is complete
6009 // (in particular, this matters if the decl context is a namespace).
6010 //
6011 // FIXME: This should be performed by lookup instead of here.
6012 cast<Decl>(DC)->getMostRecentDecl();
6013
6014 // If this is a named declaration, complete it by looking it up
6015 // within its context.
6016 //
6017 // FIXME: We don't currently handle the cases where we can't do this;
6018 // merging a class definition that contains unnamed entities should merge
6019 // those entities. Likewise, merging a function definition should merge
6020 // all mergeable entities within it.
6021 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6022 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6023 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
6024 auto *II = Name.getAsIdentifierInfo();
6025 if (isa<TranslationUnitDecl>(DC) && II) {
6026 // Outside of C++, we don't have a lookup table for the TU, so update
6027 // the identifier instead. In C++, either way should work fine.
6028 if (II->isOutOfDate())
6029 updateOutOfDateIdentifier(*II);
6030 } else
6031 DC->lookup(Name);
6032 }
6033 }
6034}
6035
Richard Smithcd45dbc2014-04-19 03:48:30 +00006036uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6037 const RecordData &Record,
6038 unsigned &Idx) {
6039 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6040 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006041 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006042 }
6043
Guy Benyei11169dd2012-12-18 14:30:41 +00006044 unsigned LocalID = Record[Idx++];
6045 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6046}
6047
6048CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6049 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006050 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006051 SavedStreamPosition SavedPosition(Cursor);
6052 Cursor.JumpToBit(Loc.Offset);
6053 ReadingKindTracker ReadingKind(Read_Decl, *this);
6054 RecordData Record;
6055 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006056 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006057 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006058 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006059 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006060 }
6061
6062 unsigned Idx = 0;
6063 unsigned NumBases = Record[Idx++];
6064 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6065 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6066 for (unsigned I = 0; I != NumBases; ++I)
6067 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6068 return Bases;
6069}
6070
6071serialization::DeclID
6072ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6073 if (LocalID < NUM_PREDEF_DECL_IDS)
6074 return LocalID;
6075
6076 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6077 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6078 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6079
6080 return LocalID + I->second;
6081}
6082
6083bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6084 ModuleFile &M) const {
6085 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6086 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6087 return &M == I->second;
6088}
6089
Douglas Gregor9f782892013-01-21 15:25:38 +00006090ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006091 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006092 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006093 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6094 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6095 return I->second;
6096}
6097
6098SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6099 if (ID < NUM_PREDEF_DECL_IDS)
6100 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006101
Guy Benyei11169dd2012-12-18 14:30:41 +00006102 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6103
6104 if (Index > DeclsLoaded.size()) {
6105 Error("declaration ID out-of-range for AST file");
6106 return SourceLocation();
6107 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006108
Guy Benyei11169dd2012-12-18 14:30:41 +00006109 if (Decl *D = DeclsLoaded[Index])
6110 return D->getLocation();
6111
6112 unsigned RawLocation = 0;
6113 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6114 return ReadSourceLocation(*Rec.F, RawLocation);
6115}
6116
Richard Smithcd45dbc2014-04-19 03:48:30 +00006117Decl *ASTReader::GetExistingDecl(DeclID ID) {
6118 if (ID < NUM_PREDEF_DECL_IDS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006119 switch ((PredefinedDeclIDs)ID) {
6120 case PREDEF_DECL_NULL_ID:
Craig Toppera13603a2014-05-22 05:54:18 +00006121 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006122
Guy Benyei11169dd2012-12-18 14:30:41 +00006123 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6124 return Context.getTranslationUnitDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006125
Guy Benyei11169dd2012-12-18 14:30:41 +00006126 case PREDEF_DECL_OBJC_ID_ID:
6127 return Context.getObjCIdDecl();
6128
6129 case PREDEF_DECL_OBJC_SEL_ID:
6130 return Context.getObjCSelDecl();
6131
6132 case PREDEF_DECL_OBJC_CLASS_ID:
6133 return Context.getObjCClassDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006134
Guy Benyei11169dd2012-12-18 14:30:41 +00006135 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6136 return Context.getObjCProtocolDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006137
Guy Benyei11169dd2012-12-18 14:30:41 +00006138 case PREDEF_DECL_INT_128_ID:
6139 return Context.getInt128Decl();
6140
6141 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6142 return Context.getUInt128Decl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006143
Guy Benyei11169dd2012-12-18 14:30:41 +00006144 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6145 return Context.getObjCInstanceTypeDecl();
6146
6147 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6148 return Context.getBuiltinVaListDecl();
6149 }
6150 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006151
Guy Benyei11169dd2012-12-18 14:30:41 +00006152 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6153
6154 if (Index >= DeclsLoaded.size()) {
6155 assert(0 && "declaration ID out-of-range for AST file");
6156 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006157 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006158 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006159
6160 return DeclsLoaded[Index];
6161}
6162
6163Decl *ASTReader::GetDecl(DeclID ID) {
6164 if (ID < NUM_PREDEF_DECL_IDS)
6165 return GetExistingDecl(ID);
6166
6167 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6168
6169 if (Index >= DeclsLoaded.size()) {
6170 assert(0 && "declaration ID out-of-range for AST file");
6171 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006172 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006173 }
6174
Guy Benyei11169dd2012-12-18 14:30:41 +00006175 if (!DeclsLoaded[Index]) {
6176 ReadDeclRecord(ID);
6177 if (DeserializationListener)
6178 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6179 }
6180
6181 return DeclsLoaded[Index];
6182}
6183
6184DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6185 DeclID GlobalID) {
6186 if (GlobalID < NUM_PREDEF_DECL_IDS)
6187 return GlobalID;
6188
6189 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6190 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6191 ModuleFile *Owner = I->second;
6192
6193 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6194 = M.GlobalToLocalDeclIDs.find(Owner);
6195 if (Pos == M.GlobalToLocalDeclIDs.end())
6196 return 0;
6197
6198 return GlobalID - Owner->BaseDeclID + Pos->second;
6199}
6200
6201serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6202 const RecordData &Record,
6203 unsigned &Idx) {
6204 if (Idx >= Record.size()) {
6205 Error("Corrupted AST file");
6206 return 0;
6207 }
6208
6209 return getGlobalDeclID(F, Record[Idx++]);
6210}
6211
6212/// \brief Resolve the offset of a statement into a statement.
6213///
6214/// This operation will read a new statement from the external
6215/// source each time it is called, and is meant to be used via a
6216/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6217Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6218 // Switch case IDs are per Decl.
6219 ClearSwitchCaseIDs();
6220
6221 // Offset here is a global offset across the entire chain.
6222 RecordLocation Loc = getLocalBitOffset(Offset);
6223 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6224 return ReadStmtFromStream(*Loc.F);
6225}
6226
6227namespace {
6228 class FindExternalLexicalDeclsVisitor {
6229 ASTReader &Reader;
6230 const DeclContext *DC;
6231 bool (*isKindWeWant)(Decl::Kind);
6232
6233 SmallVectorImpl<Decl*> &Decls;
6234 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6235
6236 public:
6237 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6238 bool (*isKindWeWant)(Decl::Kind),
6239 SmallVectorImpl<Decl*> &Decls)
6240 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6241 {
6242 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6243 PredefsVisited[I] = false;
6244 }
6245
6246 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6247 if (Preorder)
6248 return false;
6249
6250 FindExternalLexicalDeclsVisitor *This
6251 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6252
6253 ModuleFile::DeclContextInfosMap::iterator Info
6254 = M.DeclContextInfos.find(This->DC);
6255 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6256 return false;
6257
6258 // Load all of the declaration IDs
6259 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6260 *IDE = ID + Info->second.NumLexicalDecls;
6261 ID != IDE; ++ID) {
6262 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6263 continue;
6264
6265 // Don't add predefined declarations to the lexical context more
6266 // than once.
6267 if (ID->second < NUM_PREDEF_DECL_IDS) {
6268 if (This->PredefsVisited[ID->second])
6269 continue;
6270
6271 This->PredefsVisited[ID->second] = true;
6272 }
6273
6274 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6275 if (!This->DC->isDeclInLexicalTraversal(D))
6276 This->Decls.push_back(D);
6277 }
6278 }
6279
6280 return false;
6281 }
6282 };
6283}
6284
6285ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6286 bool (*isKindWeWant)(Decl::Kind),
6287 SmallVectorImpl<Decl*> &Decls) {
6288 // There might be lexical decls in multiple modules, for the TU at
6289 // least. Walk all of the modules in the order they were loaded.
6290 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6291 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6292 ++NumLexicalDeclContextsRead;
6293 return ELR_Success;
6294}
6295
6296namespace {
6297
6298class DeclIDComp {
6299 ASTReader &Reader;
6300 ModuleFile &Mod;
6301
6302public:
6303 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6304
6305 bool operator()(LocalDeclID L, LocalDeclID R) const {
6306 SourceLocation LHS = getLocation(L);
6307 SourceLocation RHS = getLocation(R);
6308 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6309 }
6310
6311 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6312 SourceLocation RHS = getLocation(R);
6313 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6314 }
6315
6316 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6317 SourceLocation LHS = getLocation(L);
6318 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6319 }
6320
6321 SourceLocation getLocation(LocalDeclID ID) const {
6322 return Reader.getSourceManager().getFileLoc(
6323 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6324 }
6325};
6326
6327}
6328
6329void ASTReader::FindFileRegionDecls(FileID File,
6330 unsigned Offset, unsigned Length,
6331 SmallVectorImpl<Decl *> &Decls) {
6332 SourceManager &SM = getSourceManager();
6333
6334 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6335 if (I == FileDeclIDs.end())
6336 return;
6337
6338 FileDeclsInfo &DInfo = I->second;
6339 if (DInfo.Decls.empty())
6340 return;
6341
6342 SourceLocation
6343 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6344 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6345
6346 DeclIDComp DIDComp(*this, *DInfo.Mod);
6347 ArrayRef<serialization::LocalDeclID>::iterator
6348 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6349 BeginLoc, DIDComp);
6350 if (BeginIt != DInfo.Decls.begin())
6351 --BeginIt;
6352
6353 // If we are pointing at a top-level decl inside an objc container, we need
6354 // to backtrack until we find it otherwise we will fail to report that the
6355 // region overlaps with an objc container.
6356 while (BeginIt != DInfo.Decls.begin() &&
6357 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6358 ->isTopLevelDeclInObjCContainer())
6359 --BeginIt;
6360
6361 ArrayRef<serialization::LocalDeclID>::iterator
6362 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6363 EndLoc, DIDComp);
6364 if (EndIt != DInfo.Decls.end())
6365 ++EndIt;
6366
6367 for (ArrayRef<serialization::LocalDeclID>::iterator
6368 DIt = BeginIt; DIt != EndIt; ++DIt)
6369 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6370}
6371
6372namespace {
6373 /// \brief ModuleFile visitor used to perform name lookup into a
6374 /// declaration context.
6375 class DeclContextNameLookupVisitor {
6376 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006377 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006378 DeclarationName Name;
6379 SmallVectorImpl<NamedDecl *> &Decls;
6380
6381 public:
6382 DeclContextNameLookupVisitor(ASTReader &Reader,
6383 SmallVectorImpl<const DeclContext *> &Contexts,
6384 DeclarationName Name,
6385 SmallVectorImpl<NamedDecl *> &Decls)
6386 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
6387
6388 static bool visit(ModuleFile &M, void *UserData) {
6389 DeclContextNameLookupVisitor *This
6390 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6391
6392 // Check whether we have any visible declaration information for
6393 // this context in this module.
6394 ModuleFile::DeclContextInfosMap::iterator Info;
6395 bool FoundInfo = false;
6396 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6397 Info = M.DeclContextInfos.find(This->Contexts[I]);
6398 if (Info != M.DeclContextInfos.end() &&
6399 Info->second.NameLookupTableData) {
6400 FoundInfo = true;
6401 break;
6402 }
6403 }
6404
6405 if (!FoundInfo)
6406 return false;
6407
6408 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006409 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006410 Info->second.NameLookupTableData;
6411 ASTDeclContextNameLookupTable::iterator Pos
6412 = LookupTable->find(This->Name);
6413 if (Pos == LookupTable->end())
6414 return false;
6415
6416 bool FoundAnything = false;
6417 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6418 for (; Data.first != Data.second; ++Data.first) {
6419 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6420 if (!ND)
6421 continue;
6422
6423 if (ND->getDeclName() != This->Name) {
6424 // A name might be null because the decl's redeclarable part is
6425 // currently read before reading its name. The lookup is triggered by
6426 // building that decl (likely indirectly), and so it is later in the
6427 // sense of "already existing" and can be ignored here.
6428 continue;
6429 }
6430
6431 // Record this declaration.
6432 FoundAnything = true;
6433 This->Decls.push_back(ND);
6434 }
6435
6436 return FoundAnything;
6437 }
6438 };
6439}
6440
Douglas Gregor9f782892013-01-21 15:25:38 +00006441/// \brief Retrieve the "definitive" module file for the definition of the
6442/// given declaration context, if there is one.
6443///
6444/// The "definitive" module file is the only place where we need to look to
6445/// find information about the declarations within the given declaration
6446/// context. For example, C++ and Objective-C classes, C structs/unions, and
6447/// Objective-C protocols, categories, and extensions are all defined in a
6448/// single place in the source code, so they have definitive module files
6449/// associated with them. C++ namespaces, on the other hand, can have
6450/// definitions in multiple different module files.
6451///
6452/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6453/// NDEBUG checking.
6454static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6455 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006456 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6457 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006458
Craig Toppera13603a2014-05-22 05:54:18 +00006459 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006460}
6461
Richard Smith9ce12e32013-02-07 03:30:24 +00006462bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006463ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6464 DeclarationName Name) {
6465 assert(DC->hasExternalVisibleStorage() &&
6466 "DeclContext has no visible decls in storage");
6467 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006468 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006469
6470 SmallVector<NamedDecl *, 64> Decls;
6471
6472 // Compute the declaration contexts we need to look into. Multiple such
6473 // declaration contexts occur when two declaration contexts from disjoint
6474 // modules get merged, e.g., when two namespaces with the same name are
6475 // independently defined in separate modules.
6476 SmallVector<const DeclContext *, 2> Contexts;
6477 Contexts.push_back(DC);
6478
6479 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006480 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006481 if (Merged != MergedDecls.end()) {
6482 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6483 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6484 }
6485 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006486 if (isa<CXXRecordDecl>(DC)) {
6487 auto Merged = MergedLookups.find(DC);
6488 if (Merged != MergedLookups.end())
6489 Contexts.insert(Contexts.end(), Merged->second.begin(),
6490 Merged->second.end());
6491 }
6492
Guy Benyei11169dd2012-12-18 14:30:41 +00006493 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor9f782892013-01-21 15:25:38 +00006494
6495 // If we can definitively determine which module file to look into,
6496 // only look there. Otherwise, look in all module files.
6497 ModuleFile *Definitive;
6498 if (Contexts.size() == 1 &&
6499 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
6500 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6501 } else {
6502 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6503 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006504 ++NumVisibleDeclContextsRead;
6505 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006506 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006507}
6508
6509namespace {
6510 /// \brief ModuleFile visitor used to retrieve all visible names in a
6511 /// declaration context.
6512 class DeclContextAllNamesVisitor {
6513 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006514 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006515 DeclsMap &Decls;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006516 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006517
6518 public:
6519 DeclContextAllNamesVisitor(ASTReader &Reader,
6520 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006521 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006522 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006523
6524 static bool visit(ModuleFile &M, void *UserData) {
6525 DeclContextAllNamesVisitor *This
6526 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6527
6528 // Check whether we have any visible declaration information for
6529 // this context in this module.
6530 ModuleFile::DeclContextInfosMap::iterator Info;
6531 bool FoundInfo = false;
6532 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6533 Info = M.DeclContextInfos.find(This->Contexts[I]);
6534 if (Info != M.DeclContextInfos.end() &&
6535 Info->second.NameLookupTableData) {
6536 FoundInfo = true;
6537 break;
6538 }
6539 }
6540
6541 if (!FoundInfo)
6542 return false;
6543
Richard Smith52e3fba2014-03-11 07:17:35 +00006544 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006545 Info->second.NameLookupTableData;
6546 bool FoundAnything = false;
6547 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006548 I = LookupTable->data_begin(), E = LookupTable->data_end();
6549 I != E;
6550 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006551 ASTDeclContextNameLookupTrait::data_type Data = *I;
6552 for (; Data.first != Data.second; ++Data.first) {
6553 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6554 *Data.first);
6555 if (!ND)
6556 continue;
6557
6558 // Record this declaration.
6559 FoundAnything = true;
6560 This->Decls[ND->getDeclName()].push_back(ND);
6561 }
6562 }
6563
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006564 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006565 }
6566 };
6567}
6568
6569void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6570 if (!DC->hasExternalVisibleStorage())
6571 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006572 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006573
6574 // Compute the declaration contexts we need to look into. Multiple such
6575 // declaration contexts occur when two declaration contexts from disjoint
6576 // modules get merged, e.g., when two namespaces with the same name are
6577 // independently defined in separate modules.
6578 SmallVector<const DeclContext *, 2> Contexts;
6579 Contexts.push_back(DC);
6580
6581 if (DC->isNamespace()) {
6582 MergedDeclsMap::iterator Merged
6583 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6584 if (Merged != MergedDecls.end()) {
6585 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6586 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6587 }
6588 }
6589
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006590 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6591 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006592 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6593 ++NumVisibleDeclContextsRead;
6594
Craig Topper79be4cd2013-07-05 04:33:53 +00006595 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006596 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6597 }
6598 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6599}
6600
6601/// \brief Under non-PCH compilation the consumer receives the objc methods
6602/// before receiving the implementation, and codegen depends on this.
6603/// We simulate this by deserializing and passing to consumer the methods of the
6604/// implementation before passing the deserialized implementation decl.
6605static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6606 ASTConsumer *Consumer) {
6607 assert(ImplD && Consumer);
6608
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006609 for (auto *I : ImplD->methods())
6610 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006611
6612 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6613}
6614
6615void ASTReader::PassInterestingDeclsToConsumer() {
6616 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006617
6618 if (PassingDeclsToConsumer)
6619 return;
6620
6621 // Guard variable to avoid recursively redoing the process of passing
6622 // decls to consumer.
6623 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6624 true);
6625
Guy Benyei11169dd2012-12-18 14:30:41 +00006626 while (!InterestingDecls.empty()) {
6627 Decl *D = InterestingDecls.front();
6628 InterestingDecls.pop_front();
6629
6630 PassInterestingDeclToConsumer(D);
6631 }
6632}
6633
6634void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6635 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6636 PassObjCImplDeclToConsumer(ImplD, Consumer);
6637 else
6638 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6639}
6640
6641void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6642 this->Consumer = Consumer;
6643
6644 if (!Consumer)
6645 return;
6646
Ben Langmuir332aafe2014-01-31 01:06:56 +00006647 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006648 // Force deserialization of this decl, which will cause it to be queued for
6649 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006650 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006651 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006652 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006653
6654 PassInterestingDeclsToConsumer();
6655}
6656
6657void ASTReader::PrintStats() {
6658 std::fprintf(stderr, "*** AST File Statistics:\n");
6659
6660 unsigned NumTypesLoaded
6661 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6662 QualType());
6663 unsigned NumDeclsLoaded
6664 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006665 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006666 unsigned NumIdentifiersLoaded
6667 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6668 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006669 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006670 unsigned NumMacrosLoaded
6671 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6672 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006673 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006674 unsigned NumSelectorsLoaded
6675 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6676 SelectorsLoaded.end(),
6677 Selector());
6678
6679 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6680 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6681 NumSLocEntriesRead, TotalNumSLocEntries,
6682 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6683 if (!TypesLoaded.empty())
6684 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6685 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6686 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6687 if (!DeclsLoaded.empty())
6688 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6689 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6690 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6691 if (!IdentifiersLoaded.empty())
6692 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6693 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6694 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6695 if (!MacrosLoaded.empty())
6696 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6697 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6698 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6699 if (!SelectorsLoaded.empty())
6700 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6701 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6702 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6703 if (TotalNumStatements)
6704 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6705 NumStatementsRead, TotalNumStatements,
6706 ((float)NumStatementsRead/TotalNumStatements * 100));
6707 if (TotalNumMacros)
6708 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6709 NumMacrosRead, TotalNumMacros,
6710 ((float)NumMacrosRead/TotalNumMacros * 100));
6711 if (TotalLexicalDeclContexts)
6712 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6713 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6714 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6715 * 100));
6716 if (TotalVisibleDeclContexts)
6717 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6718 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6719 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6720 * 100));
6721 if (TotalNumMethodPoolEntries) {
6722 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6723 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6724 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6725 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006726 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006727 if (NumMethodPoolLookups) {
6728 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6729 NumMethodPoolHits, NumMethodPoolLookups,
6730 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6731 }
6732 if (NumMethodPoolTableLookups) {
6733 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6734 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6735 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6736 * 100.0));
6737 }
6738
Douglas Gregor00a50f72013-01-25 00:38:33 +00006739 if (NumIdentifierLookupHits) {
6740 std::fprintf(stderr,
6741 " %u / %u identifier table lookups succeeded (%f%%)\n",
6742 NumIdentifierLookupHits, NumIdentifierLookups,
6743 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6744 }
6745
Douglas Gregore060e572013-01-25 01:03:03 +00006746 if (GlobalIndex) {
6747 std::fprintf(stderr, "\n");
6748 GlobalIndex->printStats();
6749 }
6750
Guy Benyei11169dd2012-12-18 14:30:41 +00006751 std::fprintf(stderr, "\n");
6752 dump();
6753 std::fprintf(stderr, "\n");
6754}
6755
6756template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6757static void
6758dumpModuleIDMap(StringRef Name,
6759 const ContinuousRangeMap<Key, ModuleFile *,
6760 InitialCapacity> &Map) {
6761 if (Map.begin() == Map.end())
6762 return;
6763
6764 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6765 llvm::errs() << Name << ":\n";
6766 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6767 I != IEnd; ++I) {
6768 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6769 << "\n";
6770 }
6771}
6772
6773void ASTReader::dump() {
6774 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6775 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6776 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6777 dumpModuleIDMap("Global type map", GlobalTypeMap);
6778 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6779 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6780 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6781 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6782 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6783 dumpModuleIDMap("Global preprocessed entity map",
6784 GlobalPreprocessedEntityMap);
6785
6786 llvm::errs() << "\n*** PCH/Modules Loaded:";
6787 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6788 MEnd = ModuleMgr.end();
6789 M != MEnd; ++M)
6790 (*M)->dump();
6791}
6792
6793/// Return the amount of memory used by memory buffers, breaking down
6794/// by heap-backed versus mmap'ed memory.
6795void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6796 for (ModuleConstIterator I = ModuleMgr.begin(),
6797 E = ModuleMgr.end(); I != E; ++I) {
6798 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6799 size_t bytes = buf->getBufferSize();
6800 switch (buf->getBufferKind()) {
6801 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6802 sizes.malloc_bytes += bytes;
6803 break;
6804 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6805 sizes.mmap_bytes += bytes;
6806 break;
6807 }
6808 }
6809 }
6810}
6811
6812void ASTReader::InitializeSema(Sema &S) {
6813 SemaObj = &S;
6814 S.addExternalSource(this);
6815
6816 // Makes sure any declarations that were deserialized "too early"
6817 // still get added to the identifier's declaration chains.
6818 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006819 pushExternalDeclIntoScope(PreloadedDecls[I],
6820 PreloadedDecls[I]->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006821 }
6822 PreloadedDecls.clear();
6823
Richard Smith3d8e97e2013-10-18 06:54:39 +00006824 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006825 if (!FPPragmaOptions.empty()) {
6826 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6827 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6828 }
6829
Richard Smith3d8e97e2013-10-18 06:54:39 +00006830 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006831 if (!OpenCLExtensions.empty()) {
6832 unsigned I = 0;
6833#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6834#include "clang/Basic/OpenCLExtensions.def"
6835
6836 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6837 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006838
6839 UpdateSema();
6840}
6841
6842void ASTReader::UpdateSema() {
6843 assert(SemaObj && "no Sema to update");
6844
6845 // Load the offsets of the declarations that Sema references.
6846 // They will be lazily deserialized when needed.
6847 if (!SemaDeclRefs.empty()) {
6848 assert(SemaDeclRefs.size() % 2 == 0);
6849 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6850 if (!SemaObj->StdNamespace)
6851 SemaObj->StdNamespace = SemaDeclRefs[I];
6852 if (!SemaObj->StdBadAlloc)
6853 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6854 }
6855 SemaDeclRefs.clear();
6856 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006857
6858 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6859 // encountered the pragma in the source.
6860 if(OptimizeOffPragmaLocation.isValid())
6861 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006862}
6863
6864IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6865 // Note that we are loading an identifier.
6866 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006867 StringRef Name(NameStart, NameEnd - NameStart);
6868
6869 // If there is a global index, look there first to determine which modules
6870 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006871 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00006872 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00006873 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006874 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6875 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006876 }
6877 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006878 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006879 NumIdentifierLookups,
6880 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006881 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006882 IdentifierInfo *II = Visitor.getIdentifierInfo();
6883 markIdentifierUpToDate(II);
6884 return II;
6885}
6886
6887namespace clang {
6888 /// \brief An identifier-lookup iterator that enumerates all of the
6889 /// identifiers stored within a set of AST files.
6890 class ASTIdentifierIterator : public IdentifierIterator {
6891 /// \brief The AST reader whose identifiers are being enumerated.
6892 const ASTReader &Reader;
6893
6894 /// \brief The current index into the chain of AST files stored in
6895 /// the AST reader.
6896 unsigned Index;
6897
6898 /// \brief The current position within the identifier lookup table
6899 /// of the current AST file.
6900 ASTIdentifierLookupTable::key_iterator Current;
6901
6902 /// \brief The end position within the identifier lookup table of
6903 /// the current AST file.
6904 ASTIdentifierLookupTable::key_iterator End;
6905
6906 public:
6907 explicit ASTIdentifierIterator(const ASTReader &Reader);
6908
Craig Topper3e89dfe2014-03-13 02:13:41 +00006909 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006910 };
6911}
6912
6913ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6914 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6915 ASTIdentifierLookupTable *IdTable
6916 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6917 Current = IdTable->key_begin();
6918 End = IdTable->key_end();
6919}
6920
6921StringRef ASTIdentifierIterator::Next() {
6922 while (Current == End) {
6923 // If we have exhausted all of our AST files, we're done.
6924 if (Index == 0)
6925 return StringRef();
6926
6927 --Index;
6928 ASTIdentifierLookupTable *IdTable
6929 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6930 IdentifierLookupTable;
6931 Current = IdTable->key_begin();
6932 End = IdTable->key_end();
6933 }
6934
6935 // We have any identifiers remaining in the current AST file; return
6936 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006937 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006938 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006939 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006940}
6941
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006942IdentifierIterator *ASTReader::getIdentifiers() {
6943 if (!loadGlobalIndex())
6944 return GlobalIndex->createIdentifierIterator();
6945
Guy Benyei11169dd2012-12-18 14:30:41 +00006946 return new ASTIdentifierIterator(*this);
6947}
6948
6949namespace clang { namespace serialization {
6950 class ReadMethodPoolVisitor {
6951 ASTReader &Reader;
6952 Selector Sel;
6953 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006954 unsigned InstanceBits;
6955 unsigned FactoryBits;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006956 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6957 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006958
6959 public:
6960 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6961 unsigned PriorGeneration)
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006962 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6963 InstanceBits(0), FactoryBits(0) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006964
6965 static bool visit(ModuleFile &M, void *UserData) {
6966 ReadMethodPoolVisitor *This
6967 = static_cast<ReadMethodPoolVisitor *>(UserData);
6968
6969 if (!M.SelectorLookupTable)
6970 return false;
6971
6972 // If we've already searched this module file, skip it now.
6973 if (M.Generation <= This->PriorGeneration)
6974 return true;
6975
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006976 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006977 ASTSelectorLookupTable *PoolTable
6978 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6979 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6980 if (Pos == PoolTable->end())
6981 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006982
6983 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006984 ++This->Reader.NumSelectorsRead;
6985 // FIXME: Not quite happy with the statistics here. We probably should
6986 // disable this tracking when called via LoadSelector.
6987 // Also, should entries without methods count as misses?
6988 ++This->Reader.NumMethodPoolEntriesRead;
6989 ASTSelectorLookupTrait::data_type Data = *Pos;
6990 if (This->Reader.DeserializationListener)
6991 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6992 This->Sel);
6993
6994 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6995 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006996 This->InstanceBits = Data.InstanceBits;
6997 This->FactoryBits = Data.FactoryBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006998 return true;
6999 }
7000
7001 /// \brief Retrieve the instance methods found by this visitor.
7002 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7003 return InstanceMethods;
7004 }
7005
7006 /// \brief Retrieve the instance methods found by this visitor.
7007 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7008 return FactoryMethods;
7009 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007010
7011 unsigned getInstanceBits() const { return InstanceBits; }
7012 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007013 };
7014} } // end namespace clang::serialization
7015
7016/// \brief Add the given set of methods to the method list.
7017static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7018 ObjCMethodList &List) {
7019 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7020 S.addMethodToGlobalList(&List, Methods[I]);
7021 }
7022}
7023
7024void ASTReader::ReadMethodPool(Selector Sel) {
7025 // Get the selector generation and update it to the current generation.
7026 unsigned &Generation = SelectorGeneration[Sel];
7027 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007028 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007029
7030 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007031 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007032 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7033 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
7034
7035 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007036 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007037 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007038
7039 ++NumMethodPoolHits;
7040
Guy Benyei11169dd2012-12-18 14:30:41 +00007041 if (!getSema())
7042 return;
7043
7044 Sema &S = *getSema();
7045 Sema::GlobalMethodPool::iterator Pos
7046 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
7047
7048 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7049 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007050 Pos->second.first.setBits(Visitor.getInstanceBits());
7051 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei11169dd2012-12-18 14:30:41 +00007052}
7053
7054void ASTReader::ReadKnownNamespaces(
7055 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7056 Namespaces.clear();
7057
7058 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7059 if (NamespaceDecl *Namespace
7060 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7061 Namespaces.push_back(Namespace);
7062 }
7063}
7064
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007065void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007066 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007067 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7068 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007069 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007070 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007071 Undefined.insert(std::make_pair(D, Loc));
7072 }
7073}
Nick Lewycky8334af82013-01-26 00:35:08 +00007074
Guy Benyei11169dd2012-12-18 14:30:41 +00007075void ASTReader::ReadTentativeDefinitions(
7076 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7077 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7078 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7079 if (Var)
7080 TentativeDefs.push_back(Var);
7081 }
7082 TentativeDefinitions.clear();
7083}
7084
7085void ASTReader::ReadUnusedFileScopedDecls(
7086 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7087 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7088 DeclaratorDecl *D
7089 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7090 if (D)
7091 Decls.push_back(D);
7092 }
7093 UnusedFileScopedDecls.clear();
7094}
7095
7096void ASTReader::ReadDelegatingConstructors(
7097 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7098 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7099 CXXConstructorDecl *D
7100 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7101 if (D)
7102 Decls.push_back(D);
7103 }
7104 DelegatingCtorDecls.clear();
7105}
7106
7107void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7108 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7109 TypedefNameDecl *D
7110 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7111 if (D)
7112 Decls.push_back(D);
7113 }
7114 ExtVectorDecls.clear();
7115}
7116
7117void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
7118 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
7119 CXXRecordDecl *D
7120 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
7121 if (D)
7122 Decls.push_back(D);
7123 }
7124 DynamicClasses.clear();
7125}
7126
7127void
Richard Smith78165b52013-01-10 23:43:47 +00007128ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
7129 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
7130 NamedDecl *D
7131 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007132 if (D)
7133 Decls.push_back(D);
7134 }
Richard Smith78165b52013-01-10 23:43:47 +00007135 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007136}
7137
7138void ASTReader::ReadReferencedSelectors(
7139 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7140 if (ReferencedSelectorsData.empty())
7141 return;
7142
7143 // If there are @selector references added them to its pool. This is for
7144 // implementation of -Wselector.
7145 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7146 unsigned I = 0;
7147 while (I < DataSize) {
7148 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7149 SourceLocation SelLoc
7150 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7151 Sels.push_back(std::make_pair(Sel, SelLoc));
7152 }
7153 ReferencedSelectorsData.clear();
7154}
7155
7156void ASTReader::ReadWeakUndeclaredIdentifiers(
7157 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7158 if (WeakUndeclaredIdentifiers.empty())
7159 return;
7160
7161 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7162 IdentifierInfo *WeakId
7163 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7164 IdentifierInfo *AliasId
7165 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7166 SourceLocation Loc
7167 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7168 bool Used = WeakUndeclaredIdentifiers[I++];
7169 WeakInfo WI(AliasId, Loc);
7170 WI.setUsed(Used);
7171 WeakIDs.push_back(std::make_pair(WeakId, WI));
7172 }
7173 WeakUndeclaredIdentifiers.clear();
7174}
7175
7176void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7177 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7178 ExternalVTableUse VT;
7179 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7180 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7181 VT.DefinitionRequired = VTableUses[Idx++];
7182 VTables.push_back(VT);
7183 }
7184
7185 VTableUses.clear();
7186}
7187
7188void ASTReader::ReadPendingInstantiations(
7189 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7190 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7191 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7192 SourceLocation Loc
7193 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7194
7195 Pending.push_back(std::make_pair(D, Loc));
7196 }
7197 PendingInstantiations.clear();
7198}
7199
Richard Smithe40f2ba2013-08-07 21:41:30 +00007200void ASTReader::ReadLateParsedTemplates(
7201 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7202 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7203 /* In loop */) {
7204 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7205
7206 LateParsedTemplate *LT = new LateParsedTemplate;
7207 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7208
7209 ModuleFile *F = getOwningModuleFile(LT->D);
7210 assert(F && "No module");
7211
7212 unsigned TokN = LateParsedTemplates[Idx++];
7213 LT->Toks.reserve(TokN);
7214 for (unsigned T = 0; T < TokN; ++T)
7215 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7216
7217 LPTMap[FD] = LT;
7218 }
7219
7220 LateParsedTemplates.clear();
7221}
7222
Guy Benyei11169dd2012-12-18 14:30:41 +00007223void ASTReader::LoadSelector(Selector Sel) {
7224 // It would be complicated to avoid reading the methods anyway. So don't.
7225 ReadMethodPool(Sel);
7226}
7227
7228void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7229 assert(ID && "Non-zero identifier ID required");
7230 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7231 IdentifiersLoaded[ID - 1] = II;
7232 if (DeserializationListener)
7233 DeserializationListener->IdentifierRead(ID, II);
7234}
7235
7236/// \brief Set the globally-visible declarations associated with the given
7237/// identifier.
7238///
7239/// If the AST reader is currently in a state where the given declaration IDs
7240/// cannot safely be resolved, they are queued until it is safe to resolve
7241/// them.
7242///
7243/// \param II an IdentifierInfo that refers to one or more globally-visible
7244/// declarations.
7245///
7246/// \param DeclIDs the set of declaration IDs with the name @p II that are
7247/// visible at global scope.
7248///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007249/// \param Decls if non-null, this vector will be populated with the set of
7250/// deserialized declarations. These declarations will not be pushed into
7251/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007252void
7253ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7254 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007255 SmallVectorImpl<Decl *> *Decls) {
7256 if (NumCurrentElementsDeserializing && !Decls) {
7257 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007258 return;
7259 }
7260
7261 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
7262 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7263 if (SemaObj) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007264 // If we're simply supposed to record the declarations, do so now.
7265 if (Decls) {
7266 Decls->push_back(D);
7267 continue;
7268 }
7269
Guy Benyei11169dd2012-12-18 14:30:41 +00007270 // Introduce this declaration into the translation-unit scope
7271 // and add it to the declaration chain for this identifier, so
7272 // that (unqualified) name lookup will find it.
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007273 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007274 } else {
7275 // Queue this declaration so that it will be added to the
7276 // translation unit scope and identifier's declaration chain
7277 // once a Sema object is known.
7278 PreloadedDecls.push_back(D);
7279 }
7280 }
7281}
7282
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007283IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007284 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007285 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007286
7287 if (IdentifiersLoaded.empty()) {
7288 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007289 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007290 }
7291
7292 ID -= 1;
7293 if (!IdentifiersLoaded[ID]) {
7294 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7295 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7296 ModuleFile *M = I->second;
7297 unsigned Index = ID - M->BaseIdentifierID;
7298 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7299
7300 // All of the strings in the AST file are preceded by a 16-bit length.
7301 // Extract that 16-bit length to avoid having to execute strlen().
7302 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7303 // unsigned integers. This is important to avoid integer overflow when
7304 // we cast them to 'unsigned'.
7305 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7306 unsigned StrLen = (((unsigned) StrLenPtr[0])
7307 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007308 IdentifiersLoaded[ID]
7309 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007310 if (DeserializationListener)
7311 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7312 }
7313
7314 return IdentifiersLoaded[ID];
7315}
7316
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007317IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7318 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007319}
7320
7321IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7322 if (LocalID < NUM_PREDEF_IDENT_IDS)
7323 return LocalID;
7324
7325 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7326 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7327 assert(I != M.IdentifierRemap.end()
7328 && "Invalid index into identifier index remap");
7329
7330 return LocalID + I->second;
7331}
7332
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007333MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007334 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007335 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007336
7337 if (MacrosLoaded.empty()) {
7338 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007339 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007340 }
7341
7342 ID -= NUM_PREDEF_MACRO_IDS;
7343 if (!MacrosLoaded[ID]) {
7344 GlobalMacroMapType::iterator I
7345 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7346 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7347 ModuleFile *M = I->second;
7348 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007349 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7350
7351 if (DeserializationListener)
7352 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7353 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007354 }
7355
7356 return MacrosLoaded[ID];
7357}
7358
7359MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7360 if (LocalID < NUM_PREDEF_MACRO_IDS)
7361 return LocalID;
7362
7363 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7364 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7365 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7366
7367 return LocalID + I->second;
7368}
7369
7370serialization::SubmoduleID
7371ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7372 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7373 return LocalID;
7374
7375 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7376 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7377 assert(I != M.SubmoduleRemap.end()
7378 && "Invalid index into submodule index remap");
7379
7380 return LocalID + I->second;
7381}
7382
7383Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7384 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7385 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007386 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007387 }
7388
7389 if (GlobalID > SubmodulesLoaded.size()) {
7390 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007391 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007392 }
7393
7394 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7395}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007396
7397Module *ASTReader::getModule(unsigned ID) {
7398 return getSubmodule(ID);
7399}
7400
Guy Benyei11169dd2012-12-18 14:30:41 +00007401Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7402 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7403}
7404
7405Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7406 if (ID == 0)
7407 return Selector();
7408
7409 if (ID > SelectorsLoaded.size()) {
7410 Error("selector ID out of range in AST file");
7411 return Selector();
7412 }
7413
Craig Toppera13603a2014-05-22 05:54:18 +00007414 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007415 // Load this selector from the selector table.
7416 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7417 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7418 ModuleFile &M = *I->second;
7419 ASTSelectorLookupTrait Trait(*this, M);
7420 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7421 SelectorsLoaded[ID - 1] =
7422 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7423 if (DeserializationListener)
7424 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7425 }
7426
7427 return SelectorsLoaded[ID - 1];
7428}
7429
7430Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7431 return DecodeSelector(ID);
7432}
7433
7434uint32_t ASTReader::GetNumExternalSelectors() {
7435 // ID 0 (the null selector) is considered an external selector.
7436 return getTotalNumSelectors() + 1;
7437}
7438
7439serialization::SelectorID
7440ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7441 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7442 return LocalID;
7443
7444 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7445 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7446 assert(I != M.SelectorRemap.end()
7447 && "Invalid index into selector index remap");
7448
7449 return LocalID + I->second;
7450}
7451
7452DeclarationName
7453ASTReader::ReadDeclarationName(ModuleFile &F,
7454 const RecordData &Record, unsigned &Idx) {
7455 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7456 switch (Kind) {
7457 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007458 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007459
7460 case DeclarationName::ObjCZeroArgSelector:
7461 case DeclarationName::ObjCOneArgSelector:
7462 case DeclarationName::ObjCMultiArgSelector:
7463 return DeclarationName(ReadSelector(F, Record, Idx));
7464
7465 case DeclarationName::CXXConstructorName:
7466 return Context.DeclarationNames.getCXXConstructorName(
7467 Context.getCanonicalType(readType(F, Record, Idx)));
7468
7469 case DeclarationName::CXXDestructorName:
7470 return Context.DeclarationNames.getCXXDestructorName(
7471 Context.getCanonicalType(readType(F, Record, Idx)));
7472
7473 case DeclarationName::CXXConversionFunctionName:
7474 return Context.DeclarationNames.getCXXConversionFunctionName(
7475 Context.getCanonicalType(readType(F, Record, Idx)));
7476
7477 case DeclarationName::CXXOperatorName:
7478 return Context.DeclarationNames.getCXXOperatorName(
7479 (OverloadedOperatorKind)Record[Idx++]);
7480
7481 case DeclarationName::CXXLiteralOperatorName:
7482 return Context.DeclarationNames.getCXXLiteralOperatorName(
7483 GetIdentifierInfo(F, Record, Idx));
7484
7485 case DeclarationName::CXXUsingDirective:
7486 return DeclarationName::getUsingDirectiveName();
7487 }
7488
7489 llvm_unreachable("Invalid NameKind!");
7490}
7491
7492void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7493 DeclarationNameLoc &DNLoc,
7494 DeclarationName Name,
7495 const RecordData &Record, unsigned &Idx) {
7496 switch (Name.getNameKind()) {
7497 case DeclarationName::CXXConstructorName:
7498 case DeclarationName::CXXDestructorName:
7499 case DeclarationName::CXXConversionFunctionName:
7500 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7501 break;
7502
7503 case DeclarationName::CXXOperatorName:
7504 DNLoc.CXXOperatorName.BeginOpNameLoc
7505 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7506 DNLoc.CXXOperatorName.EndOpNameLoc
7507 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7508 break;
7509
7510 case DeclarationName::CXXLiteralOperatorName:
7511 DNLoc.CXXLiteralOperatorName.OpNameLoc
7512 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7513 break;
7514
7515 case DeclarationName::Identifier:
7516 case DeclarationName::ObjCZeroArgSelector:
7517 case DeclarationName::ObjCOneArgSelector:
7518 case DeclarationName::ObjCMultiArgSelector:
7519 case DeclarationName::CXXUsingDirective:
7520 break;
7521 }
7522}
7523
7524void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7525 DeclarationNameInfo &NameInfo,
7526 const RecordData &Record, unsigned &Idx) {
7527 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7528 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7529 DeclarationNameLoc DNLoc;
7530 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7531 NameInfo.setInfo(DNLoc);
7532}
7533
7534void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7535 const RecordData &Record, unsigned &Idx) {
7536 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7537 unsigned NumTPLists = Record[Idx++];
7538 Info.NumTemplParamLists = NumTPLists;
7539 if (NumTPLists) {
7540 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7541 for (unsigned i=0; i != NumTPLists; ++i)
7542 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7543 }
7544}
7545
7546TemplateName
7547ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7548 unsigned &Idx) {
7549 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7550 switch (Kind) {
7551 case TemplateName::Template:
7552 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7553
7554 case TemplateName::OverloadedTemplate: {
7555 unsigned size = Record[Idx++];
7556 UnresolvedSet<8> Decls;
7557 while (size--)
7558 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7559
7560 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7561 }
7562
7563 case TemplateName::QualifiedTemplate: {
7564 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7565 bool hasTemplKeyword = Record[Idx++];
7566 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7567 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7568 }
7569
7570 case TemplateName::DependentTemplate: {
7571 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7572 if (Record[Idx++]) // isIdentifier
7573 return Context.getDependentTemplateName(NNS,
7574 GetIdentifierInfo(F, Record,
7575 Idx));
7576 return Context.getDependentTemplateName(NNS,
7577 (OverloadedOperatorKind)Record[Idx++]);
7578 }
7579
7580 case TemplateName::SubstTemplateTemplateParm: {
7581 TemplateTemplateParmDecl *param
7582 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7583 if (!param) return TemplateName();
7584 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7585 return Context.getSubstTemplateTemplateParm(param, replacement);
7586 }
7587
7588 case TemplateName::SubstTemplateTemplateParmPack: {
7589 TemplateTemplateParmDecl *Param
7590 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7591 if (!Param)
7592 return TemplateName();
7593
7594 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7595 if (ArgPack.getKind() != TemplateArgument::Pack)
7596 return TemplateName();
7597
7598 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7599 }
7600 }
7601
7602 llvm_unreachable("Unhandled template name kind!");
7603}
7604
7605TemplateArgument
7606ASTReader::ReadTemplateArgument(ModuleFile &F,
7607 const RecordData &Record, unsigned &Idx) {
7608 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7609 switch (Kind) {
7610 case TemplateArgument::Null:
7611 return TemplateArgument();
7612 case TemplateArgument::Type:
7613 return TemplateArgument(readType(F, Record, Idx));
7614 case TemplateArgument::Declaration: {
7615 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7616 bool ForReferenceParam = Record[Idx++];
7617 return TemplateArgument(D, ForReferenceParam);
7618 }
7619 case TemplateArgument::NullPtr:
7620 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7621 case TemplateArgument::Integral: {
7622 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7623 QualType T = readType(F, Record, Idx);
7624 return TemplateArgument(Context, Value, T);
7625 }
7626 case TemplateArgument::Template:
7627 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7628 case TemplateArgument::TemplateExpansion: {
7629 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007630 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007631 if (unsigned NumExpansions = Record[Idx++])
7632 NumTemplateExpansions = NumExpansions - 1;
7633 return TemplateArgument(Name, NumTemplateExpansions);
7634 }
7635 case TemplateArgument::Expression:
7636 return TemplateArgument(ReadExpr(F));
7637 case TemplateArgument::Pack: {
7638 unsigned NumArgs = Record[Idx++];
7639 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7640 for (unsigned I = 0; I != NumArgs; ++I)
7641 Args[I] = ReadTemplateArgument(F, Record, Idx);
7642 return TemplateArgument(Args, NumArgs);
7643 }
7644 }
7645
7646 llvm_unreachable("Unhandled template argument kind!");
7647}
7648
7649TemplateParameterList *
7650ASTReader::ReadTemplateParameterList(ModuleFile &F,
7651 const RecordData &Record, unsigned &Idx) {
7652 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7653 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7654 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7655
7656 unsigned NumParams = Record[Idx++];
7657 SmallVector<NamedDecl *, 16> Params;
7658 Params.reserve(NumParams);
7659 while (NumParams--)
7660 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7661
7662 TemplateParameterList* TemplateParams =
7663 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7664 Params.data(), Params.size(), RAngleLoc);
7665 return TemplateParams;
7666}
7667
7668void
7669ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007670ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007671 ModuleFile &F, const RecordData &Record,
7672 unsigned &Idx) {
7673 unsigned NumTemplateArgs = Record[Idx++];
7674 TemplArgs.reserve(NumTemplateArgs);
7675 while (NumTemplateArgs--)
7676 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7677}
7678
7679/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007680void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007681 const RecordData &Record, unsigned &Idx) {
7682 unsigned NumDecls = Record[Idx++];
7683 Set.reserve(Context, NumDecls);
7684 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007685 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007686 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007687 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007688 }
7689}
7690
7691CXXBaseSpecifier
7692ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7693 const RecordData &Record, unsigned &Idx) {
7694 bool isVirtual = static_cast<bool>(Record[Idx++]);
7695 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7696 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7697 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7698 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7699 SourceRange Range = ReadSourceRange(F, Record, Idx);
7700 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7701 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7702 EllipsisLoc);
7703 Result.setInheritConstructors(inheritConstructors);
7704 return Result;
7705}
7706
7707std::pair<CXXCtorInitializer **, unsigned>
7708ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7709 unsigned &Idx) {
Craig Toppera13603a2014-05-22 05:54:18 +00007710 CXXCtorInitializer **CtorInitializers = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007711 unsigned NumInitializers = Record[Idx++];
7712 if (NumInitializers) {
7713 CtorInitializers
7714 = new (Context) CXXCtorInitializer*[NumInitializers];
7715 for (unsigned i=0; i != NumInitializers; ++i) {
Craig Toppera13603a2014-05-22 05:54:18 +00007716 TypeSourceInfo *TInfo = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007717 bool IsBaseVirtual = false;
Craig Toppera13603a2014-05-22 05:54:18 +00007718 FieldDecl *Member = nullptr;
7719 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007720
7721 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7722 switch (Type) {
7723 case CTOR_INITIALIZER_BASE:
7724 TInfo = GetTypeSourceInfo(F, Record, Idx);
7725 IsBaseVirtual = Record[Idx++];
7726 break;
7727
7728 case CTOR_INITIALIZER_DELEGATING:
7729 TInfo = GetTypeSourceInfo(F, Record, Idx);
7730 break;
7731
7732 case CTOR_INITIALIZER_MEMBER:
7733 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7734 break;
7735
7736 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7737 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7738 break;
7739 }
7740
7741 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7742 Expr *Init = ReadExpr(F);
7743 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7744 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7745 bool IsWritten = Record[Idx++];
7746 unsigned SourceOrderOrNumArrayIndices;
7747 SmallVector<VarDecl *, 8> Indices;
7748 if (IsWritten) {
7749 SourceOrderOrNumArrayIndices = Record[Idx++];
7750 } else {
7751 SourceOrderOrNumArrayIndices = Record[Idx++];
7752 Indices.reserve(SourceOrderOrNumArrayIndices);
7753 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7754 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7755 }
7756
7757 CXXCtorInitializer *BOMInit;
7758 if (Type == CTOR_INITIALIZER_BASE) {
7759 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7760 LParenLoc, Init, RParenLoc,
7761 MemberOrEllipsisLoc);
7762 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7763 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7764 Init, RParenLoc);
7765 } else if (IsWritten) {
7766 if (Member)
7767 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7768 LParenLoc, Init, RParenLoc);
7769 else
7770 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7771 MemberOrEllipsisLoc, LParenLoc,
7772 Init, RParenLoc);
7773 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007774 if (IndirectMember) {
7775 assert(Indices.empty() && "Indirect field improperly initialized");
7776 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7777 MemberOrEllipsisLoc, LParenLoc,
7778 Init, RParenLoc);
7779 } else {
7780 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7781 LParenLoc, Init, RParenLoc,
7782 Indices.data(), Indices.size());
7783 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007784 }
7785
7786 if (IsWritten)
7787 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7788 CtorInitializers[i] = BOMInit;
7789 }
7790 }
7791
7792 return std::make_pair(CtorInitializers, NumInitializers);
7793}
7794
7795NestedNameSpecifier *
7796ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7797 const RecordData &Record, unsigned &Idx) {
7798 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007799 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007800 for (unsigned I = 0; I != N; ++I) {
7801 NestedNameSpecifier::SpecifierKind Kind
7802 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7803 switch (Kind) {
7804 case NestedNameSpecifier::Identifier: {
7805 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7806 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7807 break;
7808 }
7809
7810 case NestedNameSpecifier::Namespace: {
7811 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7812 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7813 break;
7814 }
7815
7816 case NestedNameSpecifier::NamespaceAlias: {
7817 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7818 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7819 break;
7820 }
7821
7822 case NestedNameSpecifier::TypeSpec:
7823 case NestedNameSpecifier::TypeSpecWithTemplate: {
7824 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7825 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007826 return nullptr;
7827
Guy Benyei11169dd2012-12-18 14:30:41 +00007828 bool Template = Record[Idx++];
7829 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7830 break;
7831 }
7832
7833 case NestedNameSpecifier::Global: {
7834 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7835 // No associated value, and there can't be a prefix.
7836 break;
7837 }
7838 }
7839 Prev = NNS;
7840 }
7841 return NNS;
7842}
7843
7844NestedNameSpecifierLoc
7845ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7846 unsigned &Idx) {
7847 unsigned N = Record[Idx++];
7848 NestedNameSpecifierLocBuilder Builder;
7849 for (unsigned I = 0; I != N; ++I) {
7850 NestedNameSpecifier::SpecifierKind Kind
7851 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7852 switch (Kind) {
7853 case NestedNameSpecifier::Identifier: {
7854 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7855 SourceRange Range = ReadSourceRange(F, Record, Idx);
7856 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7857 break;
7858 }
7859
7860 case NestedNameSpecifier::Namespace: {
7861 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7862 SourceRange Range = ReadSourceRange(F, Record, Idx);
7863 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7864 break;
7865 }
7866
7867 case NestedNameSpecifier::NamespaceAlias: {
7868 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7869 SourceRange Range = ReadSourceRange(F, Record, Idx);
7870 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7871 break;
7872 }
7873
7874 case NestedNameSpecifier::TypeSpec:
7875 case NestedNameSpecifier::TypeSpecWithTemplate: {
7876 bool Template = Record[Idx++];
7877 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7878 if (!T)
7879 return NestedNameSpecifierLoc();
7880 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7881
7882 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7883 Builder.Extend(Context,
7884 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7885 T->getTypeLoc(), ColonColonLoc);
7886 break;
7887 }
7888
7889 case NestedNameSpecifier::Global: {
7890 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7891 Builder.MakeGlobal(Context, ColonColonLoc);
7892 break;
7893 }
7894 }
7895 }
7896
7897 return Builder.getWithLocInContext(Context);
7898}
7899
7900SourceRange
7901ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7902 unsigned &Idx) {
7903 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7904 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7905 return SourceRange(beg, end);
7906}
7907
7908/// \brief Read an integral value
7909llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7910 unsigned BitWidth = Record[Idx++];
7911 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7912 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7913 Idx += NumWords;
7914 return Result;
7915}
7916
7917/// \brief Read a signed integral value
7918llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7919 bool isUnsigned = Record[Idx++];
7920 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7921}
7922
7923/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007924llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7925 const llvm::fltSemantics &Sem,
7926 unsigned &Idx) {
7927 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007928}
7929
7930// \brief Read a string
7931std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7932 unsigned Len = Record[Idx++];
7933 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7934 Idx += Len;
7935 return Result;
7936}
7937
7938VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7939 unsigned &Idx) {
7940 unsigned Major = Record[Idx++];
7941 unsigned Minor = Record[Idx++];
7942 unsigned Subminor = Record[Idx++];
7943 if (Minor == 0)
7944 return VersionTuple(Major);
7945 if (Subminor == 0)
7946 return VersionTuple(Major, Minor - 1);
7947 return VersionTuple(Major, Minor - 1, Subminor - 1);
7948}
7949
7950CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7951 const RecordData &Record,
7952 unsigned &Idx) {
7953 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7954 return CXXTemporary::Create(Context, Decl);
7955}
7956
7957DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007958 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007959}
7960
7961DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7962 return Diags.Report(Loc, DiagID);
7963}
7964
7965/// \brief Retrieve the identifier table associated with the
7966/// preprocessor.
7967IdentifierTable &ASTReader::getIdentifierTable() {
7968 return PP.getIdentifierTable();
7969}
7970
7971/// \brief Record that the given ID maps to the given switch-case
7972/// statement.
7973void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007974 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007975 "Already have a SwitchCase with this ID");
7976 (*CurrSwitchCaseStmts)[ID] = SC;
7977}
7978
7979/// \brief Retrieve the switch-case statement with the given ID.
7980SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007981 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00007982 return (*CurrSwitchCaseStmts)[ID];
7983}
7984
7985void ASTReader::ClearSwitchCaseIDs() {
7986 CurrSwitchCaseStmts->clear();
7987}
7988
7989void ASTReader::ReadComments() {
7990 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007991 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007992 serialization::ModuleFile *> >::iterator
7993 I = CommentsCursors.begin(),
7994 E = CommentsCursors.end();
7995 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007996 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007997 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007998 serialization::ModuleFile &F = *I->second;
7999 SavedStreamPosition SavedPosition(Cursor);
8000
8001 RecordData Record;
8002 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008003 llvm::BitstreamEntry Entry =
8004 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008005
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008006 switch (Entry.Kind) {
8007 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8008 case llvm::BitstreamEntry::Error:
8009 Error("malformed block record in AST file");
8010 return;
8011 case llvm::BitstreamEntry::EndBlock:
8012 goto NextCursor;
8013 case llvm::BitstreamEntry::Record:
8014 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008015 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008016 }
8017
8018 // Read a record.
8019 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008020 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008021 case COMMENTS_RAW_COMMENT: {
8022 unsigned Idx = 0;
8023 SourceRange SR = ReadSourceRange(F, Record, Idx);
8024 RawComment::CommentKind Kind =
8025 (RawComment::CommentKind) Record[Idx++];
8026 bool IsTrailingComment = Record[Idx++];
8027 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008028 Comments.push_back(new (Context) RawComment(
8029 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8030 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008031 break;
8032 }
8033 }
8034 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008035 NextCursor:
8036 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008037 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008038}
8039
Richard Smithcd45dbc2014-04-19 03:48:30 +00008040std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8041 // If we know the owning module, use it.
8042 if (Module *M = D->getOwningModule())
8043 return M->getFullModuleName();
8044
8045 // Otherwise, use the name of the top-level module the decl is within.
8046 if (ModuleFile *M = getOwningModuleFile(D))
8047 return M->ModuleName;
8048
8049 // Not from a module.
8050 return "";
8051}
8052
Guy Benyei11169dd2012-12-18 14:30:41 +00008053void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008054 while (!PendingIdentifierInfos.empty() ||
8055 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008056 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smith93914a92014-05-08 00:25:01 +00008057 !PendingUpdateRecords.empty() || !PendingOdrMergeChecks.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008058 // If any identifiers with corresponding top-level declarations have
8059 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008060 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8061 TopLevelDeclsMap;
8062 TopLevelDeclsMap TopLevelDecls;
8063
Guy Benyei11169dd2012-12-18 14:30:41 +00008064 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008065 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008066 SmallVector<uint32_t, 4> DeclIDs =
8067 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008068 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008069
8070 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008071 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008072
Richard Smith851072e2014-05-19 20:59:20 +00008073 // For each decl chain that we wanted to complete while deserializing, mark
8074 // it as "still needs to be completed".
8075 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8076 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8077 }
8078 PendingIncompleteDeclChains.clear();
8079
Guy Benyei11169dd2012-12-18 14:30:41 +00008080 // Load pending declaration chains.
8081 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
8082 loadPendingDeclChain(PendingDeclChains[I]);
8083 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
8084 }
8085 PendingDeclChains.clear();
8086
Douglas Gregor6168bd22013-02-18 15:53:43 +00008087 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008088 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8089 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008090 IdentifierInfo *II = TLD->first;
8091 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008092 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008093 }
8094 }
8095
Guy Benyei11169dd2012-12-18 14:30:41 +00008096 // Load any pending macro definitions.
8097 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008098 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8099 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8100 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8101 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008102 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008103 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008104 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8105 if (Info.M->Kind != MK_Module)
8106 resolvePendingMacro(II, Info);
8107 }
8108 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008109 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008110 ++IDIdx) {
8111 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8112 if (Info.M->Kind == MK_Module)
8113 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008114 }
8115 }
8116 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008117
8118 // Wire up the DeclContexts for Decls that we delayed setting until
8119 // recursive loading is completed.
8120 while (!PendingDeclContextInfos.empty()) {
8121 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8122 PendingDeclContextInfos.pop_front();
8123 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8124 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8125 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8126 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008127
Richard Smithd1c46742014-04-30 02:24:17 +00008128 // Perform any pending declaration updates.
Richard Smith675d2792014-06-16 20:26:19 +00008129 //
8130 // Don't do this if we have known-incomplete redecl chains: it relies on
8131 // being able to walk redeclaration chains.
8132 while (PendingDeclChains.empty() && !PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008133 auto Update = PendingUpdateRecords.pop_back_val();
8134 ReadingKindTracker ReadingKind(Read_Decl, *this);
8135 loadDeclUpdateRecords(Update.first, Update.second);
8136 }
8137
Richard Smithcd45dbc2014-04-19 03:48:30 +00008138 // Trigger the import of the full definition of each class that had any
8139 // odr-merging problems, so we can produce better diagnostics for them.
8140 for (auto &Merge : PendingOdrMergeFailures) {
8141 Merge.first->buildLookup();
8142 Merge.first->decls_begin();
8143 Merge.first->bases_begin();
8144 Merge.first->vbases_begin();
8145 for (auto *RD : Merge.second) {
8146 RD->decls_begin();
8147 RD->bases_begin();
8148 RD->vbases_begin();
8149 }
8150 }
8151
Richard Smith2b9e3e32013-10-18 06:05:18 +00008152 // For each declaration from a merged context, check that the canonical
8153 // definition of that context also contains a declaration of the same
8154 // entity.
8155 while (!PendingOdrMergeChecks.empty()) {
8156 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8157
8158 // FIXME: Skip over implicit declarations for now. This matters for things
8159 // like implicitly-declared special member functions. This isn't entirely
8160 // correct; we can end up with multiple unmerged declarations of the same
8161 // implicit entity.
8162 if (D->isImplicit())
8163 continue;
8164
8165 DeclContext *CanonDef = D->getDeclContext();
8166 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
8167
8168 bool Found = false;
8169 const Decl *DCanon = D->getCanonicalDecl();
8170
8171 llvm::SmallVector<const NamedDecl*, 4> Candidates;
8172 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8173 !Found && I != E; ++I) {
Aaron Ballman86c93902014-03-06 23:45:36 +00008174 for (auto RI : (*I)->redecls()) {
8175 if (RI->getLexicalDeclContext() == CanonDef) {
Richard Smith2b9e3e32013-10-18 06:05:18 +00008176 // This declaration is present in the canonical definition. If it's
8177 // in the same redecl chain, it's the one we're looking for.
Aaron Ballman86c93902014-03-06 23:45:36 +00008178 if (RI->getCanonicalDecl() == DCanon)
Richard Smith2b9e3e32013-10-18 06:05:18 +00008179 Found = true;
8180 else
Aaron Ballman86c93902014-03-06 23:45:36 +00008181 Candidates.push_back(cast<NamedDecl>(RI));
Richard Smith2b9e3e32013-10-18 06:05:18 +00008182 break;
8183 }
8184 }
8185 }
8186
8187 if (!Found) {
8188 D->setInvalidDecl();
8189
Richard Smithcd45dbc2014-04-19 03:48:30 +00008190 std::string CanonDefModule =
8191 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
Richard Smith2b9e3e32013-10-18 06:05:18 +00008192 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008193 << D << getOwningModuleNameForDiagnostic(D)
8194 << CanonDef << CanonDefModule.empty() << CanonDefModule;
Richard Smith2b9e3e32013-10-18 06:05:18 +00008195
8196 if (Candidates.empty())
8197 Diag(cast<Decl>(CanonDef)->getLocation(),
8198 diag::note_module_odr_violation_no_possible_decls) << D;
8199 else {
8200 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8201 Diag(Candidates[I]->getLocation(),
8202 diag::note_module_odr_violation_possible_decl)
8203 << Candidates[I];
8204 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008205
8206 DiagnosedOdrMergeFailures.insert(CanonDef);
Richard Smith2b9e3e32013-10-18 06:05:18 +00008207 }
8208 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008209 }
8210
8211 // If we deserialized any C++ or Objective-C class definitions, any
8212 // Objective-C protocol definitions, or any redeclarable templates, make sure
8213 // that all redeclarations point to the definitions. Note that this can only
8214 // happen now, after the redeclaration chains have been fully wired.
8215 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
8216 DEnd = PendingDefinitions.end();
8217 D != DEnd; ++D) {
8218 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008219 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008220 // Make sure that the TagType points at the definition.
8221 const_cast<TagType*>(TagT)->decl = TD;
8222 }
8223
Aaron Ballman86c93902014-03-06 23:45:36 +00008224 if (auto RD = dyn_cast<CXXRecordDecl>(*D)) {
8225 for (auto R : RD->redecls())
8226 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Guy Benyei11169dd2012-12-18 14:30:41 +00008227 }
8228
8229 continue;
8230 }
8231
Aaron Ballman86c93902014-03-06 23:45:36 +00008232 if (auto ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008233 // Make sure that the ObjCInterfaceType points at the definition.
8234 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8235 ->Decl = ID;
8236
Aaron Ballman86c93902014-03-06 23:45:36 +00008237 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008238 R->Data = ID->Data;
8239
8240 continue;
8241 }
8242
Aaron Ballman86c93902014-03-06 23:45:36 +00008243 if (auto PD = dyn_cast<ObjCProtocolDecl>(*D)) {
8244 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008245 R->Data = PD->Data;
8246
8247 continue;
8248 }
8249
Aaron Ballman86c93902014-03-06 23:45:36 +00008250 auto RTD = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
8251 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008252 R->Common = RTD->Common;
8253 }
8254 PendingDefinitions.clear();
8255
8256 // Load the bodies of any functions or methods we've encountered. We do
8257 // this now (delayed) so that we can be sure that the declaration chains
8258 // have been fully wired up.
8259 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8260 PBEnd = PendingBodies.end();
8261 PB != PBEnd; ++PB) {
8262 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8263 // FIXME: Check for =delete/=default?
8264 // FIXME: Complain about ODR violations here?
8265 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8266 FD->setLazyBody(PB->second);
8267 continue;
8268 }
8269
8270 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8271 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8272 MD->setLazyBody(PB->second);
8273 }
8274 PendingBodies.clear();
Richard Smithcd45dbc2014-04-19 03:48:30 +00008275
8276 // Issue any pending ODR-failure diagnostics.
8277 for (auto &Merge : PendingOdrMergeFailures) {
8278 if (!DiagnosedOdrMergeFailures.insert(Merge.first))
8279 continue;
8280
8281 bool Diagnosed = false;
8282 for (auto *RD : Merge.second) {
8283 // Multiple different declarations got merged together; tell the user
8284 // where they came from.
8285 if (Merge.first != RD) {
8286 // FIXME: Walk the definition, figure out what's different,
8287 // and diagnose that.
8288 if (!Diagnosed) {
8289 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8290 Diag(Merge.first->getLocation(),
8291 diag::err_module_odr_violation_different_definitions)
8292 << Merge.first << Module.empty() << Module;
8293 Diagnosed = true;
8294 }
8295
8296 Diag(RD->getLocation(),
8297 diag::note_module_odr_violation_different_definitions)
8298 << getOwningModuleNameForDiagnostic(RD);
8299 }
8300 }
8301
8302 if (!Diagnosed) {
8303 // All definitions are updates to the same declaration. This happens if a
8304 // module instantiates the declaration of a class template specialization
8305 // and two or more other modules instantiate its definition.
8306 //
8307 // FIXME: Indicate which modules had instantiations of this definition.
8308 // FIXME: How can this even happen?
8309 Diag(Merge.first->getLocation(),
8310 diag::err_module_odr_violation_different_instantiations)
8311 << Merge.first;
8312 }
8313 }
8314 PendingOdrMergeFailures.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00008315}
8316
8317void ASTReader::FinishedDeserializing() {
8318 assert(NumCurrentElementsDeserializing &&
8319 "FinishedDeserializing not paired with StartedDeserializing");
8320 if (NumCurrentElementsDeserializing == 1) {
8321 // We decrease NumCurrentElementsDeserializing only after pending actions
8322 // are finished, to avoid recursively re-calling finishPendingActions().
8323 finishPendingActions();
8324 }
8325 --NumCurrentElementsDeserializing;
8326
Richard Smith04d05b52014-03-23 00:27:18 +00008327 if (NumCurrentElementsDeserializing == 0 && Consumer) {
8328 // We are not in recursive loading, so it's safe to pass the "interesting"
8329 // decls to the consumer.
8330 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008331 }
8332}
8333
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008334void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00008335 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008336
8337 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8338 SemaObj->TUScope->AddDecl(D);
8339 } else if (SemaObj->TUScope) {
8340 // Adding the decl to IdResolver may have failed because it was already in
8341 // (even though it was not added in scope). If it is already in, make sure
8342 // it gets in the scope as well.
8343 if (std::find(SemaObj->IdResolver.begin(Name),
8344 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8345 SemaObj->TUScope->AddDecl(D);
8346 }
8347}
8348
Nico Weber824285e2014-05-08 04:26:47 +00008349ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8350 bool DisableValidation, bool AllowASTWithCompilerErrors,
8351 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008352 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008353 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008354 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Craig Toppera13603a2014-05-22 05:54:18 +00008355 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
8356 SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
8357 ModuleMgr(PP.getFileManager()), isysroot(isysroot),
8358 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008359 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8360 AllowConfigurationMismatch(AllowConfigurationMismatch),
8361 ValidateSystemInputs(ValidateSystemInputs),
8362 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Richard Smith053f6c62014-05-16 23:01:30 +00008363 CurrSwitchCaseStmts(&SwitchCaseStmts),
Nico Weber824285e2014-05-08 04:26:47 +00008364 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8365 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8366 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8367 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8368 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8369 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8370 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8371 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8372 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8373 PassingDeclsToConsumer(false), NumCXXBaseSpecifiersLoaded(0),
8374 ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008375 SourceMgr.setExternalSLocEntrySource(this);
8376}
8377
8378ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008379 if (OwnsDeserializationListener)
8380 delete DeserializationListener;
8381
Guy Benyei11169dd2012-12-18 14:30:41 +00008382 for (DeclContextVisibleUpdatesPending::iterator
8383 I = PendingVisibleUpdates.begin(),
8384 E = PendingVisibleUpdates.end();
8385 I != E; ++I) {
8386 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8387 F = I->second.end();
8388 J != F; ++J)
8389 delete J->first;
8390 }
8391}