blob: 6ed41c39702e487b96cb8e6022be888b478028e1 [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;
5265 unsigned NumParams = Record[Idx++];
5266 SmallVector<QualType, 16> ParamTypes;
5267 for (unsigned I = 0; I != NumParams; ++I)
5268 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5269
5270 EPI.Variadic = Record[Idx++];
5271 EPI.HasTrailingReturn = Record[Idx++];
5272 EPI.TypeQuals = Record[Idx++];
5273 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005274 SmallVector<QualType, 8> ExceptionStorage;
5275 readExceptionSpec(*Loc.F, ExceptionStorage, EPI, Record, Idx);
Jordan Rose5c382722013-03-08 21:51:21 +00005276 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005277 }
5278
5279 case TYPE_UNRESOLVED_USING: {
5280 unsigned Idx = 0;
5281 return Context.getTypeDeclType(
5282 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5283 }
5284
5285 case TYPE_TYPEDEF: {
5286 if (Record.size() != 2) {
5287 Error("incorrect encoding of typedef type");
5288 return QualType();
5289 }
5290 unsigned Idx = 0;
5291 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5292 QualType Canonical = readType(*Loc.F, Record, Idx);
5293 if (!Canonical.isNull())
5294 Canonical = Context.getCanonicalType(Canonical);
5295 return Context.getTypedefType(Decl, Canonical);
5296 }
5297
5298 case TYPE_TYPEOF_EXPR:
5299 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5300
5301 case TYPE_TYPEOF: {
5302 if (Record.size() != 1) {
5303 Error("incorrect encoding of typeof(type) in AST file");
5304 return QualType();
5305 }
5306 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5307 return Context.getTypeOfType(UnderlyingType);
5308 }
5309
5310 case TYPE_DECLTYPE: {
5311 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5312 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5313 }
5314
5315 case TYPE_UNARY_TRANSFORM: {
5316 QualType BaseType = readType(*Loc.F, Record, Idx);
5317 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5318 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5319 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5320 }
5321
Richard Smith74aeef52013-04-26 16:15:35 +00005322 case TYPE_AUTO: {
5323 QualType Deduced = readType(*Loc.F, Record, Idx);
5324 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005325 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005326 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005327 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005328
5329 case TYPE_RECORD: {
5330 if (Record.size() != 2) {
5331 Error("incorrect encoding of record type");
5332 return QualType();
5333 }
5334 unsigned Idx = 0;
5335 bool IsDependent = Record[Idx++];
5336 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5337 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5338 QualType T = Context.getRecordType(RD);
5339 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5340 return T;
5341 }
5342
5343 case TYPE_ENUM: {
5344 if (Record.size() != 2) {
5345 Error("incorrect encoding of enum type");
5346 return QualType();
5347 }
5348 unsigned Idx = 0;
5349 bool IsDependent = Record[Idx++];
5350 QualType T
5351 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5352 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5353 return T;
5354 }
5355
5356 case TYPE_ATTRIBUTED: {
5357 if (Record.size() != 3) {
5358 Error("incorrect encoding of attributed type");
5359 return QualType();
5360 }
5361 QualType modifiedType = readType(*Loc.F, Record, Idx);
5362 QualType equivalentType = readType(*Loc.F, Record, Idx);
5363 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5364 return Context.getAttributedType(kind, modifiedType, equivalentType);
5365 }
5366
5367 case TYPE_PAREN: {
5368 if (Record.size() != 1) {
5369 Error("incorrect encoding of paren type");
5370 return QualType();
5371 }
5372 QualType InnerType = readType(*Loc.F, Record, Idx);
5373 return Context.getParenType(InnerType);
5374 }
5375
5376 case TYPE_PACK_EXPANSION: {
5377 if (Record.size() != 2) {
5378 Error("incorrect encoding of pack expansion type");
5379 return QualType();
5380 }
5381 QualType Pattern = readType(*Loc.F, Record, Idx);
5382 if (Pattern.isNull())
5383 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005384 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005385 if (Record[1])
5386 NumExpansions = Record[1] - 1;
5387 return Context.getPackExpansionType(Pattern, NumExpansions);
5388 }
5389
5390 case TYPE_ELABORATED: {
5391 unsigned Idx = 0;
5392 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5393 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5394 QualType NamedType = readType(*Loc.F, Record, Idx);
5395 return Context.getElaboratedType(Keyword, NNS, NamedType);
5396 }
5397
5398 case TYPE_OBJC_INTERFACE: {
5399 unsigned Idx = 0;
5400 ObjCInterfaceDecl *ItfD
5401 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5402 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5403 }
5404
5405 case TYPE_OBJC_OBJECT: {
5406 unsigned Idx = 0;
5407 QualType Base = readType(*Loc.F, Record, Idx);
5408 unsigned NumProtos = Record[Idx++];
5409 SmallVector<ObjCProtocolDecl*, 4> Protos;
5410 for (unsigned I = 0; I != NumProtos; ++I)
5411 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5412 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5413 }
5414
5415 case TYPE_OBJC_OBJECT_POINTER: {
5416 unsigned Idx = 0;
5417 QualType Pointee = readType(*Loc.F, Record, Idx);
5418 return Context.getObjCObjectPointerType(Pointee);
5419 }
5420
5421 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5422 unsigned Idx = 0;
5423 QualType Parm = readType(*Loc.F, Record, Idx);
5424 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005425 return Context.getSubstTemplateTypeParmType(
5426 cast<TemplateTypeParmType>(Parm),
5427 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005428 }
5429
5430 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5431 unsigned Idx = 0;
5432 QualType Parm = readType(*Loc.F, Record, Idx);
5433 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5434 return Context.getSubstTemplateTypeParmPackType(
5435 cast<TemplateTypeParmType>(Parm),
5436 ArgPack);
5437 }
5438
5439 case TYPE_INJECTED_CLASS_NAME: {
5440 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5441 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5442 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5443 // for AST reading, too much interdependencies.
Richard Smithf17fdbd2014-04-24 02:25:27 +00005444 const Type *T;
5445 if (const Type *Existing = D->getTypeForDecl())
5446 T = Existing;
5447 else if (auto *Prev = D->getPreviousDecl())
5448 T = Prev->getTypeForDecl();
5449 else
5450 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
5451 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005452 }
5453
5454 case TYPE_TEMPLATE_TYPE_PARM: {
5455 unsigned Idx = 0;
5456 unsigned Depth = Record[Idx++];
5457 unsigned Index = Record[Idx++];
5458 bool Pack = Record[Idx++];
5459 TemplateTypeParmDecl *D
5460 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5461 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5462 }
5463
5464 case TYPE_DEPENDENT_NAME: {
5465 unsigned Idx = 0;
5466 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5467 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5468 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5469 QualType Canon = readType(*Loc.F, Record, Idx);
5470 if (!Canon.isNull())
5471 Canon = Context.getCanonicalType(Canon);
5472 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5473 }
5474
5475 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5476 unsigned Idx = 0;
5477 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5478 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5479 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5480 unsigned NumArgs = Record[Idx++];
5481 SmallVector<TemplateArgument, 8> Args;
5482 Args.reserve(NumArgs);
5483 while (NumArgs--)
5484 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5485 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5486 Args.size(), Args.data());
5487 }
5488
5489 case TYPE_DEPENDENT_SIZED_ARRAY: {
5490 unsigned Idx = 0;
5491
5492 // ArrayType
5493 QualType ElementType = readType(*Loc.F, Record, Idx);
5494 ArrayType::ArraySizeModifier ASM
5495 = (ArrayType::ArraySizeModifier)Record[Idx++];
5496 unsigned IndexTypeQuals = Record[Idx++];
5497
5498 // DependentSizedArrayType
5499 Expr *NumElts = ReadExpr(*Loc.F);
5500 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5501
5502 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5503 IndexTypeQuals, Brackets);
5504 }
5505
5506 case TYPE_TEMPLATE_SPECIALIZATION: {
5507 unsigned Idx = 0;
5508 bool IsDependent = Record[Idx++];
5509 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5510 SmallVector<TemplateArgument, 8> Args;
5511 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5512 QualType Underlying = readType(*Loc.F, Record, Idx);
5513 QualType T;
5514 if (Underlying.isNull())
5515 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5516 Args.size());
5517 else
5518 T = Context.getTemplateSpecializationType(Name, Args.data(),
5519 Args.size(), Underlying);
5520 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5521 return T;
5522 }
5523
5524 case TYPE_ATOMIC: {
5525 if (Record.size() != 1) {
5526 Error("Incorrect encoding of atomic type");
5527 return QualType();
5528 }
5529 QualType ValueType = readType(*Loc.F, Record, Idx);
5530 return Context.getAtomicType(ValueType);
5531 }
5532 }
5533 llvm_unreachable("Invalid TypeCode!");
5534}
5535
Richard Smith564417a2014-03-20 21:47:22 +00005536void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5537 SmallVectorImpl<QualType> &Exceptions,
5538 FunctionProtoType::ExtProtoInfo &EPI,
5539 const RecordData &Record, unsigned &Idx) {
5540 ExceptionSpecificationType EST =
5541 static_cast<ExceptionSpecificationType>(Record[Idx++]);
5542 EPI.ExceptionSpecType = EST;
5543 if (EST == EST_Dynamic) {
5544 EPI.NumExceptions = Record[Idx++];
5545 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
5546 Exceptions.push_back(readType(ModuleFile, Record, Idx));
5547 EPI.Exceptions = Exceptions.data();
5548 } else if (EST == EST_ComputedNoexcept) {
5549 EPI.NoexceptExpr = ReadExpr(ModuleFile);
5550 } else if (EST == EST_Uninstantiated) {
5551 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5552 EPI.ExceptionSpecTemplate =
5553 ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5554 } else if (EST == EST_Unevaluated) {
5555 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5556 }
5557}
5558
Guy Benyei11169dd2012-12-18 14:30:41 +00005559class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5560 ASTReader &Reader;
5561 ModuleFile &F;
5562 const ASTReader::RecordData &Record;
5563 unsigned &Idx;
5564
5565 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5566 unsigned &I) {
5567 return Reader.ReadSourceLocation(F, R, I);
5568 }
5569
5570 template<typename T>
5571 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5572 return Reader.ReadDeclAs<T>(F, Record, Idx);
5573 }
5574
5575public:
5576 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5577 const ASTReader::RecordData &Record, unsigned &Idx)
5578 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5579 { }
5580
5581 // We want compile-time assurance that we've enumerated all of
5582 // these, so unfortunately we have to declare them first, then
5583 // define them out-of-line.
5584#define ABSTRACT_TYPELOC(CLASS, PARENT)
5585#define TYPELOC(CLASS, PARENT) \
5586 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5587#include "clang/AST/TypeLocNodes.def"
5588
5589 void VisitFunctionTypeLoc(FunctionTypeLoc);
5590 void VisitArrayTypeLoc(ArrayTypeLoc);
5591};
5592
5593void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5594 // nothing to do
5595}
5596void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5597 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5598 if (TL.needsExtraLocalData()) {
5599 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5600 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5601 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5602 TL.setModeAttr(Record[Idx++]);
5603 }
5604}
5605void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5606 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5607}
5608void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5609 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5610}
Reid Kleckner8a365022013-06-24 17:51:48 +00005611void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5612 // nothing to do
5613}
Reid Kleckner0503a872013-12-05 01:23:43 +00005614void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5615 // nothing to do
5616}
Guy Benyei11169dd2012-12-18 14:30:41 +00005617void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5618 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5619}
5620void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5621 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5622}
5623void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5624 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5625}
5626void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5627 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5628 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5629}
5630void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5631 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5632 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5633 if (Record[Idx++])
5634 TL.setSizeExpr(Reader.ReadExpr(F));
5635 else
Craig Toppera13603a2014-05-22 05:54:18 +00005636 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005637}
5638void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5639 VisitArrayTypeLoc(TL);
5640}
5641void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5642 VisitArrayTypeLoc(TL);
5643}
5644void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5645 VisitArrayTypeLoc(TL);
5646}
5647void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5648 DependentSizedArrayTypeLoc TL) {
5649 VisitArrayTypeLoc(TL);
5650}
5651void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5652 DependentSizedExtVectorTypeLoc TL) {
5653 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5654}
5655void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5656 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5657}
5658void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5659 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5660}
5661void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5662 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5663 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5664 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5665 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005666 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5667 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005668 }
5669}
5670void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5671 VisitFunctionTypeLoc(TL);
5672}
5673void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5674 VisitFunctionTypeLoc(TL);
5675}
5676void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5677 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5678}
5679void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5680 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5681}
5682void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5683 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5684 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5685 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5686}
5687void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5688 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5689 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5690 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5691 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5692}
5693void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5694 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5695}
5696void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5697 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5698 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5699 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5700 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5701}
5702void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5703 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5704}
5705void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5706 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5707}
5708void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5709 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5710}
5711void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5712 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5713 if (TL.hasAttrOperand()) {
5714 SourceRange range;
5715 range.setBegin(ReadSourceLocation(Record, Idx));
5716 range.setEnd(ReadSourceLocation(Record, Idx));
5717 TL.setAttrOperandParensRange(range);
5718 }
5719 if (TL.hasAttrExprOperand()) {
5720 if (Record[Idx++])
5721 TL.setAttrExprOperand(Reader.ReadExpr(F));
5722 else
Craig Toppera13603a2014-05-22 05:54:18 +00005723 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005724 } else if (TL.hasAttrEnumOperand())
5725 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5726}
5727void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5728 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5729}
5730void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5731 SubstTemplateTypeParmTypeLoc TL) {
5732 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5733}
5734void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5735 SubstTemplateTypeParmPackTypeLoc TL) {
5736 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5737}
5738void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5739 TemplateSpecializationTypeLoc TL) {
5740 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5741 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5742 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5743 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5744 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5745 TL.setArgLocInfo(i,
5746 Reader.GetTemplateArgumentLocInfo(F,
5747 TL.getTypePtr()->getArg(i).getKind(),
5748 Record, Idx));
5749}
5750void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5751 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5752 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5753}
5754void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5755 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5756 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5757}
5758void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5759 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5760}
5761void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5762 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5763 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5764 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5765}
5766void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5767 DependentTemplateSpecializationTypeLoc TL) {
5768 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5769 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5770 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5771 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5772 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5773 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5774 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5775 TL.setArgLocInfo(I,
5776 Reader.GetTemplateArgumentLocInfo(F,
5777 TL.getTypePtr()->getArg(I).getKind(),
5778 Record, Idx));
5779}
5780void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5781 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5782}
5783void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5784 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5785}
5786void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5787 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5788 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5789 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5790 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5791 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5792}
5793void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5794 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5795}
5796void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5797 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5798 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5799 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5800}
5801
5802TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5803 const RecordData &Record,
5804 unsigned &Idx) {
5805 QualType InfoTy = readType(F, Record, Idx);
5806 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005807 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005808
5809 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5810 TypeLocReader TLR(*this, F, Record, Idx);
5811 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5812 TLR.Visit(TL);
5813 return TInfo;
5814}
5815
5816QualType ASTReader::GetType(TypeID ID) {
5817 unsigned FastQuals = ID & Qualifiers::FastMask;
5818 unsigned Index = ID >> Qualifiers::FastWidth;
5819
5820 if (Index < NUM_PREDEF_TYPE_IDS) {
5821 QualType T;
5822 switch ((PredefinedTypeIDs)Index) {
5823 case PREDEF_TYPE_NULL_ID: return QualType();
5824 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5825 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5826
5827 case PREDEF_TYPE_CHAR_U_ID:
5828 case PREDEF_TYPE_CHAR_S_ID:
5829 // FIXME: Check that the signedness of CharTy is correct!
5830 T = Context.CharTy;
5831 break;
5832
5833 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5834 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5835 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5836 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5837 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5838 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5839 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5840 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5841 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5842 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5843 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5844 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5845 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5846 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5847 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5848 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5849 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5850 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5851 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5852 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5853 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5854 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5855 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5856 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5857 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5858 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5859 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5860 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005861 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5862 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5863 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5864 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5865 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5866 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005867 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005868 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005869 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5870
5871 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5872 T = Context.getAutoRRefDeductType();
5873 break;
5874
5875 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5876 T = Context.ARCUnbridgedCastTy;
5877 break;
5878
5879 case PREDEF_TYPE_VA_LIST_TAG:
5880 T = Context.getVaListTagType();
5881 break;
5882
5883 case PREDEF_TYPE_BUILTIN_FN:
5884 T = Context.BuiltinFnTy;
5885 break;
5886 }
5887
5888 assert(!T.isNull() && "Unknown predefined type");
5889 return T.withFastQualifiers(FastQuals);
5890 }
5891
5892 Index -= NUM_PREDEF_TYPE_IDS;
5893 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5894 if (TypesLoaded[Index].isNull()) {
5895 TypesLoaded[Index] = readTypeRecord(Index);
5896 if (TypesLoaded[Index].isNull())
5897 return QualType();
5898
5899 TypesLoaded[Index]->setFromAST();
5900 if (DeserializationListener)
5901 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5902 TypesLoaded[Index]);
5903 }
5904
5905 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5906}
5907
5908QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5909 return GetType(getGlobalTypeID(F, LocalID));
5910}
5911
5912serialization::TypeID
5913ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5914 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5915 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5916
5917 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5918 return LocalID;
5919
5920 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5921 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5922 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5923
5924 unsigned GlobalIndex = LocalIndex + I->second;
5925 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5926}
5927
5928TemplateArgumentLocInfo
5929ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5930 TemplateArgument::ArgKind Kind,
5931 const RecordData &Record,
5932 unsigned &Index) {
5933 switch (Kind) {
5934 case TemplateArgument::Expression:
5935 return ReadExpr(F);
5936 case TemplateArgument::Type:
5937 return GetTypeSourceInfo(F, Record, Index);
5938 case TemplateArgument::Template: {
5939 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5940 Index);
5941 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5942 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5943 SourceLocation());
5944 }
5945 case TemplateArgument::TemplateExpansion: {
5946 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5947 Index);
5948 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5949 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5950 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5951 EllipsisLoc);
5952 }
5953 case TemplateArgument::Null:
5954 case TemplateArgument::Integral:
5955 case TemplateArgument::Declaration:
5956 case TemplateArgument::NullPtr:
5957 case TemplateArgument::Pack:
5958 // FIXME: Is this right?
5959 return TemplateArgumentLocInfo();
5960 }
5961 llvm_unreachable("unexpected template argument loc");
5962}
5963
5964TemplateArgumentLoc
5965ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5966 const RecordData &Record, unsigned &Index) {
5967 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5968
5969 if (Arg.getKind() == TemplateArgument::Expression) {
5970 if (Record[Index++]) // bool InfoHasSameExpr.
5971 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5972 }
5973 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5974 Record, Index));
5975}
5976
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005977const ASTTemplateArgumentListInfo*
5978ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5979 const RecordData &Record,
5980 unsigned &Index) {
5981 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5982 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5983 unsigned NumArgsAsWritten = Record[Index++];
5984 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5985 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5986 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5987 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5988}
5989
Guy Benyei11169dd2012-12-18 14:30:41 +00005990Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5991 return GetDecl(ID);
5992}
5993
Richard Smith053f6c62014-05-16 23:01:30 +00005994void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005995 if (NumCurrentElementsDeserializing) {
5996 // We arrange to not care about the complete redeclaration chain while we're
5997 // deserializing. Just remember that the AST has marked this one as complete
5998 // but that it's not actually complete yet, so we know we still need to
5999 // complete it later.
6000 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6001 return;
6002 }
6003
Richard Smith053f6c62014-05-16 23:01:30 +00006004 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6005
6006 // Recursively ensure that the decl context itself is complete
6007 // (in particular, this matters if the decl context is a namespace).
6008 //
6009 // FIXME: This should be performed by lookup instead of here.
6010 cast<Decl>(DC)->getMostRecentDecl();
6011
6012 // If this is a named declaration, complete it by looking it up
6013 // within its context.
6014 //
6015 // FIXME: We don't currently handle the cases where we can't do this;
6016 // merging a class definition that contains unnamed entities should merge
6017 // those entities. Likewise, merging a function definition should merge
6018 // all mergeable entities within it.
6019 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6020 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6021 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
6022 auto *II = Name.getAsIdentifierInfo();
6023 if (isa<TranslationUnitDecl>(DC) && II) {
6024 // Outside of C++, we don't have a lookup table for the TU, so update
6025 // the identifier instead. In C++, either way should work fine.
6026 if (II->isOutOfDate())
6027 updateOutOfDateIdentifier(*II);
6028 } else
6029 DC->lookup(Name);
6030 }
6031 }
6032}
6033
Richard Smithcd45dbc2014-04-19 03:48:30 +00006034uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6035 const RecordData &Record,
6036 unsigned &Idx) {
6037 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6038 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006039 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006040 }
6041
Guy Benyei11169dd2012-12-18 14:30:41 +00006042 unsigned LocalID = Record[Idx++];
6043 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6044}
6045
6046CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6047 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006048 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006049 SavedStreamPosition SavedPosition(Cursor);
6050 Cursor.JumpToBit(Loc.Offset);
6051 ReadingKindTracker ReadingKind(Read_Decl, *this);
6052 RecordData Record;
6053 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006054 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006055 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006056 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006057 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006058 }
6059
6060 unsigned Idx = 0;
6061 unsigned NumBases = Record[Idx++];
6062 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6063 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6064 for (unsigned I = 0; I != NumBases; ++I)
6065 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6066 return Bases;
6067}
6068
6069serialization::DeclID
6070ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6071 if (LocalID < NUM_PREDEF_DECL_IDS)
6072 return LocalID;
6073
6074 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6075 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6076 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6077
6078 return LocalID + I->second;
6079}
6080
6081bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6082 ModuleFile &M) const {
6083 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6084 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6085 return &M == I->second;
6086}
6087
Douglas Gregor9f782892013-01-21 15:25:38 +00006088ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006089 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006090 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006091 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6092 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6093 return I->second;
6094}
6095
6096SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6097 if (ID < NUM_PREDEF_DECL_IDS)
6098 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006099
Guy Benyei11169dd2012-12-18 14:30:41 +00006100 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6101
6102 if (Index > DeclsLoaded.size()) {
6103 Error("declaration ID out-of-range for AST file");
6104 return SourceLocation();
6105 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006106
Guy Benyei11169dd2012-12-18 14:30:41 +00006107 if (Decl *D = DeclsLoaded[Index])
6108 return D->getLocation();
6109
6110 unsigned RawLocation = 0;
6111 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6112 return ReadSourceLocation(*Rec.F, RawLocation);
6113}
6114
Richard Smithcd45dbc2014-04-19 03:48:30 +00006115Decl *ASTReader::GetExistingDecl(DeclID ID) {
6116 if (ID < NUM_PREDEF_DECL_IDS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006117 switch ((PredefinedDeclIDs)ID) {
6118 case PREDEF_DECL_NULL_ID:
Craig Toppera13603a2014-05-22 05:54:18 +00006119 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006120
Guy Benyei11169dd2012-12-18 14:30:41 +00006121 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6122 return Context.getTranslationUnitDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006123
Guy Benyei11169dd2012-12-18 14:30:41 +00006124 case PREDEF_DECL_OBJC_ID_ID:
6125 return Context.getObjCIdDecl();
6126
6127 case PREDEF_DECL_OBJC_SEL_ID:
6128 return Context.getObjCSelDecl();
6129
6130 case PREDEF_DECL_OBJC_CLASS_ID:
6131 return Context.getObjCClassDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006132
Guy Benyei11169dd2012-12-18 14:30:41 +00006133 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6134 return Context.getObjCProtocolDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006135
Guy Benyei11169dd2012-12-18 14:30:41 +00006136 case PREDEF_DECL_INT_128_ID:
6137 return Context.getInt128Decl();
6138
6139 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6140 return Context.getUInt128Decl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006141
Guy Benyei11169dd2012-12-18 14:30:41 +00006142 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6143 return Context.getObjCInstanceTypeDecl();
6144
6145 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6146 return Context.getBuiltinVaListDecl();
6147 }
6148 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006149
Guy Benyei11169dd2012-12-18 14:30:41 +00006150 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6151
6152 if (Index >= DeclsLoaded.size()) {
6153 assert(0 && "declaration ID out-of-range for AST file");
6154 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006155 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006156 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006157
6158 return DeclsLoaded[Index];
6159}
6160
6161Decl *ASTReader::GetDecl(DeclID ID) {
6162 if (ID < NUM_PREDEF_DECL_IDS)
6163 return GetExistingDecl(ID);
6164
6165 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6166
6167 if (Index >= DeclsLoaded.size()) {
6168 assert(0 && "declaration ID out-of-range for AST file");
6169 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006170 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006171 }
6172
Guy Benyei11169dd2012-12-18 14:30:41 +00006173 if (!DeclsLoaded[Index]) {
6174 ReadDeclRecord(ID);
6175 if (DeserializationListener)
6176 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6177 }
6178
6179 return DeclsLoaded[Index];
6180}
6181
6182DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6183 DeclID GlobalID) {
6184 if (GlobalID < NUM_PREDEF_DECL_IDS)
6185 return GlobalID;
6186
6187 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6188 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6189 ModuleFile *Owner = I->second;
6190
6191 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6192 = M.GlobalToLocalDeclIDs.find(Owner);
6193 if (Pos == M.GlobalToLocalDeclIDs.end())
6194 return 0;
6195
6196 return GlobalID - Owner->BaseDeclID + Pos->second;
6197}
6198
6199serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6200 const RecordData &Record,
6201 unsigned &Idx) {
6202 if (Idx >= Record.size()) {
6203 Error("Corrupted AST file");
6204 return 0;
6205 }
6206
6207 return getGlobalDeclID(F, Record[Idx++]);
6208}
6209
6210/// \brief Resolve the offset of a statement into a statement.
6211///
6212/// This operation will read a new statement from the external
6213/// source each time it is called, and is meant to be used via a
6214/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6215Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6216 // Switch case IDs are per Decl.
6217 ClearSwitchCaseIDs();
6218
6219 // Offset here is a global offset across the entire chain.
6220 RecordLocation Loc = getLocalBitOffset(Offset);
6221 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6222 return ReadStmtFromStream(*Loc.F);
6223}
6224
6225namespace {
6226 class FindExternalLexicalDeclsVisitor {
6227 ASTReader &Reader;
6228 const DeclContext *DC;
6229 bool (*isKindWeWant)(Decl::Kind);
6230
6231 SmallVectorImpl<Decl*> &Decls;
6232 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6233
6234 public:
6235 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6236 bool (*isKindWeWant)(Decl::Kind),
6237 SmallVectorImpl<Decl*> &Decls)
6238 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6239 {
6240 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6241 PredefsVisited[I] = false;
6242 }
6243
6244 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6245 if (Preorder)
6246 return false;
6247
6248 FindExternalLexicalDeclsVisitor *This
6249 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6250
6251 ModuleFile::DeclContextInfosMap::iterator Info
6252 = M.DeclContextInfos.find(This->DC);
6253 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6254 return false;
6255
6256 // Load all of the declaration IDs
6257 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6258 *IDE = ID + Info->second.NumLexicalDecls;
6259 ID != IDE; ++ID) {
6260 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6261 continue;
6262
6263 // Don't add predefined declarations to the lexical context more
6264 // than once.
6265 if (ID->second < NUM_PREDEF_DECL_IDS) {
6266 if (This->PredefsVisited[ID->second])
6267 continue;
6268
6269 This->PredefsVisited[ID->second] = true;
6270 }
6271
6272 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6273 if (!This->DC->isDeclInLexicalTraversal(D))
6274 This->Decls.push_back(D);
6275 }
6276 }
6277
6278 return false;
6279 }
6280 };
6281}
6282
6283ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6284 bool (*isKindWeWant)(Decl::Kind),
6285 SmallVectorImpl<Decl*> &Decls) {
6286 // There might be lexical decls in multiple modules, for the TU at
6287 // least. Walk all of the modules in the order they were loaded.
6288 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6289 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6290 ++NumLexicalDeclContextsRead;
6291 return ELR_Success;
6292}
6293
6294namespace {
6295
6296class DeclIDComp {
6297 ASTReader &Reader;
6298 ModuleFile &Mod;
6299
6300public:
6301 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6302
6303 bool operator()(LocalDeclID L, LocalDeclID R) const {
6304 SourceLocation LHS = getLocation(L);
6305 SourceLocation RHS = getLocation(R);
6306 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6307 }
6308
6309 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6310 SourceLocation RHS = getLocation(R);
6311 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6312 }
6313
6314 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6315 SourceLocation LHS = getLocation(L);
6316 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6317 }
6318
6319 SourceLocation getLocation(LocalDeclID ID) const {
6320 return Reader.getSourceManager().getFileLoc(
6321 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6322 }
6323};
6324
6325}
6326
6327void ASTReader::FindFileRegionDecls(FileID File,
6328 unsigned Offset, unsigned Length,
6329 SmallVectorImpl<Decl *> &Decls) {
6330 SourceManager &SM = getSourceManager();
6331
6332 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6333 if (I == FileDeclIDs.end())
6334 return;
6335
6336 FileDeclsInfo &DInfo = I->second;
6337 if (DInfo.Decls.empty())
6338 return;
6339
6340 SourceLocation
6341 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6342 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6343
6344 DeclIDComp DIDComp(*this, *DInfo.Mod);
6345 ArrayRef<serialization::LocalDeclID>::iterator
6346 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6347 BeginLoc, DIDComp);
6348 if (BeginIt != DInfo.Decls.begin())
6349 --BeginIt;
6350
6351 // If we are pointing at a top-level decl inside an objc container, we need
6352 // to backtrack until we find it otherwise we will fail to report that the
6353 // region overlaps with an objc container.
6354 while (BeginIt != DInfo.Decls.begin() &&
6355 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6356 ->isTopLevelDeclInObjCContainer())
6357 --BeginIt;
6358
6359 ArrayRef<serialization::LocalDeclID>::iterator
6360 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6361 EndLoc, DIDComp);
6362 if (EndIt != DInfo.Decls.end())
6363 ++EndIt;
6364
6365 for (ArrayRef<serialization::LocalDeclID>::iterator
6366 DIt = BeginIt; DIt != EndIt; ++DIt)
6367 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6368}
6369
6370namespace {
6371 /// \brief ModuleFile visitor used to perform name lookup into a
6372 /// declaration context.
6373 class DeclContextNameLookupVisitor {
6374 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006375 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006376 DeclarationName Name;
6377 SmallVectorImpl<NamedDecl *> &Decls;
6378
6379 public:
6380 DeclContextNameLookupVisitor(ASTReader &Reader,
6381 SmallVectorImpl<const DeclContext *> &Contexts,
6382 DeclarationName Name,
6383 SmallVectorImpl<NamedDecl *> &Decls)
6384 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
6385
6386 static bool visit(ModuleFile &M, void *UserData) {
6387 DeclContextNameLookupVisitor *This
6388 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6389
6390 // Check whether we have any visible declaration information for
6391 // this context in this module.
6392 ModuleFile::DeclContextInfosMap::iterator Info;
6393 bool FoundInfo = false;
6394 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6395 Info = M.DeclContextInfos.find(This->Contexts[I]);
6396 if (Info != M.DeclContextInfos.end() &&
6397 Info->second.NameLookupTableData) {
6398 FoundInfo = true;
6399 break;
6400 }
6401 }
6402
6403 if (!FoundInfo)
6404 return false;
6405
6406 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006407 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006408 Info->second.NameLookupTableData;
6409 ASTDeclContextNameLookupTable::iterator Pos
6410 = LookupTable->find(This->Name);
6411 if (Pos == LookupTable->end())
6412 return false;
6413
6414 bool FoundAnything = false;
6415 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6416 for (; Data.first != Data.second; ++Data.first) {
6417 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6418 if (!ND)
6419 continue;
6420
6421 if (ND->getDeclName() != This->Name) {
6422 // A name might be null because the decl's redeclarable part is
6423 // currently read before reading its name. The lookup is triggered by
6424 // building that decl (likely indirectly), and so it is later in the
6425 // sense of "already existing" and can be ignored here.
6426 continue;
6427 }
6428
6429 // Record this declaration.
6430 FoundAnything = true;
6431 This->Decls.push_back(ND);
6432 }
6433
6434 return FoundAnything;
6435 }
6436 };
6437}
6438
Douglas Gregor9f782892013-01-21 15:25:38 +00006439/// \brief Retrieve the "definitive" module file for the definition of the
6440/// given declaration context, if there is one.
6441///
6442/// The "definitive" module file is the only place where we need to look to
6443/// find information about the declarations within the given declaration
6444/// context. For example, C++ and Objective-C classes, C structs/unions, and
6445/// Objective-C protocols, categories, and extensions are all defined in a
6446/// single place in the source code, so they have definitive module files
6447/// associated with them. C++ namespaces, on the other hand, can have
6448/// definitions in multiple different module files.
6449///
6450/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6451/// NDEBUG checking.
6452static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6453 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006454 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6455 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006456
Craig Toppera13603a2014-05-22 05:54:18 +00006457 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006458}
6459
Richard Smith9ce12e32013-02-07 03:30:24 +00006460bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006461ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6462 DeclarationName Name) {
6463 assert(DC->hasExternalVisibleStorage() &&
6464 "DeclContext has no visible decls in storage");
6465 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006466 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006467
6468 SmallVector<NamedDecl *, 64> Decls;
6469
6470 // Compute the declaration contexts we need to look into. Multiple such
6471 // declaration contexts occur when two declaration contexts from disjoint
6472 // modules get merged, e.g., when two namespaces with the same name are
6473 // independently defined in separate modules.
6474 SmallVector<const DeclContext *, 2> Contexts;
6475 Contexts.push_back(DC);
6476
6477 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006478 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006479 if (Merged != MergedDecls.end()) {
6480 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6481 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6482 }
6483 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006484 if (isa<CXXRecordDecl>(DC)) {
6485 auto Merged = MergedLookups.find(DC);
6486 if (Merged != MergedLookups.end())
6487 Contexts.insert(Contexts.end(), Merged->second.begin(),
6488 Merged->second.end());
6489 }
6490
Guy Benyei11169dd2012-12-18 14:30:41 +00006491 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor9f782892013-01-21 15:25:38 +00006492
6493 // If we can definitively determine which module file to look into,
6494 // only look there. Otherwise, look in all module files.
6495 ModuleFile *Definitive;
6496 if (Contexts.size() == 1 &&
6497 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
6498 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6499 } else {
6500 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6501 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006502 ++NumVisibleDeclContextsRead;
6503 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006504 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006505}
6506
6507namespace {
6508 /// \brief ModuleFile visitor used to retrieve all visible names in a
6509 /// declaration context.
6510 class DeclContextAllNamesVisitor {
6511 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006512 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006513 DeclsMap &Decls;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006514 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006515
6516 public:
6517 DeclContextAllNamesVisitor(ASTReader &Reader,
6518 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006519 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006520 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006521
6522 static bool visit(ModuleFile &M, void *UserData) {
6523 DeclContextAllNamesVisitor *This
6524 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6525
6526 // Check whether we have any visible declaration information for
6527 // this context in this module.
6528 ModuleFile::DeclContextInfosMap::iterator Info;
6529 bool FoundInfo = false;
6530 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6531 Info = M.DeclContextInfos.find(This->Contexts[I]);
6532 if (Info != M.DeclContextInfos.end() &&
6533 Info->second.NameLookupTableData) {
6534 FoundInfo = true;
6535 break;
6536 }
6537 }
6538
6539 if (!FoundInfo)
6540 return false;
6541
Richard Smith52e3fba2014-03-11 07:17:35 +00006542 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006543 Info->second.NameLookupTableData;
6544 bool FoundAnything = false;
6545 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006546 I = LookupTable->data_begin(), E = LookupTable->data_end();
6547 I != E;
6548 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006549 ASTDeclContextNameLookupTrait::data_type Data = *I;
6550 for (; Data.first != Data.second; ++Data.first) {
6551 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6552 *Data.first);
6553 if (!ND)
6554 continue;
6555
6556 // Record this declaration.
6557 FoundAnything = true;
6558 This->Decls[ND->getDeclName()].push_back(ND);
6559 }
6560 }
6561
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006562 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006563 }
6564 };
6565}
6566
6567void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6568 if (!DC->hasExternalVisibleStorage())
6569 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006570 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006571
6572 // Compute the declaration contexts we need to look into. Multiple such
6573 // declaration contexts occur when two declaration contexts from disjoint
6574 // modules get merged, e.g., when two namespaces with the same name are
6575 // independently defined in separate modules.
6576 SmallVector<const DeclContext *, 2> Contexts;
6577 Contexts.push_back(DC);
6578
6579 if (DC->isNamespace()) {
6580 MergedDeclsMap::iterator Merged
6581 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6582 if (Merged != MergedDecls.end()) {
6583 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6584 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6585 }
6586 }
6587
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006588 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6589 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006590 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6591 ++NumVisibleDeclContextsRead;
6592
Craig Topper79be4cd2013-07-05 04:33:53 +00006593 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006594 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6595 }
6596 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6597}
6598
6599/// \brief Under non-PCH compilation the consumer receives the objc methods
6600/// before receiving the implementation, and codegen depends on this.
6601/// We simulate this by deserializing and passing to consumer the methods of the
6602/// implementation before passing the deserialized implementation decl.
6603static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6604 ASTConsumer *Consumer) {
6605 assert(ImplD && Consumer);
6606
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006607 for (auto *I : ImplD->methods())
6608 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006609
6610 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6611}
6612
6613void ASTReader::PassInterestingDeclsToConsumer() {
6614 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006615
6616 if (PassingDeclsToConsumer)
6617 return;
6618
6619 // Guard variable to avoid recursively redoing the process of passing
6620 // decls to consumer.
6621 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6622 true);
6623
Guy Benyei11169dd2012-12-18 14:30:41 +00006624 while (!InterestingDecls.empty()) {
6625 Decl *D = InterestingDecls.front();
6626 InterestingDecls.pop_front();
6627
6628 PassInterestingDeclToConsumer(D);
6629 }
6630}
6631
6632void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6633 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6634 PassObjCImplDeclToConsumer(ImplD, Consumer);
6635 else
6636 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6637}
6638
6639void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6640 this->Consumer = Consumer;
6641
6642 if (!Consumer)
6643 return;
6644
Ben Langmuir332aafe2014-01-31 01:06:56 +00006645 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006646 // Force deserialization of this decl, which will cause it to be queued for
6647 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006648 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006649 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006650 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006651
6652 PassInterestingDeclsToConsumer();
6653}
6654
6655void ASTReader::PrintStats() {
6656 std::fprintf(stderr, "*** AST File Statistics:\n");
6657
6658 unsigned NumTypesLoaded
6659 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6660 QualType());
6661 unsigned NumDeclsLoaded
6662 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006663 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006664 unsigned NumIdentifiersLoaded
6665 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6666 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006667 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006668 unsigned NumMacrosLoaded
6669 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6670 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006671 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006672 unsigned NumSelectorsLoaded
6673 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6674 SelectorsLoaded.end(),
6675 Selector());
6676
6677 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6678 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6679 NumSLocEntriesRead, TotalNumSLocEntries,
6680 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6681 if (!TypesLoaded.empty())
6682 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6683 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6684 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6685 if (!DeclsLoaded.empty())
6686 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6687 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6688 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6689 if (!IdentifiersLoaded.empty())
6690 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6691 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6692 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6693 if (!MacrosLoaded.empty())
6694 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6695 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6696 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6697 if (!SelectorsLoaded.empty())
6698 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6699 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6700 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6701 if (TotalNumStatements)
6702 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6703 NumStatementsRead, TotalNumStatements,
6704 ((float)NumStatementsRead/TotalNumStatements * 100));
6705 if (TotalNumMacros)
6706 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6707 NumMacrosRead, TotalNumMacros,
6708 ((float)NumMacrosRead/TotalNumMacros * 100));
6709 if (TotalLexicalDeclContexts)
6710 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6711 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6712 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6713 * 100));
6714 if (TotalVisibleDeclContexts)
6715 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6716 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6717 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6718 * 100));
6719 if (TotalNumMethodPoolEntries) {
6720 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6721 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6722 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6723 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006724 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006725 if (NumMethodPoolLookups) {
6726 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6727 NumMethodPoolHits, NumMethodPoolLookups,
6728 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6729 }
6730 if (NumMethodPoolTableLookups) {
6731 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6732 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6733 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6734 * 100.0));
6735 }
6736
Douglas Gregor00a50f72013-01-25 00:38:33 +00006737 if (NumIdentifierLookupHits) {
6738 std::fprintf(stderr,
6739 " %u / %u identifier table lookups succeeded (%f%%)\n",
6740 NumIdentifierLookupHits, NumIdentifierLookups,
6741 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6742 }
6743
Douglas Gregore060e572013-01-25 01:03:03 +00006744 if (GlobalIndex) {
6745 std::fprintf(stderr, "\n");
6746 GlobalIndex->printStats();
6747 }
6748
Guy Benyei11169dd2012-12-18 14:30:41 +00006749 std::fprintf(stderr, "\n");
6750 dump();
6751 std::fprintf(stderr, "\n");
6752}
6753
6754template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6755static void
6756dumpModuleIDMap(StringRef Name,
6757 const ContinuousRangeMap<Key, ModuleFile *,
6758 InitialCapacity> &Map) {
6759 if (Map.begin() == Map.end())
6760 return;
6761
6762 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6763 llvm::errs() << Name << ":\n";
6764 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6765 I != IEnd; ++I) {
6766 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6767 << "\n";
6768 }
6769}
6770
6771void ASTReader::dump() {
6772 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6773 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6774 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6775 dumpModuleIDMap("Global type map", GlobalTypeMap);
6776 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6777 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6778 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6779 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6780 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6781 dumpModuleIDMap("Global preprocessed entity map",
6782 GlobalPreprocessedEntityMap);
6783
6784 llvm::errs() << "\n*** PCH/Modules Loaded:";
6785 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6786 MEnd = ModuleMgr.end();
6787 M != MEnd; ++M)
6788 (*M)->dump();
6789}
6790
6791/// Return the amount of memory used by memory buffers, breaking down
6792/// by heap-backed versus mmap'ed memory.
6793void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6794 for (ModuleConstIterator I = ModuleMgr.begin(),
6795 E = ModuleMgr.end(); I != E; ++I) {
6796 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6797 size_t bytes = buf->getBufferSize();
6798 switch (buf->getBufferKind()) {
6799 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6800 sizes.malloc_bytes += bytes;
6801 break;
6802 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6803 sizes.mmap_bytes += bytes;
6804 break;
6805 }
6806 }
6807 }
6808}
6809
6810void ASTReader::InitializeSema(Sema &S) {
6811 SemaObj = &S;
6812 S.addExternalSource(this);
6813
6814 // Makes sure any declarations that were deserialized "too early"
6815 // still get added to the identifier's declaration chains.
6816 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006817 pushExternalDeclIntoScope(PreloadedDecls[I],
6818 PreloadedDecls[I]->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006819 }
6820 PreloadedDecls.clear();
6821
Richard Smith3d8e97e2013-10-18 06:54:39 +00006822 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006823 if (!FPPragmaOptions.empty()) {
6824 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6825 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6826 }
6827
Richard Smith3d8e97e2013-10-18 06:54:39 +00006828 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006829 if (!OpenCLExtensions.empty()) {
6830 unsigned I = 0;
6831#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6832#include "clang/Basic/OpenCLExtensions.def"
6833
6834 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6835 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006836
6837 UpdateSema();
6838}
6839
6840void ASTReader::UpdateSema() {
6841 assert(SemaObj && "no Sema to update");
6842
6843 // Load the offsets of the declarations that Sema references.
6844 // They will be lazily deserialized when needed.
6845 if (!SemaDeclRefs.empty()) {
6846 assert(SemaDeclRefs.size() % 2 == 0);
6847 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6848 if (!SemaObj->StdNamespace)
6849 SemaObj->StdNamespace = SemaDeclRefs[I];
6850 if (!SemaObj->StdBadAlloc)
6851 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6852 }
6853 SemaDeclRefs.clear();
6854 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006855
6856 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6857 // encountered the pragma in the source.
6858 if(OptimizeOffPragmaLocation.isValid())
6859 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006860}
6861
6862IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6863 // Note that we are loading an identifier.
6864 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006865 StringRef Name(NameStart, NameEnd - NameStart);
6866
6867 // If there is a global index, look there first to determine which modules
6868 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006869 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00006870 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00006871 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006872 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6873 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006874 }
6875 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006876 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006877 NumIdentifierLookups,
6878 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006879 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006880 IdentifierInfo *II = Visitor.getIdentifierInfo();
6881 markIdentifierUpToDate(II);
6882 return II;
6883}
6884
6885namespace clang {
6886 /// \brief An identifier-lookup iterator that enumerates all of the
6887 /// identifiers stored within a set of AST files.
6888 class ASTIdentifierIterator : public IdentifierIterator {
6889 /// \brief The AST reader whose identifiers are being enumerated.
6890 const ASTReader &Reader;
6891
6892 /// \brief The current index into the chain of AST files stored in
6893 /// the AST reader.
6894 unsigned Index;
6895
6896 /// \brief The current position within the identifier lookup table
6897 /// of the current AST file.
6898 ASTIdentifierLookupTable::key_iterator Current;
6899
6900 /// \brief The end position within the identifier lookup table of
6901 /// the current AST file.
6902 ASTIdentifierLookupTable::key_iterator End;
6903
6904 public:
6905 explicit ASTIdentifierIterator(const ASTReader &Reader);
6906
Craig Topper3e89dfe2014-03-13 02:13:41 +00006907 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006908 };
6909}
6910
6911ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6912 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6913 ASTIdentifierLookupTable *IdTable
6914 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6915 Current = IdTable->key_begin();
6916 End = IdTable->key_end();
6917}
6918
6919StringRef ASTIdentifierIterator::Next() {
6920 while (Current == End) {
6921 // If we have exhausted all of our AST files, we're done.
6922 if (Index == 0)
6923 return StringRef();
6924
6925 --Index;
6926 ASTIdentifierLookupTable *IdTable
6927 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6928 IdentifierLookupTable;
6929 Current = IdTable->key_begin();
6930 End = IdTable->key_end();
6931 }
6932
6933 // We have any identifiers remaining in the current AST file; return
6934 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006935 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006936 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006937 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006938}
6939
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006940IdentifierIterator *ASTReader::getIdentifiers() {
6941 if (!loadGlobalIndex())
6942 return GlobalIndex->createIdentifierIterator();
6943
Guy Benyei11169dd2012-12-18 14:30:41 +00006944 return new ASTIdentifierIterator(*this);
6945}
6946
6947namespace clang { namespace serialization {
6948 class ReadMethodPoolVisitor {
6949 ASTReader &Reader;
6950 Selector Sel;
6951 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006952 unsigned InstanceBits;
6953 unsigned FactoryBits;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006954 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6955 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006956
6957 public:
6958 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6959 unsigned PriorGeneration)
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006960 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6961 InstanceBits(0), FactoryBits(0) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006962
6963 static bool visit(ModuleFile &M, void *UserData) {
6964 ReadMethodPoolVisitor *This
6965 = static_cast<ReadMethodPoolVisitor *>(UserData);
6966
6967 if (!M.SelectorLookupTable)
6968 return false;
6969
6970 // If we've already searched this module file, skip it now.
6971 if (M.Generation <= This->PriorGeneration)
6972 return true;
6973
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006974 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006975 ASTSelectorLookupTable *PoolTable
6976 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6977 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6978 if (Pos == PoolTable->end())
6979 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006980
6981 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006982 ++This->Reader.NumSelectorsRead;
6983 // FIXME: Not quite happy with the statistics here. We probably should
6984 // disable this tracking when called via LoadSelector.
6985 // Also, should entries without methods count as misses?
6986 ++This->Reader.NumMethodPoolEntriesRead;
6987 ASTSelectorLookupTrait::data_type Data = *Pos;
6988 if (This->Reader.DeserializationListener)
6989 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6990 This->Sel);
6991
6992 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6993 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006994 This->InstanceBits = Data.InstanceBits;
6995 This->FactoryBits = Data.FactoryBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006996 return true;
6997 }
6998
6999 /// \brief Retrieve the instance methods found by this visitor.
7000 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7001 return InstanceMethods;
7002 }
7003
7004 /// \brief Retrieve the instance methods found by this visitor.
7005 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7006 return FactoryMethods;
7007 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007008
7009 unsigned getInstanceBits() const { return InstanceBits; }
7010 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007011 };
7012} } // end namespace clang::serialization
7013
7014/// \brief Add the given set of methods to the method list.
7015static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7016 ObjCMethodList &List) {
7017 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7018 S.addMethodToGlobalList(&List, Methods[I]);
7019 }
7020}
7021
7022void ASTReader::ReadMethodPool(Selector Sel) {
7023 // Get the selector generation and update it to the current generation.
7024 unsigned &Generation = SelectorGeneration[Sel];
7025 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007026 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007027
7028 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007029 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007030 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7031 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
7032
7033 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007034 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007035 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007036
7037 ++NumMethodPoolHits;
7038
Guy Benyei11169dd2012-12-18 14:30:41 +00007039 if (!getSema())
7040 return;
7041
7042 Sema &S = *getSema();
7043 Sema::GlobalMethodPool::iterator Pos
7044 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
7045
7046 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7047 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007048 Pos->second.first.setBits(Visitor.getInstanceBits());
7049 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei11169dd2012-12-18 14:30:41 +00007050}
7051
7052void ASTReader::ReadKnownNamespaces(
7053 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7054 Namespaces.clear();
7055
7056 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7057 if (NamespaceDecl *Namespace
7058 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7059 Namespaces.push_back(Namespace);
7060 }
7061}
7062
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007063void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007064 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007065 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7066 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007067 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007068 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007069 Undefined.insert(std::make_pair(D, Loc));
7070 }
7071}
Nick Lewycky8334af82013-01-26 00:35:08 +00007072
Guy Benyei11169dd2012-12-18 14:30:41 +00007073void ASTReader::ReadTentativeDefinitions(
7074 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7075 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7076 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7077 if (Var)
7078 TentativeDefs.push_back(Var);
7079 }
7080 TentativeDefinitions.clear();
7081}
7082
7083void ASTReader::ReadUnusedFileScopedDecls(
7084 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7085 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7086 DeclaratorDecl *D
7087 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7088 if (D)
7089 Decls.push_back(D);
7090 }
7091 UnusedFileScopedDecls.clear();
7092}
7093
7094void ASTReader::ReadDelegatingConstructors(
7095 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7096 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7097 CXXConstructorDecl *D
7098 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7099 if (D)
7100 Decls.push_back(D);
7101 }
7102 DelegatingCtorDecls.clear();
7103}
7104
7105void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7106 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7107 TypedefNameDecl *D
7108 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7109 if (D)
7110 Decls.push_back(D);
7111 }
7112 ExtVectorDecls.clear();
7113}
7114
7115void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
7116 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
7117 CXXRecordDecl *D
7118 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
7119 if (D)
7120 Decls.push_back(D);
7121 }
7122 DynamicClasses.clear();
7123}
7124
7125void
Richard Smith78165b52013-01-10 23:43:47 +00007126ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
7127 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
7128 NamedDecl *D
7129 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007130 if (D)
7131 Decls.push_back(D);
7132 }
Richard Smith78165b52013-01-10 23:43:47 +00007133 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007134}
7135
7136void ASTReader::ReadReferencedSelectors(
7137 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7138 if (ReferencedSelectorsData.empty())
7139 return;
7140
7141 // If there are @selector references added them to its pool. This is for
7142 // implementation of -Wselector.
7143 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7144 unsigned I = 0;
7145 while (I < DataSize) {
7146 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7147 SourceLocation SelLoc
7148 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7149 Sels.push_back(std::make_pair(Sel, SelLoc));
7150 }
7151 ReferencedSelectorsData.clear();
7152}
7153
7154void ASTReader::ReadWeakUndeclaredIdentifiers(
7155 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7156 if (WeakUndeclaredIdentifiers.empty())
7157 return;
7158
7159 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7160 IdentifierInfo *WeakId
7161 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7162 IdentifierInfo *AliasId
7163 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7164 SourceLocation Loc
7165 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7166 bool Used = WeakUndeclaredIdentifiers[I++];
7167 WeakInfo WI(AliasId, Loc);
7168 WI.setUsed(Used);
7169 WeakIDs.push_back(std::make_pair(WeakId, WI));
7170 }
7171 WeakUndeclaredIdentifiers.clear();
7172}
7173
7174void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7175 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7176 ExternalVTableUse VT;
7177 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7178 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7179 VT.DefinitionRequired = VTableUses[Idx++];
7180 VTables.push_back(VT);
7181 }
7182
7183 VTableUses.clear();
7184}
7185
7186void ASTReader::ReadPendingInstantiations(
7187 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7188 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7189 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7190 SourceLocation Loc
7191 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7192
7193 Pending.push_back(std::make_pair(D, Loc));
7194 }
7195 PendingInstantiations.clear();
7196}
7197
Richard Smithe40f2ba2013-08-07 21:41:30 +00007198void ASTReader::ReadLateParsedTemplates(
7199 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7200 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7201 /* In loop */) {
7202 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7203
7204 LateParsedTemplate *LT = new LateParsedTemplate;
7205 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7206
7207 ModuleFile *F = getOwningModuleFile(LT->D);
7208 assert(F && "No module");
7209
7210 unsigned TokN = LateParsedTemplates[Idx++];
7211 LT->Toks.reserve(TokN);
7212 for (unsigned T = 0; T < TokN; ++T)
7213 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7214
7215 LPTMap[FD] = LT;
7216 }
7217
7218 LateParsedTemplates.clear();
7219}
7220
Guy Benyei11169dd2012-12-18 14:30:41 +00007221void ASTReader::LoadSelector(Selector Sel) {
7222 // It would be complicated to avoid reading the methods anyway. So don't.
7223 ReadMethodPool(Sel);
7224}
7225
7226void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7227 assert(ID && "Non-zero identifier ID required");
7228 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7229 IdentifiersLoaded[ID - 1] = II;
7230 if (DeserializationListener)
7231 DeserializationListener->IdentifierRead(ID, II);
7232}
7233
7234/// \brief Set the globally-visible declarations associated with the given
7235/// identifier.
7236///
7237/// If the AST reader is currently in a state where the given declaration IDs
7238/// cannot safely be resolved, they are queued until it is safe to resolve
7239/// them.
7240///
7241/// \param II an IdentifierInfo that refers to one or more globally-visible
7242/// declarations.
7243///
7244/// \param DeclIDs the set of declaration IDs with the name @p II that are
7245/// visible at global scope.
7246///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007247/// \param Decls if non-null, this vector will be populated with the set of
7248/// deserialized declarations. These declarations will not be pushed into
7249/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007250void
7251ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7252 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007253 SmallVectorImpl<Decl *> *Decls) {
7254 if (NumCurrentElementsDeserializing && !Decls) {
7255 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007256 return;
7257 }
7258
7259 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
7260 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7261 if (SemaObj) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007262 // If we're simply supposed to record the declarations, do so now.
7263 if (Decls) {
7264 Decls->push_back(D);
7265 continue;
7266 }
7267
Guy Benyei11169dd2012-12-18 14:30:41 +00007268 // Introduce this declaration into the translation-unit scope
7269 // and add it to the declaration chain for this identifier, so
7270 // that (unqualified) name lookup will find it.
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007271 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007272 } else {
7273 // Queue this declaration so that it will be added to the
7274 // translation unit scope and identifier's declaration chain
7275 // once a Sema object is known.
7276 PreloadedDecls.push_back(D);
7277 }
7278 }
7279}
7280
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007281IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007282 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007283 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007284
7285 if (IdentifiersLoaded.empty()) {
7286 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007287 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007288 }
7289
7290 ID -= 1;
7291 if (!IdentifiersLoaded[ID]) {
7292 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7293 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7294 ModuleFile *M = I->second;
7295 unsigned Index = ID - M->BaseIdentifierID;
7296 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7297
7298 // All of the strings in the AST file are preceded by a 16-bit length.
7299 // Extract that 16-bit length to avoid having to execute strlen().
7300 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7301 // unsigned integers. This is important to avoid integer overflow when
7302 // we cast them to 'unsigned'.
7303 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7304 unsigned StrLen = (((unsigned) StrLenPtr[0])
7305 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007306 IdentifiersLoaded[ID]
7307 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007308 if (DeserializationListener)
7309 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7310 }
7311
7312 return IdentifiersLoaded[ID];
7313}
7314
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007315IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7316 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007317}
7318
7319IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7320 if (LocalID < NUM_PREDEF_IDENT_IDS)
7321 return LocalID;
7322
7323 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7324 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7325 assert(I != M.IdentifierRemap.end()
7326 && "Invalid index into identifier index remap");
7327
7328 return LocalID + I->second;
7329}
7330
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007331MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007332 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007333 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007334
7335 if (MacrosLoaded.empty()) {
7336 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007337 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007338 }
7339
7340 ID -= NUM_PREDEF_MACRO_IDS;
7341 if (!MacrosLoaded[ID]) {
7342 GlobalMacroMapType::iterator I
7343 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7344 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7345 ModuleFile *M = I->second;
7346 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007347 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7348
7349 if (DeserializationListener)
7350 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7351 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007352 }
7353
7354 return MacrosLoaded[ID];
7355}
7356
7357MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7358 if (LocalID < NUM_PREDEF_MACRO_IDS)
7359 return LocalID;
7360
7361 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7362 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7363 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7364
7365 return LocalID + I->second;
7366}
7367
7368serialization::SubmoduleID
7369ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7370 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7371 return LocalID;
7372
7373 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7374 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7375 assert(I != M.SubmoduleRemap.end()
7376 && "Invalid index into submodule index remap");
7377
7378 return LocalID + I->second;
7379}
7380
7381Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7382 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7383 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007384 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007385 }
7386
7387 if (GlobalID > SubmodulesLoaded.size()) {
7388 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007389 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007390 }
7391
7392 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7393}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007394
7395Module *ASTReader::getModule(unsigned ID) {
7396 return getSubmodule(ID);
7397}
7398
Guy Benyei11169dd2012-12-18 14:30:41 +00007399Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7400 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7401}
7402
7403Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7404 if (ID == 0)
7405 return Selector();
7406
7407 if (ID > SelectorsLoaded.size()) {
7408 Error("selector ID out of range in AST file");
7409 return Selector();
7410 }
7411
Craig Toppera13603a2014-05-22 05:54:18 +00007412 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007413 // Load this selector from the selector table.
7414 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7415 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7416 ModuleFile &M = *I->second;
7417 ASTSelectorLookupTrait Trait(*this, M);
7418 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7419 SelectorsLoaded[ID - 1] =
7420 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7421 if (DeserializationListener)
7422 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7423 }
7424
7425 return SelectorsLoaded[ID - 1];
7426}
7427
7428Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7429 return DecodeSelector(ID);
7430}
7431
7432uint32_t ASTReader::GetNumExternalSelectors() {
7433 // ID 0 (the null selector) is considered an external selector.
7434 return getTotalNumSelectors() + 1;
7435}
7436
7437serialization::SelectorID
7438ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7439 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7440 return LocalID;
7441
7442 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7443 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7444 assert(I != M.SelectorRemap.end()
7445 && "Invalid index into selector index remap");
7446
7447 return LocalID + I->second;
7448}
7449
7450DeclarationName
7451ASTReader::ReadDeclarationName(ModuleFile &F,
7452 const RecordData &Record, unsigned &Idx) {
7453 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7454 switch (Kind) {
7455 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007456 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007457
7458 case DeclarationName::ObjCZeroArgSelector:
7459 case DeclarationName::ObjCOneArgSelector:
7460 case DeclarationName::ObjCMultiArgSelector:
7461 return DeclarationName(ReadSelector(F, Record, Idx));
7462
7463 case DeclarationName::CXXConstructorName:
7464 return Context.DeclarationNames.getCXXConstructorName(
7465 Context.getCanonicalType(readType(F, Record, Idx)));
7466
7467 case DeclarationName::CXXDestructorName:
7468 return Context.DeclarationNames.getCXXDestructorName(
7469 Context.getCanonicalType(readType(F, Record, Idx)));
7470
7471 case DeclarationName::CXXConversionFunctionName:
7472 return Context.DeclarationNames.getCXXConversionFunctionName(
7473 Context.getCanonicalType(readType(F, Record, Idx)));
7474
7475 case DeclarationName::CXXOperatorName:
7476 return Context.DeclarationNames.getCXXOperatorName(
7477 (OverloadedOperatorKind)Record[Idx++]);
7478
7479 case DeclarationName::CXXLiteralOperatorName:
7480 return Context.DeclarationNames.getCXXLiteralOperatorName(
7481 GetIdentifierInfo(F, Record, Idx));
7482
7483 case DeclarationName::CXXUsingDirective:
7484 return DeclarationName::getUsingDirectiveName();
7485 }
7486
7487 llvm_unreachable("Invalid NameKind!");
7488}
7489
7490void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7491 DeclarationNameLoc &DNLoc,
7492 DeclarationName Name,
7493 const RecordData &Record, unsigned &Idx) {
7494 switch (Name.getNameKind()) {
7495 case DeclarationName::CXXConstructorName:
7496 case DeclarationName::CXXDestructorName:
7497 case DeclarationName::CXXConversionFunctionName:
7498 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7499 break;
7500
7501 case DeclarationName::CXXOperatorName:
7502 DNLoc.CXXOperatorName.BeginOpNameLoc
7503 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7504 DNLoc.CXXOperatorName.EndOpNameLoc
7505 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7506 break;
7507
7508 case DeclarationName::CXXLiteralOperatorName:
7509 DNLoc.CXXLiteralOperatorName.OpNameLoc
7510 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7511 break;
7512
7513 case DeclarationName::Identifier:
7514 case DeclarationName::ObjCZeroArgSelector:
7515 case DeclarationName::ObjCOneArgSelector:
7516 case DeclarationName::ObjCMultiArgSelector:
7517 case DeclarationName::CXXUsingDirective:
7518 break;
7519 }
7520}
7521
7522void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7523 DeclarationNameInfo &NameInfo,
7524 const RecordData &Record, unsigned &Idx) {
7525 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7526 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7527 DeclarationNameLoc DNLoc;
7528 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7529 NameInfo.setInfo(DNLoc);
7530}
7531
7532void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7533 const RecordData &Record, unsigned &Idx) {
7534 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7535 unsigned NumTPLists = Record[Idx++];
7536 Info.NumTemplParamLists = NumTPLists;
7537 if (NumTPLists) {
7538 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7539 for (unsigned i=0; i != NumTPLists; ++i)
7540 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7541 }
7542}
7543
7544TemplateName
7545ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7546 unsigned &Idx) {
7547 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7548 switch (Kind) {
7549 case TemplateName::Template:
7550 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7551
7552 case TemplateName::OverloadedTemplate: {
7553 unsigned size = Record[Idx++];
7554 UnresolvedSet<8> Decls;
7555 while (size--)
7556 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7557
7558 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7559 }
7560
7561 case TemplateName::QualifiedTemplate: {
7562 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7563 bool hasTemplKeyword = Record[Idx++];
7564 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7565 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7566 }
7567
7568 case TemplateName::DependentTemplate: {
7569 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7570 if (Record[Idx++]) // isIdentifier
7571 return Context.getDependentTemplateName(NNS,
7572 GetIdentifierInfo(F, Record,
7573 Idx));
7574 return Context.getDependentTemplateName(NNS,
7575 (OverloadedOperatorKind)Record[Idx++]);
7576 }
7577
7578 case TemplateName::SubstTemplateTemplateParm: {
7579 TemplateTemplateParmDecl *param
7580 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7581 if (!param) return TemplateName();
7582 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7583 return Context.getSubstTemplateTemplateParm(param, replacement);
7584 }
7585
7586 case TemplateName::SubstTemplateTemplateParmPack: {
7587 TemplateTemplateParmDecl *Param
7588 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7589 if (!Param)
7590 return TemplateName();
7591
7592 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7593 if (ArgPack.getKind() != TemplateArgument::Pack)
7594 return TemplateName();
7595
7596 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7597 }
7598 }
7599
7600 llvm_unreachable("Unhandled template name kind!");
7601}
7602
7603TemplateArgument
7604ASTReader::ReadTemplateArgument(ModuleFile &F,
7605 const RecordData &Record, unsigned &Idx) {
7606 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7607 switch (Kind) {
7608 case TemplateArgument::Null:
7609 return TemplateArgument();
7610 case TemplateArgument::Type:
7611 return TemplateArgument(readType(F, Record, Idx));
7612 case TemplateArgument::Declaration: {
7613 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7614 bool ForReferenceParam = Record[Idx++];
7615 return TemplateArgument(D, ForReferenceParam);
7616 }
7617 case TemplateArgument::NullPtr:
7618 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7619 case TemplateArgument::Integral: {
7620 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7621 QualType T = readType(F, Record, Idx);
7622 return TemplateArgument(Context, Value, T);
7623 }
7624 case TemplateArgument::Template:
7625 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7626 case TemplateArgument::TemplateExpansion: {
7627 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007628 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007629 if (unsigned NumExpansions = Record[Idx++])
7630 NumTemplateExpansions = NumExpansions - 1;
7631 return TemplateArgument(Name, NumTemplateExpansions);
7632 }
7633 case TemplateArgument::Expression:
7634 return TemplateArgument(ReadExpr(F));
7635 case TemplateArgument::Pack: {
7636 unsigned NumArgs = Record[Idx++];
7637 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7638 for (unsigned I = 0; I != NumArgs; ++I)
7639 Args[I] = ReadTemplateArgument(F, Record, Idx);
7640 return TemplateArgument(Args, NumArgs);
7641 }
7642 }
7643
7644 llvm_unreachable("Unhandled template argument kind!");
7645}
7646
7647TemplateParameterList *
7648ASTReader::ReadTemplateParameterList(ModuleFile &F,
7649 const RecordData &Record, unsigned &Idx) {
7650 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7651 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7652 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7653
7654 unsigned NumParams = Record[Idx++];
7655 SmallVector<NamedDecl *, 16> Params;
7656 Params.reserve(NumParams);
7657 while (NumParams--)
7658 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7659
7660 TemplateParameterList* TemplateParams =
7661 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7662 Params.data(), Params.size(), RAngleLoc);
7663 return TemplateParams;
7664}
7665
7666void
7667ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007668ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007669 ModuleFile &F, const RecordData &Record,
7670 unsigned &Idx) {
7671 unsigned NumTemplateArgs = Record[Idx++];
7672 TemplArgs.reserve(NumTemplateArgs);
7673 while (NumTemplateArgs--)
7674 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7675}
7676
7677/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007678void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007679 const RecordData &Record, unsigned &Idx) {
7680 unsigned NumDecls = Record[Idx++];
7681 Set.reserve(Context, NumDecls);
7682 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007683 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007684 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007685 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007686 }
7687}
7688
7689CXXBaseSpecifier
7690ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7691 const RecordData &Record, unsigned &Idx) {
7692 bool isVirtual = static_cast<bool>(Record[Idx++]);
7693 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7694 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7695 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7696 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7697 SourceRange Range = ReadSourceRange(F, Record, Idx);
7698 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7699 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7700 EllipsisLoc);
7701 Result.setInheritConstructors(inheritConstructors);
7702 return Result;
7703}
7704
7705std::pair<CXXCtorInitializer **, unsigned>
7706ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7707 unsigned &Idx) {
Craig Toppera13603a2014-05-22 05:54:18 +00007708 CXXCtorInitializer **CtorInitializers = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007709 unsigned NumInitializers = Record[Idx++];
7710 if (NumInitializers) {
7711 CtorInitializers
7712 = new (Context) CXXCtorInitializer*[NumInitializers];
7713 for (unsigned i=0; i != NumInitializers; ++i) {
Craig Toppera13603a2014-05-22 05:54:18 +00007714 TypeSourceInfo *TInfo = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007715 bool IsBaseVirtual = false;
Craig Toppera13603a2014-05-22 05:54:18 +00007716 FieldDecl *Member = nullptr;
7717 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007718
7719 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7720 switch (Type) {
7721 case CTOR_INITIALIZER_BASE:
7722 TInfo = GetTypeSourceInfo(F, Record, Idx);
7723 IsBaseVirtual = Record[Idx++];
7724 break;
7725
7726 case CTOR_INITIALIZER_DELEGATING:
7727 TInfo = GetTypeSourceInfo(F, Record, Idx);
7728 break;
7729
7730 case CTOR_INITIALIZER_MEMBER:
7731 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7732 break;
7733
7734 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7735 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7736 break;
7737 }
7738
7739 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7740 Expr *Init = ReadExpr(F);
7741 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7742 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7743 bool IsWritten = Record[Idx++];
7744 unsigned SourceOrderOrNumArrayIndices;
7745 SmallVector<VarDecl *, 8> Indices;
7746 if (IsWritten) {
7747 SourceOrderOrNumArrayIndices = Record[Idx++];
7748 } else {
7749 SourceOrderOrNumArrayIndices = Record[Idx++];
7750 Indices.reserve(SourceOrderOrNumArrayIndices);
7751 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7752 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7753 }
7754
7755 CXXCtorInitializer *BOMInit;
7756 if (Type == CTOR_INITIALIZER_BASE) {
7757 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7758 LParenLoc, Init, RParenLoc,
7759 MemberOrEllipsisLoc);
7760 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7761 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7762 Init, RParenLoc);
7763 } else if (IsWritten) {
7764 if (Member)
7765 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7766 LParenLoc, Init, RParenLoc);
7767 else
7768 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7769 MemberOrEllipsisLoc, LParenLoc,
7770 Init, RParenLoc);
7771 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007772 if (IndirectMember) {
7773 assert(Indices.empty() && "Indirect field improperly initialized");
7774 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7775 MemberOrEllipsisLoc, LParenLoc,
7776 Init, RParenLoc);
7777 } else {
7778 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7779 LParenLoc, Init, RParenLoc,
7780 Indices.data(), Indices.size());
7781 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007782 }
7783
7784 if (IsWritten)
7785 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7786 CtorInitializers[i] = BOMInit;
7787 }
7788 }
7789
7790 return std::make_pair(CtorInitializers, NumInitializers);
7791}
7792
7793NestedNameSpecifier *
7794ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7795 const RecordData &Record, unsigned &Idx) {
7796 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007797 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007798 for (unsigned I = 0; I != N; ++I) {
7799 NestedNameSpecifier::SpecifierKind Kind
7800 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7801 switch (Kind) {
7802 case NestedNameSpecifier::Identifier: {
7803 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7804 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7805 break;
7806 }
7807
7808 case NestedNameSpecifier::Namespace: {
7809 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7810 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7811 break;
7812 }
7813
7814 case NestedNameSpecifier::NamespaceAlias: {
7815 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7816 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7817 break;
7818 }
7819
7820 case NestedNameSpecifier::TypeSpec:
7821 case NestedNameSpecifier::TypeSpecWithTemplate: {
7822 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7823 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007824 return nullptr;
7825
Guy Benyei11169dd2012-12-18 14:30:41 +00007826 bool Template = Record[Idx++];
7827 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7828 break;
7829 }
7830
7831 case NestedNameSpecifier::Global: {
7832 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7833 // No associated value, and there can't be a prefix.
7834 break;
7835 }
7836 }
7837 Prev = NNS;
7838 }
7839 return NNS;
7840}
7841
7842NestedNameSpecifierLoc
7843ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7844 unsigned &Idx) {
7845 unsigned N = Record[Idx++];
7846 NestedNameSpecifierLocBuilder Builder;
7847 for (unsigned I = 0; I != N; ++I) {
7848 NestedNameSpecifier::SpecifierKind Kind
7849 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7850 switch (Kind) {
7851 case NestedNameSpecifier::Identifier: {
7852 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7853 SourceRange Range = ReadSourceRange(F, Record, Idx);
7854 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7855 break;
7856 }
7857
7858 case NestedNameSpecifier::Namespace: {
7859 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7860 SourceRange Range = ReadSourceRange(F, Record, Idx);
7861 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7862 break;
7863 }
7864
7865 case NestedNameSpecifier::NamespaceAlias: {
7866 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7867 SourceRange Range = ReadSourceRange(F, Record, Idx);
7868 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7869 break;
7870 }
7871
7872 case NestedNameSpecifier::TypeSpec:
7873 case NestedNameSpecifier::TypeSpecWithTemplate: {
7874 bool Template = Record[Idx++];
7875 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7876 if (!T)
7877 return NestedNameSpecifierLoc();
7878 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7879
7880 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7881 Builder.Extend(Context,
7882 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7883 T->getTypeLoc(), ColonColonLoc);
7884 break;
7885 }
7886
7887 case NestedNameSpecifier::Global: {
7888 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7889 Builder.MakeGlobal(Context, ColonColonLoc);
7890 break;
7891 }
7892 }
7893 }
7894
7895 return Builder.getWithLocInContext(Context);
7896}
7897
7898SourceRange
7899ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7900 unsigned &Idx) {
7901 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7902 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7903 return SourceRange(beg, end);
7904}
7905
7906/// \brief Read an integral value
7907llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7908 unsigned BitWidth = Record[Idx++];
7909 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7910 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7911 Idx += NumWords;
7912 return Result;
7913}
7914
7915/// \brief Read a signed integral value
7916llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7917 bool isUnsigned = Record[Idx++];
7918 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7919}
7920
7921/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007922llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7923 const llvm::fltSemantics &Sem,
7924 unsigned &Idx) {
7925 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007926}
7927
7928// \brief Read a string
7929std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7930 unsigned Len = Record[Idx++];
7931 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7932 Idx += Len;
7933 return Result;
7934}
7935
7936VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7937 unsigned &Idx) {
7938 unsigned Major = Record[Idx++];
7939 unsigned Minor = Record[Idx++];
7940 unsigned Subminor = Record[Idx++];
7941 if (Minor == 0)
7942 return VersionTuple(Major);
7943 if (Subminor == 0)
7944 return VersionTuple(Major, Minor - 1);
7945 return VersionTuple(Major, Minor - 1, Subminor - 1);
7946}
7947
7948CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7949 const RecordData &Record,
7950 unsigned &Idx) {
7951 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7952 return CXXTemporary::Create(Context, Decl);
7953}
7954
7955DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007956 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007957}
7958
7959DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7960 return Diags.Report(Loc, DiagID);
7961}
7962
7963/// \brief Retrieve the identifier table associated with the
7964/// preprocessor.
7965IdentifierTable &ASTReader::getIdentifierTable() {
7966 return PP.getIdentifierTable();
7967}
7968
7969/// \brief Record that the given ID maps to the given switch-case
7970/// statement.
7971void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007972 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007973 "Already have a SwitchCase with this ID");
7974 (*CurrSwitchCaseStmts)[ID] = SC;
7975}
7976
7977/// \brief Retrieve the switch-case statement with the given ID.
7978SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007979 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00007980 return (*CurrSwitchCaseStmts)[ID];
7981}
7982
7983void ASTReader::ClearSwitchCaseIDs() {
7984 CurrSwitchCaseStmts->clear();
7985}
7986
7987void ASTReader::ReadComments() {
7988 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007989 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007990 serialization::ModuleFile *> >::iterator
7991 I = CommentsCursors.begin(),
7992 E = CommentsCursors.end();
7993 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007994 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007995 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007996 serialization::ModuleFile &F = *I->second;
7997 SavedStreamPosition SavedPosition(Cursor);
7998
7999 RecordData Record;
8000 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008001 llvm::BitstreamEntry Entry =
8002 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008003
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008004 switch (Entry.Kind) {
8005 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8006 case llvm::BitstreamEntry::Error:
8007 Error("malformed block record in AST file");
8008 return;
8009 case llvm::BitstreamEntry::EndBlock:
8010 goto NextCursor;
8011 case llvm::BitstreamEntry::Record:
8012 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008013 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008014 }
8015
8016 // Read a record.
8017 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008018 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008019 case COMMENTS_RAW_COMMENT: {
8020 unsigned Idx = 0;
8021 SourceRange SR = ReadSourceRange(F, Record, Idx);
8022 RawComment::CommentKind Kind =
8023 (RawComment::CommentKind) Record[Idx++];
8024 bool IsTrailingComment = Record[Idx++];
8025 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008026 Comments.push_back(new (Context) RawComment(
8027 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8028 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008029 break;
8030 }
8031 }
8032 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008033 NextCursor:
8034 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008035 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008036}
8037
Richard Smithcd45dbc2014-04-19 03:48:30 +00008038std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8039 // If we know the owning module, use it.
8040 if (Module *M = D->getOwningModule())
8041 return M->getFullModuleName();
8042
8043 // Otherwise, use the name of the top-level module the decl is within.
8044 if (ModuleFile *M = getOwningModuleFile(D))
8045 return M->ModuleName;
8046
8047 // Not from a module.
8048 return "";
8049}
8050
Guy Benyei11169dd2012-12-18 14:30:41 +00008051void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008052 while (!PendingIdentifierInfos.empty() ||
8053 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008054 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smith93914a92014-05-08 00:25:01 +00008055 !PendingUpdateRecords.empty() || !PendingOdrMergeChecks.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008056 // If any identifiers with corresponding top-level declarations have
8057 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008058 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8059 TopLevelDeclsMap;
8060 TopLevelDeclsMap TopLevelDecls;
8061
Guy Benyei11169dd2012-12-18 14:30:41 +00008062 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008063 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008064 SmallVector<uint32_t, 4> DeclIDs =
8065 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008066 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008067
8068 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008069 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008070
Richard Smith851072e2014-05-19 20:59:20 +00008071 // For each decl chain that we wanted to complete while deserializing, mark
8072 // it as "still needs to be completed".
8073 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8074 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8075 }
8076 PendingIncompleteDeclChains.clear();
8077
Guy Benyei11169dd2012-12-18 14:30:41 +00008078 // Load pending declaration chains.
8079 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
8080 loadPendingDeclChain(PendingDeclChains[I]);
8081 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
8082 }
8083 PendingDeclChains.clear();
8084
Douglas Gregor6168bd22013-02-18 15:53:43 +00008085 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008086 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8087 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008088 IdentifierInfo *II = TLD->first;
8089 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008090 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008091 }
8092 }
8093
Guy Benyei11169dd2012-12-18 14:30:41 +00008094 // Load any pending macro definitions.
8095 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008096 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8097 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8098 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8099 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008100 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008101 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008102 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8103 if (Info.M->Kind != MK_Module)
8104 resolvePendingMacro(II, Info);
8105 }
8106 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008107 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008108 ++IDIdx) {
8109 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8110 if (Info.M->Kind == MK_Module)
8111 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008112 }
8113 }
8114 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008115
8116 // Wire up the DeclContexts for Decls that we delayed setting until
8117 // recursive loading is completed.
8118 while (!PendingDeclContextInfos.empty()) {
8119 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8120 PendingDeclContextInfos.pop_front();
8121 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8122 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8123 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8124 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008125
Richard Smithd1c46742014-04-30 02:24:17 +00008126 // Perform any pending declaration updates.
Richard Smith675d2792014-06-16 20:26:19 +00008127 //
8128 // Don't do this if we have known-incomplete redecl chains: it relies on
8129 // being able to walk redeclaration chains.
8130 while (PendingDeclChains.empty() && !PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008131 auto Update = PendingUpdateRecords.pop_back_val();
8132 ReadingKindTracker ReadingKind(Read_Decl, *this);
8133 loadDeclUpdateRecords(Update.first, Update.second);
8134 }
8135
Richard Smithcd45dbc2014-04-19 03:48:30 +00008136 // Trigger the import of the full definition of each class that had any
8137 // odr-merging problems, so we can produce better diagnostics for them.
8138 for (auto &Merge : PendingOdrMergeFailures) {
8139 Merge.first->buildLookup();
8140 Merge.first->decls_begin();
8141 Merge.first->bases_begin();
8142 Merge.first->vbases_begin();
8143 for (auto *RD : Merge.second) {
8144 RD->decls_begin();
8145 RD->bases_begin();
8146 RD->vbases_begin();
8147 }
8148 }
8149
Richard Smith2b9e3e32013-10-18 06:05:18 +00008150 // For each declaration from a merged context, check that the canonical
8151 // definition of that context also contains a declaration of the same
8152 // entity.
8153 while (!PendingOdrMergeChecks.empty()) {
8154 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8155
8156 // FIXME: Skip over implicit declarations for now. This matters for things
8157 // like implicitly-declared special member functions. This isn't entirely
8158 // correct; we can end up with multiple unmerged declarations of the same
8159 // implicit entity.
8160 if (D->isImplicit())
8161 continue;
8162
8163 DeclContext *CanonDef = D->getDeclContext();
8164 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
8165
8166 bool Found = false;
8167 const Decl *DCanon = D->getCanonicalDecl();
8168
8169 llvm::SmallVector<const NamedDecl*, 4> Candidates;
8170 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8171 !Found && I != E; ++I) {
Aaron Ballman86c93902014-03-06 23:45:36 +00008172 for (auto RI : (*I)->redecls()) {
8173 if (RI->getLexicalDeclContext() == CanonDef) {
Richard Smith2b9e3e32013-10-18 06:05:18 +00008174 // This declaration is present in the canonical definition. If it's
8175 // in the same redecl chain, it's the one we're looking for.
Aaron Ballman86c93902014-03-06 23:45:36 +00008176 if (RI->getCanonicalDecl() == DCanon)
Richard Smith2b9e3e32013-10-18 06:05:18 +00008177 Found = true;
8178 else
Aaron Ballman86c93902014-03-06 23:45:36 +00008179 Candidates.push_back(cast<NamedDecl>(RI));
Richard Smith2b9e3e32013-10-18 06:05:18 +00008180 break;
8181 }
8182 }
8183 }
8184
8185 if (!Found) {
8186 D->setInvalidDecl();
8187
Richard Smithcd45dbc2014-04-19 03:48:30 +00008188 std::string CanonDefModule =
8189 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
Richard Smith2b9e3e32013-10-18 06:05:18 +00008190 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008191 << D << getOwningModuleNameForDiagnostic(D)
8192 << CanonDef << CanonDefModule.empty() << CanonDefModule;
Richard Smith2b9e3e32013-10-18 06:05:18 +00008193
8194 if (Candidates.empty())
8195 Diag(cast<Decl>(CanonDef)->getLocation(),
8196 diag::note_module_odr_violation_no_possible_decls) << D;
8197 else {
8198 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8199 Diag(Candidates[I]->getLocation(),
8200 diag::note_module_odr_violation_possible_decl)
8201 << Candidates[I];
8202 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008203
8204 DiagnosedOdrMergeFailures.insert(CanonDef);
Richard Smith2b9e3e32013-10-18 06:05:18 +00008205 }
8206 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008207 }
8208
8209 // If we deserialized any C++ or Objective-C class definitions, any
8210 // Objective-C protocol definitions, or any redeclarable templates, make sure
8211 // that all redeclarations point to the definitions. Note that this can only
8212 // happen now, after the redeclaration chains have been fully wired.
8213 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
8214 DEnd = PendingDefinitions.end();
8215 D != DEnd; ++D) {
8216 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008217 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008218 // Make sure that the TagType points at the definition.
8219 const_cast<TagType*>(TagT)->decl = TD;
8220 }
8221
Aaron Ballman86c93902014-03-06 23:45:36 +00008222 if (auto RD = dyn_cast<CXXRecordDecl>(*D)) {
8223 for (auto R : RD->redecls())
8224 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Guy Benyei11169dd2012-12-18 14:30:41 +00008225 }
8226
8227 continue;
8228 }
8229
Aaron Ballman86c93902014-03-06 23:45:36 +00008230 if (auto ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008231 // Make sure that the ObjCInterfaceType points at the definition.
8232 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8233 ->Decl = ID;
8234
Aaron Ballman86c93902014-03-06 23:45:36 +00008235 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008236 R->Data = ID->Data;
8237
8238 continue;
8239 }
8240
Aaron Ballman86c93902014-03-06 23:45:36 +00008241 if (auto PD = dyn_cast<ObjCProtocolDecl>(*D)) {
8242 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008243 R->Data = PD->Data;
8244
8245 continue;
8246 }
8247
Aaron Ballman86c93902014-03-06 23:45:36 +00008248 auto RTD = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
8249 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008250 R->Common = RTD->Common;
8251 }
8252 PendingDefinitions.clear();
8253
8254 // Load the bodies of any functions or methods we've encountered. We do
8255 // this now (delayed) so that we can be sure that the declaration chains
8256 // have been fully wired up.
8257 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8258 PBEnd = PendingBodies.end();
8259 PB != PBEnd; ++PB) {
8260 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8261 // FIXME: Check for =delete/=default?
8262 // FIXME: Complain about ODR violations here?
8263 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8264 FD->setLazyBody(PB->second);
8265 continue;
8266 }
8267
8268 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8269 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8270 MD->setLazyBody(PB->second);
8271 }
8272 PendingBodies.clear();
Richard Smithcd45dbc2014-04-19 03:48:30 +00008273
8274 // Issue any pending ODR-failure diagnostics.
8275 for (auto &Merge : PendingOdrMergeFailures) {
8276 if (!DiagnosedOdrMergeFailures.insert(Merge.first))
8277 continue;
8278
8279 bool Diagnosed = false;
8280 for (auto *RD : Merge.second) {
8281 // Multiple different declarations got merged together; tell the user
8282 // where they came from.
8283 if (Merge.first != RD) {
8284 // FIXME: Walk the definition, figure out what's different,
8285 // and diagnose that.
8286 if (!Diagnosed) {
8287 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8288 Diag(Merge.first->getLocation(),
8289 diag::err_module_odr_violation_different_definitions)
8290 << Merge.first << Module.empty() << Module;
8291 Diagnosed = true;
8292 }
8293
8294 Diag(RD->getLocation(),
8295 diag::note_module_odr_violation_different_definitions)
8296 << getOwningModuleNameForDiagnostic(RD);
8297 }
8298 }
8299
8300 if (!Diagnosed) {
8301 // All definitions are updates to the same declaration. This happens if a
8302 // module instantiates the declaration of a class template specialization
8303 // and two or more other modules instantiate its definition.
8304 //
8305 // FIXME: Indicate which modules had instantiations of this definition.
8306 // FIXME: How can this even happen?
8307 Diag(Merge.first->getLocation(),
8308 diag::err_module_odr_violation_different_instantiations)
8309 << Merge.first;
8310 }
8311 }
8312 PendingOdrMergeFailures.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00008313}
8314
8315void ASTReader::FinishedDeserializing() {
8316 assert(NumCurrentElementsDeserializing &&
8317 "FinishedDeserializing not paired with StartedDeserializing");
8318 if (NumCurrentElementsDeserializing == 1) {
8319 // We decrease NumCurrentElementsDeserializing only after pending actions
8320 // are finished, to avoid recursively re-calling finishPendingActions().
8321 finishPendingActions();
8322 }
8323 --NumCurrentElementsDeserializing;
8324
Richard Smith04d05b52014-03-23 00:27:18 +00008325 if (NumCurrentElementsDeserializing == 0 && Consumer) {
8326 // We are not in recursive loading, so it's safe to pass the "interesting"
8327 // decls to the consumer.
8328 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008329 }
8330}
8331
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008332void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00008333 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008334
8335 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8336 SemaObj->TUScope->AddDecl(D);
8337 } else if (SemaObj->TUScope) {
8338 // Adding the decl to IdResolver may have failed because it was already in
8339 // (even though it was not added in scope). If it is already in, make sure
8340 // it gets in the scope as well.
8341 if (std::find(SemaObj->IdResolver.begin(Name),
8342 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8343 SemaObj->TUScope->AddDecl(D);
8344 }
8345}
8346
Nico Weber824285e2014-05-08 04:26:47 +00008347ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8348 bool DisableValidation, bool AllowASTWithCompilerErrors,
8349 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008350 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008351 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008352 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Craig Toppera13603a2014-05-22 05:54:18 +00008353 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
8354 SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
8355 ModuleMgr(PP.getFileManager()), isysroot(isysroot),
8356 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008357 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8358 AllowConfigurationMismatch(AllowConfigurationMismatch),
8359 ValidateSystemInputs(ValidateSystemInputs),
8360 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Richard Smith053f6c62014-05-16 23:01:30 +00008361 CurrSwitchCaseStmts(&SwitchCaseStmts),
Nico Weber824285e2014-05-08 04:26:47 +00008362 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8363 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8364 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8365 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8366 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8367 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8368 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8369 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8370 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8371 PassingDeclsToConsumer(false), NumCXXBaseSpecifiersLoaded(0),
8372 ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008373 SourceMgr.setExternalSLocEntrySource(this);
8374}
8375
8376ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008377 if (OwnsDeserializationListener)
8378 delete DeserializationListener;
8379
Guy Benyei11169dd2012-12-18 14:30:41 +00008380 for (DeclContextVisibleUpdatesPending::iterator
8381 I = PendingVisibleUpdates.begin(),
8382 E = PendingVisibleUpdates.end();
8383 I != E; ++I) {
8384 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8385 F = I->second.end();
8386 J != F; ++J)
8387 delete J->first;
8388 }
8389}