blob: 143a7386ff2fa4c158f5f2617407dcf414734f50 [file] [log] [blame]
Nick Lewyckyf0f56162013-01-31 03:23:57 +00001//===--- ASTReader.cpp - AST File Reader ----------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the ASTReader class, which reads AST files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Serialization/ASTReader.h"
15#include "ASTCommon.h"
16#include "ASTReaderInternals.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/NestedNameSpecifier.h"
23#include "clang/AST/Type.h"
24#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000025#include "clang/Basic/DiagnosticOptions.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000026#include "clang/Basic/FileManager.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000027#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/SourceManagerInternals.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Basic/TargetOptions.h"
31#include "clang/Basic/Version.h"
32#include "clang/Basic/VersionTuple.h"
Ben Langmuirb92de022014-04-29 16:25:26 +000033#include "clang/Frontend/Utils.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000034#include "clang/Lex/HeaderSearch.h"
35#include "clang/Lex/HeaderSearchOptions.h"
36#include "clang/Lex/MacroInfo.h"
37#include "clang/Lex/PreprocessingRecord.h"
38#include "clang/Lex/Preprocessor.h"
39#include "clang/Lex/PreprocessorOptions.h"
40#include "clang/Sema/Scope.h"
41#include "clang/Sema/Sema.h"
42#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000043#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000044#include "clang/Serialization/ModuleManager.h"
45#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000046#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000047#include "llvm/ADT/StringExtras.h"
48#include "llvm/Bitcode/BitstreamReader.h"
49#include "llvm/Support/ErrorHandling.h"
50#include "llvm/Support/FileSystem.h"
51#include "llvm/Support/MemoryBuffer.h"
52#include "llvm/Support/Path.h"
53#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000054#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000055#include "llvm/Support/system_error.h"
56#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000057#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000058#include <iterator>
59
60using namespace clang;
61using namespace clang::serialization;
62using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000063using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000064
Ben Langmuircb69b572014-03-07 06:40:32 +000065
66//===----------------------------------------------------------------------===//
67// ChainedASTReaderListener implementation
68//===----------------------------------------------------------------------===//
69
70bool
71ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
72 return First->ReadFullVersionInformation(FullVersion) ||
73 Second->ReadFullVersionInformation(FullVersion);
74}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000075void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
76 First->ReadModuleName(ModuleName);
77 Second->ReadModuleName(ModuleName);
78}
79void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
80 First->ReadModuleMapFile(ModuleMapPath);
81 Second->ReadModuleMapFile(ModuleMapPath);
82}
Ben Langmuircb69b572014-03-07 06:40:32 +000083bool ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
84 bool Complain) {
85 return First->ReadLanguageOptions(LangOpts, Complain) ||
86 Second->ReadLanguageOptions(LangOpts, Complain);
87}
88bool
89ChainedASTReaderListener::ReadTargetOptions(const TargetOptions &TargetOpts,
90 bool Complain) {
91 return First->ReadTargetOptions(TargetOpts, Complain) ||
92 Second->ReadTargetOptions(TargetOpts, Complain);
93}
94bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +000095 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +000096 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
97 Second->ReadDiagnosticOptions(DiagOpts, Complain);
98}
99bool
100ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
101 bool Complain) {
102 return First->ReadFileSystemOptions(FSOpts, Complain) ||
103 Second->ReadFileSystemOptions(FSOpts, Complain);
104}
105
106bool ChainedASTReaderListener::ReadHeaderSearchOptions(
107 const HeaderSearchOptions &HSOpts, bool Complain) {
108 return First->ReadHeaderSearchOptions(HSOpts, Complain) ||
109 Second->ReadHeaderSearchOptions(HSOpts, Complain);
110}
111bool ChainedASTReaderListener::ReadPreprocessorOptions(
112 const PreprocessorOptions &PPOpts, bool Complain,
113 std::string &SuggestedPredefines) {
114 return First->ReadPreprocessorOptions(PPOpts, Complain,
115 SuggestedPredefines) ||
116 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
117}
118void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
119 unsigned Value) {
120 First->ReadCounter(M, Value);
121 Second->ReadCounter(M, Value);
122}
123bool ChainedASTReaderListener::needsInputFileVisitation() {
124 return First->needsInputFileVisitation() ||
125 Second->needsInputFileVisitation();
126}
127bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
128 return First->needsSystemInputFileVisitation() ||
129 Second->needsSystemInputFileVisitation();
130}
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000131void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
132 First->visitModuleFile(Filename);
133 Second->visitModuleFile(Filename);
134}
Ben Langmuircb69b572014-03-07 06:40:32 +0000135bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000136 bool isSystem,
137 bool isOverridden) {
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
331static DiagnosticsEngine::ExtensionHandling
332isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
333 DiagnosticsEngine::ExtensionHandling Ext =
334 Diags.getExtensionHandlingBehavior();
335 if (Ext == DiagnosticsEngine::Ext_Warn && Diags.getWarningsAsErrors())
336 Ext = DiagnosticsEngine::Ext_Error;
337 return Ext;
338}
339
340static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
341 DiagnosticsEngine &Diags,
342 bool IsSystem, bool Complain) {
343 // Top-level options
344 if (IsSystem) {
345 if (Diags.getSuppressSystemWarnings())
346 return false;
347 // If -Wsystem-headers was not enabled before, be conservative
348 if (StoredDiags.getSuppressSystemWarnings()) {
349 if (Complain)
350 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
351 return true;
352 }
353 }
354
355 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
356 if (Complain)
357 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
358 return true;
359 }
360
361 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
362 !StoredDiags.getEnableAllWarnings()) {
363 if (Complain)
364 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
365 return true;
366 }
367
368 if (isExtHandlingFromDiagsError(Diags) &&
369 !isExtHandlingFromDiagsError(StoredDiags)) {
370 if (Complain)
371 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
372 return true;
373 }
374
375 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
376}
377
378bool PCHValidator::ReadDiagnosticOptions(
379 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
380 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
381 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
382 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
383 new DiagnosticsEngine(DiagIDs, DiagOpts.getPtr()));
384 // This should never fail, because we would have processed these options
385 // before writing them to an ASTFile.
386 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
387
388 ModuleManager &ModuleMgr = Reader.getModuleManager();
389 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
390
391 // If the original import came from a file explicitly generated by the user,
392 // don't check the diagnostic mappings.
393 // FIXME: currently this is approximated by checking whether this is not a
394 // module import.
395 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
396 // the transitive closure of its imports, since unrelated modules cannot be
397 // imported until after this module finishes validation.
398 ModuleFile *TopImport = *ModuleMgr.rbegin();
399 while (!TopImport->ImportedBy.empty())
400 TopImport = TopImport->ImportedBy[0];
401 if (TopImport->Kind != MK_Module)
402 return false;
403
404 StringRef ModuleName = TopImport->ModuleName;
405 assert(!ModuleName.empty() && "diagnostic options read before module name");
406
407 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
408 assert(M && "missing module");
409
410 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
411 // contains the union of their flags.
412 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
413}
414
Guy Benyei11169dd2012-12-18 14:30:41 +0000415/// \brief Collect the macro definitions provided by the given preprocessor
416/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000417static void
418collectMacroDefinitions(const PreprocessorOptions &PPOpts,
419 MacroDefinitionsMap &Macros,
420 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000421 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
422 StringRef Macro = PPOpts.Macros[I].first;
423 bool IsUndef = PPOpts.Macros[I].second;
424
425 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
426 StringRef MacroName = MacroPair.first;
427 StringRef MacroBody = MacroPair.second;
428
429 // For an #undef'd macro, we only care about the name.
430 if (IsUndef) {
431 if (MacroNames && !Macros.count(MacroName))
432 MacroNames->push_back(MacroName);
433
434 Macros[MacroName] = std::make_pair("", true);
435 continue;
436 }
437
438 // For a #define'd macro, figure out the actual definition.
439 if (MacroName.size() == Macro.size())
440 MacroBody = "1";
441 else {
442 // Note: GCC drops anything following an end-of-line character.
443 StringRef::size_type End = MacroBody.find_first_of("\n\r");
444 MacroBody = MacroBody.substr(0, End);
445 }
446
447 if (MacroNames && !Macros.count(MacroName))
448 MacroNames->push_back(MacroName);
449 Macros[MacroName] = std::make_pair(MacroBody, false);
450 }
451}
452
453/// \brief Check the preprocessor options deserialized from the control block
454/// against the preprocessor options in an existing preprocessor.
455///
456/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
457static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
458 const PreprocessorOptions &ExistingPPOpts,
459 DiagnosticsEngine *Diags,
460 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000461 std::string &SuggestedPredefines,
462 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000463 // Check macro definitions.
464 MacroDefinitionsMap ASTFileMacros;
465 collectMacroDefinitions(PPOpts, ASTFileMacros);
466 MacroDefinitionsMap ExistingMacros;
467 SmallVector<StringRef, 4> ExistingMacroNames;
468 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
469
470 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
471 // Dig out the macro definition in the existing preprocessor options.
472 StringRef MacroName = ExistingMacroNames[I];
473 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
474
475 // Check whether we know anything about this macro name or not.
476 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
477 = ASTFileMacros.find(MacroName);
478 if (Known == ASTFileMacros.end()) {
479 // FIXME: Check whether this identifier was referenced anywhere in the
480 // AST file. If so, we should reject the AST file. Unfortunately, this
481 // information isn't in the control block. What shall we do about it?
482
483 if (Existing.second) {
484 SuggestedPredefines += "#undef ";
485 SuggestedPredefines += MacroName.str();
486 SuggestedPredefines += '\n';
487 } else {
488 SuggestedPredefines += "#define ";
489 SuggestedPredefines += MacroName.str();
490 SuggestedPredefines += ' ';
491 SuggestedPredefines += Existing.first.str();
492 SuggestedPredefines += '\n';
493 }
494 continue;
495 }
496
497 // If the macro was defined in one but undef'd in the other, we have a
498 // conflict.
499 if (Existing.second != Known->second.second) {
500 if (Diags) {
501 Diags->Report(diag::err_pch_macro_def_undef)
502 << MacroName << Known->second.second;
503 }
504 return true;
505 }
506
507 // If the macro was #undef'd in both, or if the macro bodies are identical,
508 // it's fine.
509 if (Existing.second || Existing.first == Known->second.first)
510 continue;
511
512 // The macro bodies differ; complain.
513 if (Diags) {
514 Diags->Report(diag::err_pch_macro_def_conflict)
515 << MacroName << Known->second.first << Existing.first;
516 }
517 return true;
518 }
519
520 // Check whether we're using predefines.
521 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
522 if (Diags) {
523 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
524 }
525 return true;
526 }
527
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000528 // Detailed record is important since it is used for the module cache hash.
529 if (LangOpts.Modules &&
530 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
531 if (Diags) {
532 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
533 }
534 return true;
535 }
536
Guy Benyei11169dd2012-12-18 14:30:41 +0000537 // Compute the #include and #include_macros lines we need.
538 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
539 StringRef File = ExistingPPOpts.Includes[I];
540 if (File == ExistingPPOpts.ImplicitPCHInclude)
541 continue;
542
543 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
544 != PPOpts.Includes.end())
545 continue;
546
547 SuggestedPredefines += "#include \"";
548 SuggestedPredefines +=
549 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
550 SuggestedPredefines += "\"\n";
551 }
552
553 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
554 StringRef File = ExistingPPOpts.MacroIncludes[I];
555 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
556 File)
557 != PPOpts.MacroIncludes.end())
558 continue;
559
560 SuggestedPredefines += "#__include_macros \"";
561 SuggestedPredefines +=
562 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
563 SuggestedPredefines += "\"\n##\n";
564 }
565
566 return false;
567}
568
569bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
570 bool Complain,
571 std::string &SuggestedPredefines) {
572 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
573
574 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000575 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000576 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000577 SuggestedPredefines,
578 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000579}
580
Guy Benyei11169dd2012-12-18 14:30:41 +0000581void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
582 PP.setCounterValue(Value);
583}
584
585//===----------------------------------------------------------------------===//
586// AST reader implementation
587//===----------------------------------------------------------------------===//
588
Nico Weber824285e2014-05-08 04:26:47 +0000589void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
590 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000591 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000592 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000593}
594
595
596
597unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
598 return serialization::ComputeHash(Sel);
599}
600
601
602std::pair<unsigned, unsigned>
603ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000604 using namespace llvm::support;
605 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
606 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000607 return std::make_pair(KeyLen, DataLen);
608}
609
610ASTSelectorLookupTrait::internal_key_type
611ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000612 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000613 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000614 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
615 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
616 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000617 if (N == 0)
618 return SelTable.getNullarySelector(FirstII);
619 else if (N == 1)
620 return SelTable.getUnarySelector(FirstII);
621
622 SmallVector<IdentifierInfo *, 16> Args;
623 Args.push_back(FirstII);
624 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000625 Args.push_back(Reader.getLocalIdentifier(
626 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000627
628 return SelTable.getSelector(N, Args.data());
629}
630
631ASTSelectorLookupTrait::data_type
632ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
633 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000634 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000635
636 data_type Result;
637
Justin Bogner57ba0b22014-03-28 22:03:24 +0000638 Result.ID = Reader.getGlobalSelectorID(
639 F, endian::readNext<uint32_t, little, unaligned>(d));
640 unsigned NumInstanceMethodsAndBits =
641 endian::readNext<uint16_t, little, unaligned>(d);
642 unsigned NumFactoryMethodsAndBits =
643 endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +0000644 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
645 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
646 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
647 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
Guy Benyei11169dd2012-12-18 14:30:41 +0000648
649 // Load instance methods
650 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000651 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
652 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000653 Result.Instance.push_back(Method);
654 }
655
656 // Load factory methods
657 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000658 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
659 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000660 Result.Factory.push_back(Method);
661 }
662
663 return Result;
664}
665
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000666unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
667 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000668}
669
670std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000671ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000672 using namespace llvm::support;
673 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
674 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000675 return std::make_pair(KeyLen, DataLen);
676}
677
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000678ASTIdentifierLookupTraitBase::internal_key_type
679ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000680 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000681 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000682}
683
Douglas Gregordcf25082013-02-11 18:16:18 +0000684/// \brief Whether the given identifier is "interesting".
685static bool isInterestingIdentifier(IdentifierInfo &II) {
686 return II.isPoisoned() ||
687 II.isExtensionToken() ||
688 II.getObjCOrBuiltinID() ||
689 II.hasRevertedTokenIDToIdentifier() ||
690 II.hadMacroDefinition() ||
691 II.getFETokenInfo<void>();
692}
693
Guy Benyei11169dd2012-12-18 14:30:41 +0000694IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
695 const unsigned char* d,
696 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000697 using namespace llvm::support;
698 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000699 bool IsInteresting = RawID & 0x01;
700
701 // Wipe out the "is interesting" bit.
702 RawID = RawID >> 1;
703
704 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
705 if (!IsInteresting) {
706 // For uninteresting identifiers, just build the IdentifierInfo
707 // and associate it with the persistent ID.
708 IdentifierInfo *II = KnownII;
709 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000710 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000711 KnownII = II;
712 }
713 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000714 if (!II->isFromAST()) {
715 bool WasInteresting = isInterestingIdentifier(*II);
716 II->setIsFromAST();
717 if (WasInteresting)
718 II->setChangedSinceDeserialization();
719 }
720 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000721 return II;
722 }
723
Justin Bogner57ba0b22014-03-28 22:03:24 +0000724 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
725 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000726 bool CPlusPlusOperatorKeyword = Bits & 0x01;
727 Bits >>= 1;
728 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
729 Bits >>= 1;
730 bool Poisoned = Bits & 0x01;
731 Bits >>= 1;
732 bool ExtensionToken = Bits & 0x01;
733 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000734 bool hasSubmoduleMacros = Bits & 0x01;
735 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000736 bool hadMacroDefinition = Bits & 0x01;
737 Bits >>= 1;
738
739 assert(Bits == 0 && "Extra bits in the identifier?");
740 DataLen -= 8;
741
742 // Build the IdentifierInfo itself and link the identifier ID with
743 // the new IdentifierInfo.
744 IdentifierInfo *II = KnownII;
745 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000746 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000747 KnownII = II;
748 }
749 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000750 if (!II->isFromAST()) {
751 bool WasInteresting = isInterestingIdentifier(*II);
752 II->setIsFromAST();
753 if (WasInteresting)
754 II->setChangedSinceDeserialization();
755 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000756
757 // Set or check the various bits in the IdentifierInfo structure.
758 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000759 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000760 II->RevertTokenIDToIdentifier();
761 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
762 assert(II->isExtensionToken() == ExtensionToken &&
763 "Incorrect extension token flag");
764 (void)ExtensionToken;
765 if (Poisoned)
766 II->setIsPoisoned(true);
767 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
768 "Incorrect C++ operator keyword flag");
769 (void)CPlusPlusOperatorKeyword;
770
771 // If this identifier is a macro, deserialize the macro
772 // definition.
773 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000774 uint32_t MacroDirectivesOffset =
775 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000776 DataLen -= 4;
777 SmallVector<uint32_t, 8> LocalMacroIDs;
778 if (hasSubmoduleMacros) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000779 while (uint32_t LocalMacroID =
780 endian::readNext<uint32_t, little, unaligned>(d)) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000781 DataLen -= 4;
782 LocalMacroIDs.push_back(LocalMacroID);
783 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000784 DataLen -= 4;
785 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000786
787 if (F.Kind == MK_Module) {
Richard Smith49f906a2014-03-01 00:08:04 +0000788 // Macro definitions are stored from newest to oldest, so reverse them
789 // before registering them.
790 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000791 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000792 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
793 unsigned Size = 1;
794
795 static const uint32_t HasOverridesFlag = 0x80000000U;
796 if (I + 1 != E && (I[1] & HasOverridesFlag))
797 Size += 1 + (I[1] & ~HasOverridesFlag);
798
799 MacroSizes.push_back(Size);
800 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000801 }
Richard Smith49f906a2014-03-01 00:08:04 +0000802
803 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
804 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
805 SE = MacroSizes.rend();
806 SI != SE; ++SI) {
807 I -= *SI;
808
809 uint32_t LocalMacroID = *I;
810 llvm::ArrayRef<uint32_t> Overrides;
811 if (*SI != 1)
812 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
813 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
814 }
815 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000816 } else {
817 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
818 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000819 }
820
821 Reader.SetIdentifierInfo(ID, II);
822
823 // Read all of the declarations visible at global scope with this
824 // name.
825 if (DataLen > 0) {
826 SmallVector<uint32_t, 4> DeclIDs;
827 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000828 DeclIDs.push_back(Reader.getGlobalDeclID(
829 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000830 Reader.SetGloballyVisibleDecls(II, DeclIDs);
831 }
832
833 return II;
834}
835
836unsigned
837ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
838 llvm::FoldingSetNodeID ID;
839 ID.AddInteger(Key.Kind);
840
841 switch (Key.Kind) {
842 case DeclarationName::Identifier:
843 case DeclarationName::CXXLiteralOperatorName:
844 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
845 break;
846 case DeclarationName::ObjCZeroArgSelector:
847 case DeclarationName::ObjCOneArgSelector:
848 case DeclarationName::ObjCMultiArgSelector:
849 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
850 break;
851 case DeclarationName::CXXOperatorName:
852 ID.AddInteger((OverloadedOperatorKind)Key.Data);
853 break;
854 case DeclarationName::CXXConstructorName:
855 case DeclarationName::CXXDestructorName:
856 case DeclarationName::CXXConversionFunctionName:
857 case DeclarationName::CXXUsingDirective:
858 break;
859 }
860
861 return ID.ComputeHash();
862}
863
864ASTDeclContextNameLookupTrait::internal_key_type
865ASTDeclContextNameLookupTrait::GetInternalKey(
866 const external_key_type& Name) const {
867 DeclNameKey Key;
868 Key.Kind = Name.getNameKind();
869 switch (Name.getNameKind()) {
870 case DeclarationName::Identifier:
871 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
872 break;
873 case DeclarationName::ObjCZeroArgSelector:
874 case DeclarationName::ObjCOneArgSelector:
875 case DeclarationName::ObjCMultiArgSelector:
876 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
877 break;
878 case DeclarationName::CXXOperatorName:
879 Key.Data = Name.getCXXOverloadedOperator();
880 break;
881 case DeclarationName::CXXLiteralOperatorName:
882 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
883 break;
884 case DeclarationName::CXXConstructorName:
885 case DeclarationName::CXXDestructorName:
886 case DeclarationName::CXXConversionFunctionName:
887 case DeclarationName::CXXUsingDirective:
888 Key.Data = 0;
889 break;
890 }
891
892 return Key;
893}
894
895std::pair<unsigned, unsigned>
896ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000897 using namespace llvm::support;
898 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
899 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000900 return std::make_pair(KeyLen, DataLen);
901}
902
903ASTDeclContextNameLookupTrait::internal_key_type
904ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000905 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000906
907 DeclNameKey Key;
908 Key.Kind = (DeclarationName::NameKind)*d++;
909 switch (Key.Kind) {
910 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000911 Key.Data = (uint64_t)Reader.getLocalIdentifier(
912 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000913 break;
914 case DeclarationName::ObjCZeroArgSelector:
915 case DeclarationName::ObjCOneArgSelector:
916 case DeclarationName::ObjCMultiArgSelector:
917 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000918 (uint64_t)Reader.getLocalSelector(
919 F, endian::readNext<uint32_t, little, unaligned>(
920 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000921 break;
922 case DeclarationName::CXXOperatorName:
923 Key.Data = *d++; // OverloadedOperatorKind
924 break;
925 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000926 Key.Data = (uint64_t)Reader.getLocalIdentifier(
927 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000928 break;
929 case DeclarationName::CXXConstructorName:
930 case DeclarationName::CXXDestructorName:
931 case DeclarationName::CXXConversionFunctionName:
932 case DeclarationName::CXXUsingDirective:
933 Key.Data = 0;
934 break;
935 }
936
937 return Key;
938}
939
940ASTDeclContextNameLookupTrait::data_type
941ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
942 const unsigned char* d,
943 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000944 using namespace llvm::support;
945 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000946 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
947 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000948 return std::make_pair(Start, Start + NumDecls);
949}
950
951bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000952 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000953 const std::pair<uint64_t, uint64_t> &Offsets,
954 DeclContextInfo &Info) {
955 SavedStreamPosition SavedPosition(Cursor);
956 // First the lexical decls.
957 if (Offsets.first != 0) {
958 Cursor.JumpToBit(Offsets.first);
959
960 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000961 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000962 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000963 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000964 if (RecCode != DECL_CONTEXT_LEXICAL) {
965 Error("Expected lexical block");
966 return true;
967 }
968
Chris Lattner0e6c9402013-01-20 02:38:54 +0000969 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
970 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000971 }
972
973 // Now the lookup table.
974 if (Offsets.second != 0) {
975 Cursor.JumpToBit(Offsets.second);
976
977 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000978 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000979 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000980 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000981 if (RecCode != DECL_CONTEXT_VISIBLE) {
982 Error("Expected visible lookup table block");
983 return true;
984 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000985 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
986 (const unsigned char *)Blob.data() + Record[0],
987 (const unsigned char *)Blob.data() + sizeof(uint32_t),
988 (const unsigned char *)Blob.data(),
989 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +0000990 }
991
992 return false;
993}
994
995void ASTReader::Error(StringRef Msg) {
996 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +0000997 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
998 Diag(diag::note_module_cache_path)
999 << PP.getHeaderSearchInfo().getModuleCachePath();
1000 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001001}
1002
1003void ASTReader::Error(unsigned DiagID,
1004 StringRef Arg1, StringRef Arg2) {
1005 if (Diags.isDiagnosticInFlight())
1006 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1007 else
1008 Diag(DiagID) << Arg1 << Arg2;
1009}
1010
1011//===----------------------------------------------------------------------===//
1012// Source Manager Deserialization
1013//===----------------------------------------------------------------------===//
1014
1015/// \brief Read the line table in the source manager block.
1016/// \returns true if there was an error.
1017bool ASTReader::ParseLineTable(ModuleFile &F,
1018 SmallVectorImpl<uint64_t> &Record) {
1019 unsigned Idx = 0;
1020 LineTableInfo &LineTable = SourceMgr.getLineTable();
1021
1022 // Parse the file names
1023 std::map<int, int> FileIDs;
1024 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1025 // Extract the file name
1026 unsigned FilenameLen = Record[Idx++];
1027 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
1028 Idx += FilenameLen;
1029 MaybeAddSystemRootToFilename(F, Filename);
1030 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1031 }
1032
1033 // Parse the line entries
1034 std::vector<LineEntry> Entries;
1035 while (Idx < Record.size()) {
1036 int FID = Record[Idx++];
1037 assert(FID >= 0 && "Serialized line entries for non-local file.");
1038 // Remap FileID from 1-based old view.
1039 FID += F.SLocEntryBaseID - 1;
1040
1041 // Extract the line entries
1042 unsigned NumEntries = Record[Idx++];
1043 assert(NumEntries && "Numentries is 00000");
1044 Entries.clear();
1045 Entries.reserve(NumEntries);
1046 for (unsigned I = 0; I != NumEntries; ++I) {
1047 unsigned FileOffset = Record[Idx++];
1048 unsigned LineNo = Record[Idx++];
1049 int FilenameID = FileIDs[Record[Idx++]];
1050 SrcMgr::CharacteristicKind FileKind
1051 = (SrcMgr::CharacteristicKind)Record[Idx++];
1052 unsigned IncludeOffset = Record[Idx++];
1053 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1054 FileKind, IncludeOffset));
1055 }
1056 LineTable.AddEntry(FileID::get(FID), Entries);
1057 }
1058
1059 return false;
1060}
1061
1062/// \brief Read a source manager block
1063bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1064 using namespace SrcMgr;
1065
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001066 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001067
1068 // Set the source-location entry cursor to the current position in
1069 // the stream. This cursor will be used to read the contents of the
1070 // source manager block initially, and then lazily read
1071 // source-location entries as needed.
1072 SLocEntryCursor = F.Stream;
1073
1074 // The stream itself is going to skip over the source manager block.
1075 if (F.Stream.SkipBlock()) {
1076 Error("malformed block record in AST file");
1077 return true;
1078 }
1079
1080 // Enter the source manager block.
1081 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1082 Error("malformed source manager block record in AST file");
1083 return true;
1084 }
1085
1086 RecordData Record;
1087 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001088 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1089
1090 switch (E.Kind) {
1091 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1092 case llvm::BitstreamEntry::Error:
1093 Error("malformed block record in AST file");
1094 return true;
1095 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001096 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001097 case llvm::BitstreamEntry::Record:
1098 // The interesting case.
1099 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001100 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001101
Guy Benyei11169dd2012-12-18 14:30:41 +00001102 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001103 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001104 StringRef Blob;
1105 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001106 default: // Default behavior: ignore.
1107 break;
1108
1109 case SM_SLOC_FILE_ENTRY:
1110 case SM_SLOC_BUFFER_ENTRY:
1111 case SM_SLOC_EXPANSION_ENTRY:
1112 // Once we hit one of the source location entries, we're done.
1113 return false;
1114 }
1115 }
1116}
1117
1118/// \brief If a header file is not found at the path that we expect it to be
1119/// and the PCH file was moved from its original location, try to resolve the
1120/// file by assuming that header+PCH were moved together and the header is in
1121/// the same place relative to the PCH.
1122static std::string
1123resolveFileRelativeToOriginalDir(const std::string &Filename,
1124 const std::string &OriginalDir,
1125 const std::string &CurrDir) {
1126 assert(OriginalDir != CurrDir &&
1127 "No point trying to resolve the file if the PCH dir didn't change");
1128 using namespace llvm::sys;
1129 SmallString<128> filePath(Filename);
1130 fs::make_absolute(filePath);
1131 assert(path::is_absolute(OriginalDir));
1132 SmallString<128> currPCHPath(CurrDir);
1133
1134 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1135 fileDirE = path::end(path::parent_path(filePath));
1136 path::const_iterator origDirI = path::begin(OriginalDir),
1137 origDirE = path::end(OriginalDir);
1138 // Skip the common path components from filePath and OriginalDir.
1139 while (fileDirI != fileDirE && origDirI != origDirE &&
1140 *fileDirI == *origDirI) {
1141 ++fileDirI;
1142 ++origDirI;
1143 }
1144 for (; origDirI != origDirE; ++origDirI)
1145 path::append(currPCHPath, "..");
1146 path::append(currPCHPath, fileDirI, fileDirE);
1147 path::append(currPCHPath, path::filename(Filename));
1148 return currPCHPath.str();
1149}
1150
1151bool ASTReader::ReadSLocEntry(int ID) {
1152 if (ID == 0)
1153 return false;
1154
1155 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1156 Error("source location entry ID out-of-range for AST file");
1157 return true;
1158 }
1159
1160 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1161 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001162 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001163 unsigned BaseOffset = F->SLocEntryBaseOffset;
1164
1165 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001166 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1167 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001168 Error("incorrectly-formatted source location entry in AST file");
1169 return true;
1170 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001171
Guy Benyei11169dd2012-12-18 14:30:41 +00001172 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001173 StringRef Blob;
1174 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001175 default:
1176 Error("incorrectly-formatted source location entry in AST file");
1177 return true;
1178
1179 case SM_SLOC_FILE_ENTRY: {
1180 // We will detect whether a file changed and return 'Failure' for it, but
1181 // we will also try to fail gracefully by setting up the SLocEntry.
1182 unsigned InputID = Record[4];
1183 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001184 const FileEntry *File = IF.getFile();
1185 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001186
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001187 // Note that we only check if a File was returned. If it was out-of-date
1188 // we have complained but we will continue creating a FileID to recover
1189 // gracefully.
1190 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001191 return true;
1192
1193 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1194 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1195 // This is the module's main file.
1196 IncludeLoc = getImportLocation(F);
1197 }
1198 SrcMgr::CharacteristicKind
1199 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1200 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1201 ID, BaseOffset + Record[0]);
1202 SrcMgr::FileInfo &FileInfo =
1203 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1204 FileInfo.NumCreatedFIDs = Record[5];
1205 if (Record[3])
1206 FileInfo.setHasLineDirectives();
1207
1208 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1209 unsigned NumFileDecls = Record[7];
1210 if (NumFileDecls) {
1211 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1212 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1213 NumFileDecls));
1214 }
1215
1216 const SrcMgr::ContentCache *ContentCache
1217 = SourceMgr.getOrCreateContentCache(File,
1218 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1219 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1220 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1221 unsigned Code = SLocEntryCursor.ReadCode();
1222 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001223 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001224
1225 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1226 Error("AST record has invalid code");
1227 return true;
1228 }
1229
1230 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001231 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00001232 SourceMgr.overrideFileContents(File, Buffer);
1233 }
1234
1235 break;
1236 }
1237
1238 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001239 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001240 unsigned Offset = Record[0];
1241 SrcMgr::CharacteristicKind
1242 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1243 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1244 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
1245 IncludeLoc = getImportLocation(F);
1246 }
1247 unsigned Code = SLocEntryCursor.ReadCode();
1248 Record.clear();
1249 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001250 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001251
1252 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1253 Error("AST record has invalid code");
1254 return true;
1255 }
1256
1257 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001258 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
Alp Toker6ac2cd02014-05-16 17:23:01 +00001259 SourceMgr.createFileID(Buffer, FileCharacter, ID, BaseOffset + Offset,
1260 IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001261 break;
1262 }
1263
1264 case SM_SLOC_EXPANSION_ENTRY: {
1265 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1266 SourceMgr.createExpansionLoc(SpellingLoc,
1267 ReadSourceLocation(*F, Record[2]),
1268 ReadSourceLocation(*F, Record[3]),
1269 Record[4],
1270 ID,
1271 BaseOffset + Record[0]);
1272 break;
1273 }
1274 }
1275
1276 return false;
1277}
1278
1279std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1280 if (ID == 0)
1281 return std::make_pair(SourceLocation(), "");
1282
1283 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1284 Error("source location entry ID out-of-range for AST file");
1285 return std::make_pair(SourceLocation(), "");
1286 }
1287
1288 // Find which module file this entry lands in.
1289 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1290 if (M->Kind != MK_Module)
1291 return std::make_pair(SourceLocation(), "");
1292
1293 // FIXME: Can we map this down to a particular submodule? That would be
1294 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001295 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001296}
1297
1298/// \brief Find the location where the module F is imported.
1299SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1300 if (F->ImportLoc.isValid())
1301 return F->ImportLoc;
1302
1303 // Otherwise we have a PCH. It's considered to be "imported" at the first
1304 // location of its includer.
1305 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001306 // Main file is the importer.
1307 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1308 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001309 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001310 return F->ImportedBy[0]->FirstLoc;
1311}
1312
1313/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1314/// specified cursor. Read the abbreviations that are at the top of the block
1315/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001316bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001317 if (Cursor.EnterSubBlock(BlockID)) {
1318 Error("malformed block record in AST file");
1319 return Failure;
1320 }
1321
1322 while (true) {
1323 uint64_t Offset = Cursor.GetCurrentBitNo();
1324 unsigned Code = Cursor.ReadCode();
1325
1326 // We expect all abbrevs to be at the start of the block.
1327 if (Code != llvm::bitc::DEFINE_ABBREV) {
1328 Cursor.JumpToBit(Offset);
1329 return false;
1330 }
1331 Cursor.ReadAbbrevRecord();
1332 }
1333}
1334
Richard Smithe40f2ba2013-08-07 21:41:30 +00001335Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001336 unsigned &Idx) {
1337 Token Tok;
1338 Tok.startToken();
1339 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1340 Tok.setLength(Record[Idx++]);
1341 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1342 Tok.setIdentifierInfo(II);
1343 Tok.setKind((tok::TokenKind)Record[Idx++]);
1344 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1345 return Tok;
1346}
1347
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001348MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001349 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001350
1351 // Keep track of where we are in the stream, then jump back there
1352 // after reading this macro.
1353 SavedStreamPosition SavedPosition(Stream);
1354
1355 Stream.JumpToBit(Offset);
1356 RecordData Record;
1357 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001358 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001359
Guy Benyei11169dd2012-12-18 14:30:41 +00001360 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001361 // Advance to the next record, but if we get to the end of the block, don't
1362 // pop it (removing all the abbreviations from the cursor) since we want to
1363 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001364 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001365 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1366
1367 switch (Entry.Kind) {
1368 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1369 case llvm::BitstreamEntry::Error:
1370 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001371 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001372 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001373 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001374 case llvm::BitstreamEntry::Record:
1375 // The interesting case.
1376 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001377 }
1378
1379 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001380 Record.clear();
1381 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001382 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001383 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001384 case PP_MACRO_DIRECTIVE_HISTORY:
1385 return Macro;
1386
Guy Benyei11169dd2012-12-18 14:30:41 +00001387 case PP_MACRO_OBJECT_LIKE:
1388 case PP_MACRO_FUNCTION_LIKE: {
1389 // If we already have a macro, that means that we've hit the end
1390 // of the definition of the macro we were looking for. We're
1391 // done.
1392 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001393 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001394
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001395 unsigned NextIndex = 1; // Skip identifier ID.
1396 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001397 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001398 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001399 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001400 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001401 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001402
Guy Benyei11169dd2012-12-18 14:30:41 +00001403 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1404 // Decode function-like macro info.
1405 bool isC99VarArgs = Record[NextIndex++];
1406 bool isGNUVarArgs = Record[NextIndex++];
1407 bool hasCommaPasting = Record[NextIndex++];
1408 MacroArgs.clear();
1409 unsigned NumArgs = Record[NextIndex++];
1410 for (unsigned i = 0; i != NumArgs; ++i)
1411 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1412
1413 // Install function-like macro info.
1414 MI->setIsFunctionLike();
1415 if (isC99VarArgs) MI->setIsC99Varargs();
1416 if (isGNUVarArgs) MI->setIsGNUVarargs();
1417 if (hasCommaPasting) MI->setHasCommaPasting();
1418 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1419 PP.getPreprocessorAllocator());
1420 }
1421
Guy Benyei11169dd2012-12-18 14:30:41 +00001422 // Remember that we saw this macro last so that we add the tokens that
1423 // form its body to it.
1424 Macro = MI;
1425
1426 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1427 Record[NextIndex]) {
1428 // We have a macro definition. Register the association
1429 PreprocessedEntityID
1430 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1431 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001432 PreprocessingRecord::PPEntityID
1433 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1434 MacroDefinition *PPDef =
1435 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1436 if (PPDef)
1437 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001438 }
1439
1440 ++NumMacrosRead;
1441 break;
1442 }
1443
1444 case PP_TOKEN: {
1445 // If we see a TOKEN before a PP_MACRO_*, then the file is
1446 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001447 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001448
John McCallf413f5e2013-05-03 00:10:13 +00001449 unsigned Idx = 0;
1450 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001451 Macro->AddTokenToBody(Tok);
1452 break;
1453 }
1454 }
1455 }
1456}
1457
1458PreprocessedEntityID
1459ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1460 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1461 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1462 assert(I != M.PreprocessedEntityRemap.end()
1463 && "Invalid index into preprocessed entity index remap");
1464
1465 return LocalID + I->second;
1466}
1467
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001468unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1469 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001470}
1471
1472HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001473HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1474 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1475 FE->getName() };
1476 return ikey;
1477}
Guy Benyei11169dd2012-12-18 14:30:41 +00001478
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001479bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1480 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001481 return false;
1482
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001483 if (strcmp(a.Filename, b.Filename) == 0)
1484 return true;
1485
Guy Benyei11169dd2012-12-18 14:30:41 +00001486 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001487 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001488 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1489 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001490 return (FEA && FEA == FEB);
Guy Benyei11169dd2012-12-18 14:30:41 +00001491}
1492
1493std::pair<unsigned, unsigned>
1494HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001495 using namespace llvm::support;
1496 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001497 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001498 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001499}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001500
1501HeaderFileInfoTrait::internal_key_type
1502HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001503 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001504 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001505 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1506 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001507 ikey.Filename = (const char *)d;
1508 return ikey;
1509}
1510
Guy Benyei11169dd2012-12-18 14:30:41 +00001511HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001512HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001513 unsigned DataLen) {
1514 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001515 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001516 HeaderFileInfo HFI;
1517 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001518 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1519 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001520 HFI.isImport = (Flags >> 5) & 0x01;
1521 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1522 HFI.DirInfo = (Flags >> 2) & 0x03;
1523 HFI.Resolved = (Flags >> 1) & 0x01;
1524 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001525 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1526 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1527 M, endian::readNext<uint32_t, little, unaligned>(d));
1528 if (unsigned FrameworkOffset =
1529 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001530 // The framework offset is 1 greater than the actual offset,
1531 // since 0 is used as an indicator for "no framework name".
1532 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1533 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1534 }
1535
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001536 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001537 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001538 if (LocalSMID) {
1539 // This header is part of a module. Associate it with the module to enable
1540 // implicit module import.
1541 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1542 Module *Mod = Reader.getSubmodule(GlobalSMID);
1543 HFI.isModuleHeader = true;
1544 FileManager &FileMgr = Reader.getFileManager();
1545 ModuleMap &ModMap =
1546 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001547 ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001548 }
1549 }
1550
Guy Benyei11169dd2012-12-18 14:30:41 +00001551 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1552 (void)End;
1553
1554 // This HeaderFileInfo was externally loaded.
1555 HFI.External = true;
1556 return HFI;
1557}
1558
Richard Smith49f906a2014-03-01 00:08:04 +00001559void
1560ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1561 GlobalMacroID GMacID,
1562 llvm::ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001563 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Craig Toppera13603a2014-05-22 05:54:18 +00001564 SubmoduleID *OverrideData = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001565 if (!Overrides.empty()) {
1566 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1567 OverrideData[0] = Overrides.size();
1568 for (unsigned I = 0; I != Overrides.size(); ++I)
1569 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1570 }
1571 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001572}
1573
1574void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1575 ModuleFile *M,
1576 uint64_t MacroDirectivesOffset) {
1577 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1578 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001579}
1580
1581void ASTReader::ReadDefinedMacros() {
1582 // Note that we are loading defined macros.
1583 Deserializing Macros(this);
1584
1585 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1586 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001587 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001588
1589 // If there was no preprocessor block, skip this file.
1590 if (!MacroCursor.getBitStreamReader())
1591 continue;
1592
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001593 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001594 Cursor.JumpToBit((*I)->MacroStartOffset);
1595
1596 RecordData Record;
1597 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001598 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1599
1600 switch (E.Kind) {
1601 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1602 case llvm::BitstreamEntry::Error:
1603 Error("malformed block record in AST file");
1604 return;
1605 case llvm::BitstreamEntry::EndBlock:
1606 goto NextCursor;
1607
1608 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001609 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001610 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001611 default: // Default behavior: ignore.
1612 break;
1613
1614 case PP_MACRO_OBJECT_LIKE:
1615 case PP_MACRO_FUNCTION_LIKE:
1616 getLocalIdentifier(**I, Record[0]);
1617 break;
1618
1619 case PP_TOKEN:
1620 // Ignore tokens.
1621 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001622 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001623 break;
1624 }
1625 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001626 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001627 }
1628}
1629
1630namespace {
1631 /// \brief Visitor class used to look up identifirs in an AST file.
1632 class IdentifierLookupVisitor {
1633 StringRef Name;
1634 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001635 unsigned &NumIdentifierLookups;
1636 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001637 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001638
Guy Benyei11169dd2012-12-18 14:30:41 +00001639 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001640 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1641 unsigned &NumIdentifierLookups,
1642 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001643 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001644 NumIdentifierLookups(NumIdentifierLookups),
1645 NumIdentifierLookupHits(NumIdentifierLookupHits),
1646 Found()
1647 {
1648 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001649
1650 static bool visit(ModuleFile &M, void *UserData) {
1651 IdentifierLookupVisitor *This
1652 = static_cast<IdentifierLookupVisitor *>(UserData);
1653
1654 // If we've already searched this module file, skip it now.
1655 if (M.Generation <= This->PriorGeneration)
1656 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001657
Guy Benyei11169dd2012-12-18 14:30:41 +00001658 ASTIdentifierLookupTable *IdTable
1659 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1660 if (!IdTable)
1661 return false;
1662
1663 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1664 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001665 ++This->NumIdentifierLookups;
1666 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001667 if (Pos == IdTable->end())
1668 return false;
1669
1670 // Dereferencing the iterator has the effect of building the
1671 // IdentifierInfo node and populating it with the various
1672 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001673 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001674 This->Found = *Pos;
1675 return true;
1676 }
1677
1678 // \brief Retrieve the identifier info found within the module
1679 // files.
1680 IdentifierInfo *getIdentifierInfo() const { return Found; }
1681 };
1682}
1683
1684void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1685 // Note that we are loading an identifier.
1686 Deserializing AnIdentifier(this);
1687
1688 unsigned PriorGeneration = 0;
1689 if (getContext().getLangOpts().Modules)
1690 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001691
1692 // If there is a global index, look there first to determine which modules
1693 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001694 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001695 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001696 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001697 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1698 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001699 }
1700 }
1701
Douglas Gregor7211ac12013-01-25 23:32:03 +00001702 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001703 NumIdentifierLookups,
1704 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001705 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001706 markIdentifierUpToDate(&II);
1707}
1708
1709void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1710 if (!II)
1711 return;
1712
1713 II->setOutOfDate(false);
1714
1715 // Update the generation for this identifier.
1716 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001717 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001718}
1719
Richard Smith49f906a2014-03-01 00:08:04 +00001720struct ASTReader::ModuleMacroInfo {
1721 SubmoduleID SubModID;
1722 MacroInfo *MI;
1723 SubmoduleID *Overrides;
1724 // FIXME: Remove this.
1725 ModuleFile *F;
1726
1727 bool isDefine() const { return MI; }
1728
1729 SubmoduleID getSubmoduleID() const { return SubModID; }
1730
1731 llvm::ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
1732 if (!Overrides)
1733 return llvm::ArrayRef<SubmoduleID>();
1734 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1735 }
1736
1737 DefMacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
1738 if (!MI)
Craig Toppera13603a2014-05-22 05:54:18 +00001739 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001740 return PP.AllocateDefMacroDirective(MI, ImportLoc, /*isImported=*/true);
1741 }
1742};
1743
1744ASTReader::ModuleMacroInfo *
1745ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1746 ModuleMacroInfo Info;
1747
1748 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1749 if (ID & 1) {
1750 // Macro undefinition.
1751 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
Craig Toppera13603a2014-05-22 05:54:18 +00001752 Info.MI = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001753 } else {
1754 // Macro definition.
1755 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1756 assert(GMacID);
1757
1758 // If this macro has already been loaded, don't do so again.
1759 // FIXME: This is highly dubious. Multiple macro definitions can have the
1760 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1761 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
Craig Toppera13603a2014-05-22 05:54:18 +00001762 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001763
1764 Info.MI = getMacro(GMacID);
1765 Info.SubModID = Info.MI->getOwningModuleID();
1766 }
1767 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1768 Info.F = PMInfo.M;
1769
1770 return new (Context) ModuleMacroInfo(Info);
1771}
1772
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001773void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1774 const PendingMacroInfo &PMInfo) {
1775 assert(II);
1776
1777 if (PMInfo.M->Kind != MK_Module) {
1778 installPCHMacroDirectives(II, *PMInfo.M,
1779 PMInfo.PCHMacroData.MacroDirectivesOffset);
1780 return;
1781 }
Richard Smith49f906a2014-03-01 00:08:04 +00001782
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001783 // Module Macro.
1784
Richard Smith49f906a2014-03-01 00:08:04 +00001785 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1786 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001787 return;
1788
Richard Smith49f906a2014-03-01 00:08:04 +00001789 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1790 if (Owner && Owner->NameVisibility == Module::Hidden) {
1791 // Macros in the owning module are hidden. Just remember this macro to
1792 // install if we make this module visible.
1793 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1794 } else {
1795 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001796 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001797}
1798
1799void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1800 ModuleFile &M, uint64_t Offset) {
1801 assert(M.Kind != MK_Module);
1802
1803 BitstreamCursor &Cursor = M.MacroCursor;
1804 SavedStreamPosition SavedPosition(Cursor);
1805 Cursor.JumpToBit(Offset);
1806
1807 llvm::BitstreamEntry Entry =
1808 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1809 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1810 Error("malformed block record in AST file");
1811 return;
1812 }
1813
1814 RecordData Record;
1815 PreprocessorRecordTypes RecType =
1816 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1817 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1818 Error("malformed block record in AST file");
1819 return;
1820 }
1821
1822 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001823 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001824 unsigned Idx = 0, N = Record.size();
1825 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001826 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001827 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001828 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1829 switch (K) {
1830 case MacroDirective::MD_Define: {
1831 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1832 MacroInfo *MI = getMacro(GMacID);
1833 bool isImported = Record[Idx++];
1834 bool isAmbiguous = Record[Idx++];
1835 DefMacroDirective *DefMD =
1836 PP.AllocateDefMacroDirective(MI, Loc, isImported);
1837 DefMD->setAmbiguous(isAmbiguous);
1838 MD = DefMD;
1839 break;
1840 }
1841 case MacroDirective::MD_Undefine:
1842 MD = PP.AllocateUndefMacroDirective(Loc);
1843 break;
1844 case MacroDirective::MD_Visibility: {
1845 bool isPublic = Record[Idx++];
1846 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1847 break;
1848 }
1849 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001850
1851 if (!Latest)
1852 Latest = MD;
1853 if (Earliest)
1854 Earliest->setPrevious(MD);
1855 Earliest = MD;
1856 }
1857
1858 PP.setLoadedMacroDirective(II, Latest);
1859}
1860
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001861/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001862/// modules.
1863static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001864 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001865 assert(PrevMI && NewMI);
Craig Toppera13603a2014-05-22 05:54:18 +00001866 Module *PrevOwner = nullptr;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001867 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1868 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001869 SourceManager &SrcMgr = Reader.getSourceManager();
1870 bool PrevInSystem
1871 = PrevOwner? PrevOwner->IsSystem
1872 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1873 bool NewInSystem
1874 = NewOwner? NewOwner->IsSystem
1875 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1876 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001877 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001878 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001879}
1880
Richard Smith49f906a2014-03-01 00:08:04 +00001881void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1882 AmbiguousMacros &Ambig,
1883 llvm::ArrayRef<SubmoduleID> Overrides) {
1884 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1885 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001886
Richard Smith49f906a2014-03-01 00:08:04 +00001887 // If this macro is not yet visible, remove it from the hidden names list.
1888 Module *Owner = getSubmodule(OwnerID);
1889 HiddenNames &Hidden = HiddenNamesMap[Owner];
1890 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1891 if (HI != Hidden.HiddenMacros.end()) {
Richard Smith9d100862014-03-06 03:16:27 +00001892 auto SubOverrides = HI->second->getOverriddenSubmodules();
Richard Smith49f906a2014-03-01 00:08:04 +00001893 Hidden.HiddenMacros.erase(HI);
Richard Smith9d100862014-03-06 03:16:27 +00001894 removeOverriddenMacros(II, Ambig, SubOverrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001895 }
1896
1897 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001898 Ambig.erase(
1899 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1900 return MD->getInfo()->getOwningModuleID() == OwnerID;
1901 }),
1902 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001903 }
1904}
1905
1906ASTReader::AmbiguousMacros *
1907ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1908 llvm::ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001909 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001910 if (!Prev && Overrides.empty())
Craig Toppera13603a2014-05-22 05:54:18 +00001911 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001912
Craig Toppera13603a2014-05-22 05:54:18 +00001913 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective()
1914 : nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001915 if (PrevDef && PrevDef->isAmbiguous()) {
1916 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1917 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1918 Ambig.push_back(PrevDef);
1919
1920 removeOverriddenMacros(II, Ambig, Overrides);
1921
1922 if (!Ambig.empty())
1923 return &Ambig;
1924
1925 AmbiguousMacroDefs.erase(II);
1926 } else {
1927 // There's no ambiguity yet. Maybe we're introducing one.
Benjamin Kramer834652a2014-05-03 18:44:26 +00001928 AmbiguousMacros Ambig;
Richard Smith49f906a2014-03-01 00:08:04 +00001929 if (PrevDef)
1930 Ambig.push_back(PrevDef);
1931
1932 removeOverriddenMacros(II, Ambig, Overrides);
1933
1934 if (!Ambig.empty()) {
1935 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
Benjamin Kramer834652a2014-05-03 18:44:26 +00001936 std::swap(Result, Ambig);
Richard Smith49f906a2014-03-01 00:08:04 +00001937 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001938 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001939 }
Richard Smith49f906a2014-03-01 00:08:04 +00001940
1941 // We ended up with no ambiguity.
Craig Toppera13603a2014-05-22 05:54:18 +00001942 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001943}
1944
1945void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
1946 Module *Owner) {
1947 assert(II && Owner);
1948
1949 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
1950 if (ImportLoc.isInvalid()) {
1951 // FIXME: If we made macros from this module visible but didn't provide a
1952 // source location for the import, we don't have a location for the macro.
1953 // Use the location at which the containing module file was first imported
1954 // for now.
1955 ImportLoc = MMI->F->DirectImportLoc;
Richard Smith56be7542014-03-21 00:33:59 +00001956 assert(ImportLoc.isValid() && "no import location for a visible macro?");
Richard Smith49f906a2014-03-01 00:08:04 +00001957 }
1958
Benjamin Kramer834652a2014-05-03 18:44:26 +00001959 AmbiguousMacros *Prev =
Richard Smith49f906a2014-03-01 00:08:04 +00001960 removeOverriddenMacros(II, MMI->getOverriddenSubmodules());
1961
Richard Smith49f906a2014-03-01 00:08:04 +00001962 // Create a synthetic macro definition corresponding to the import (or null
1963 // if this was an undefinition of the macro).
1964 DefMacroDirective *MD = MMI->import(PP, ImportLoc);
1965
1966 // If there's no ambiguity, just install the macro.
1967 if (!Prev) {
1968 if (MD)
1969 PP.appendMacroDirective(II, MD);
1970 else
1971 PP.appendMacroDirective(II, PP.AllocateUndefMacroDirective(ImportLoc));
1972 return;
1973 }
1974 assert(!Prev->empty());
1975
1976 if (!MD) {
1977 // We imported a #undef that didn't remove all prior definitions. The most
1978 // recent prior definition remains, and we install it in the place of the
1979 // imported directive.
1980 MacroInfo *NewMI = Prev->back()->getInfo();
1981 Prev->pop_back();
1982 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc, /*Imported*/true);
1983 }
1984
1985 // We're introducing a macro definition that creates or adds to an ambiguity.
1986 // We can resolve that ambiguity if this macro is token-for-token identical to
1987 // all of the existing definitions.
1988 MacroInfo *NewMI = MD->getInfo();
1989 assert(NewMI && "macro definition with no MacroInfo?");
1990 while (!Prev->empty()) {
1991 MacroInfo *PrevMI = Prev->back()->getInfo();
1992 assert(PrevMI && "macro definition with no MacroInfo?");
1993
1994 // Before marking the macros as ambiguous, check if this is a case where
1995 // both macros are in system headers. If so, we trust that the system
1996 // did not get it wrong. This also handles cases where Clang's own
1997 // headers have a different spelling of certain system macros:
1998 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
1999 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
2000 //
2001 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
2002 // overrides the system limits.h's macros, so there's no conflict here.
2003 if (NewMI != PrevMI &&
2004 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
2005 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
2006 break;
2007
2008 // The previous definition is the same as this one (or both are defined in
2009 // system modules so we can assume they're equivalent); we don't need to
2010 // track it any more.
2011 Prev->pop_back();
2012 }
2013
2014 if (!Prev->empty())
2015 MD->setAmbiguous(true);
2016
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002017 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002018}
2019
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002020ASTReader::InputFileInfo
2021ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002022 // Go find this input file.
2023 BitstreamCursor &Cursor = F.InputFilesCursor;
2024 SavedStreamPosition SavedPosition(Cursor);
2025 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2026
2027 unsigned Code = Cursor.ReadCode();
2028 RecordData Record;
2029 StringRef Blob;
2030
2031 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2032 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2033 "invalid record type for input file");
2034 (void)Result;
2035
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002036 std::string Filename;
2037 off_t StoredSize;
2038 time_t StoredTime;
2039 bool Overridden;
2040
Ben Langmuir198c1682014-03-07 07:27:49 +00002041 assert(Record[0] == ID && "Bogus stored ID or offset");
2042 StoredSize = static_cast<off_t>(Record[1]);
2043 StoredTime = static_cast<time_t>(Record[2]);
2044 Overridden = static_cast<bool>(Record[3]);
2045 Filename = Blob;
2046 MaybeAddSystemRootToFilename(F, Filename);
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002047
Hans Wennborg73945142014-03-14 17:45:06 +00002048 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
2049 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002050}
2051
2052std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002053 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00002054}
2055
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002056InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002057 // If this ID is bogus, just return an empty input file.
2058 if (ID == 0 || ID > F.InputFilesLoaded.size())
2059 return InputFile();
2060
2061 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002062 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002063 return F.InputFilesLoaded[ID-1];
2064
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002065 if (F.InputFilesLoaded[ID-1].isNotFound())
2066 return InputFile();
2067
Guy Benyei11169dd2012-12-18 14:30:41 +00002068 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002069 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002070 SavedStreamPosition SavedPosition(Cursor);
2071 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2072
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002073 InputFileInfo FI = readInputFileInfo(F, ID);
2074 off_t StoredSize = FI.StoredSize;
2075 time_t StoredTime = FI.StoredTime;
2076 bool Overridden = FI.Overridden;
2077 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002078
Ben Langmuir198c1682014-03-07 07:27:49 +00002079 const FileEntry *File
2080 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
2081 : FileMgr.getFile(Filename, /*OpenFile=*/false);
2082
2083 // If we didn't find the file, resolve it relative to the
2084 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002085 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002086 F.OriginalDir != CurrentDir) {
2087 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2088 F.OriginalDir,
2089 CurrentDir);
2090 if (!Resolved.empty())
2091 File = FileMgr.getFile(Resolved);
2092 }
2093
2094 // For an overridden file, create a virtual file with the stored
2095 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00002096 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002097 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2098 }
2099
Craig Toppera13603a2014-05-22 05:54:18 +00002100 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002101 if (Complain) {
2102 std::string ErrorStr = "could not find file '";
2103 ErrorStr += Filename;
2104 ErrorStr += "' referenced by AST file";
2105 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00002106 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002107 // Record that we didn't find the file.
2108 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2109 return InputFile();
2110 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002111
Ben Langmuir198c1682014-03-07 07:27:49 +00002112 // Check if there was a request to override the contents of the file
2113 // that was part of the precompiled header. Overridding such a file
2114 // can lead to problems when lexing using the source locations from the
2115 // PCH.
2116 SourceManager &SM = getSourceManager();
2117 if (!Overridden && SM.isFileOverridden(File)) {
2118 if (Complain)
2119 Error(diag::err_fe_pch_file_overridden, Filename);
2120 // After emitting the diagnostic, recover by disabling the override so
2121 // that the original file will be used.
2122 SM.disableFileContentsOverride(File);
2123 // The FileEntry is a virtual file entry with the size of the contents
2124 // that would override the original contents. Set it to the original's
2125 // size/time.
2126 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2127 StoredSize, StoredTime);
2128 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002129
Ben Langmuir198c1682014-03-07 07:27:49 +00002130 bool IsOutOfDate = false;
2131
2132 // For an overridden file, there is nothing to validate.
2133 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei11169dd2012-12-18 14:30:41 +00002134#if !defined(LLVM_ON_WIN32)
Ben Langmuir198c1682014-03-07 07:27:49 +00002135 // In our regression testing, the Windows file system seems to
2136 // have inconsistent modification times that sometimes
2137 // erroneously trigger this error-handling path.
2138 || StoredTime != File->getModificationTime()
Guy Benyei11169dd2012-12-18 14:30:41 +00002139#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002140 )) {
2141 if (Complain) {
2142 // Build a list of the PCH imports that got us here (in reverse).
2143 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2144 while (ImportStack.back()->ImportedBy.size() > 0)
2145 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002146
Ben Langmuir198c1682014-03-07 07:27:49 +00002147 // The top-level PCH is stale.
2148 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2149 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002150
Ben Langmuir198c1682014-03-07 07:27:49 +00002151 // Print the import stack.
2152 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2153 Diag(diag::note_pch_required_by)
2154 << Filename << ImportStack[0]->FileName;
2155 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002156 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002157 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002158 }
2159
Ben Langmuir198c1682014-03-07 07:27:49 +00002160 if (!Diags.isDiagnosticInFlight())
2161 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002162 }
2163
Ben Langmuir198c1682014-03-07 07:27:49 +00002164 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002165 }
2166
Ben Langmuir198c1682014-03-07 07:27:49 +00002167 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2168
2169 // Note that we've loaded this input file.
2170 F.InputFilesLoaded[ID-1] = IF;
2171 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002172}
2173
2174const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
2175 ModuleFile &M = ModuleMgr.getPrimaryModule();
2176 std::string Filename = filenameStrRef;
2177 MaybeAddSystemRootToFilename(M, Filename);
2178 const FileEntry *File = FileMgr.getFile(Filename);
Craig Toppera13603a2014-05-22 05:54:18 +00002179 if (File == nullptr && !M.OriginalDir.empty() && !CurrentDir.empty() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002180 M.OriginalDir != CurrentDir) {
2181 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
2182 M.OriginalDir,
2183 CurrentDir);
2184 if (!resolved.empty())
2185 File = FileMgr.getFile(resolved);
2186 }
2187
2188 return File;
2189}
2190
2191/// \brief If we are loading a relocatable PCH file, and the filename is
2192/// not an absolute path, add the system root to the beginning of the file
2193/// name.
2194void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
2195 std::string &Filename) {
2196 // If this is not a relocatable PCH file, there's nothing to do.
2197 if (!M.RelocatablePCH)
2198 return;
2199
2200 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2201 return;
2202
2203 if (isysroot.empty()) {
2204 // If no system root was given, default to '/'
2205 Filename.insert(Filename.begin(), '/');
2206 return;
2207 }
2208
2209 unsigned Length = isysroot.size();
2210 if (isysroot[Length - 1] != '/')
2211 Filename.insert(Filename.begin(), '/');
2212
2213 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
2214}
2215
2216ASTReader::ASTReadResult
2217ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002218 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002219 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002220 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002221 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002222
2223 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2224 Error("malformed block record in AST file");
2225 return Failure;
2226 }
2227
2228 // Read all of the records and blocks in the control block.
2229 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002230 while (1) {
2231 llvm::BitstreamEntry Entry = Stream.advance();
2232
2233 switch (Entry.Kind) {
2234 case llvm::BitstreamEntry::Error:
2235 Error("malformed block record in AST file");
2236 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002237 case llvm::BitstreamEntry::EndBlock: {
2238 // Validate input files.
2239 const HeaderSearchOptions &HSOpts =
2240 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002241
2242 // All user input files reside at the index range [0, Record[1]), and
2243 // system input files reside at [Record[1], Record[0]).
2244 // Record is the one from INPUT_FILE_OFFSETS.
2245 unsigned NumInputs = Record[0];
2246 unsigned NumUserInputs = Record[1];
2247
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002248 if (!DisableValidation &&
Ben Langmuir1e258222014-04-08 15:36:28 +00002249 (ValidateSystemInputs || !HSOpts.ModulesValidateOncePerBuildSession ||
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002250 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002251 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002252
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002253 // If we are reading a module, we will create a verification timestamp,
2254 // so we verify all input files. Otherwise, verify only user input
2255 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002256
2257 unsigned N = NumUserInputs;
2258 if (ValidateSystemInputs ||
Ben Langmuircb69b572014-03-07 06:40:32 +00002259 (HSOpts.ModulesValidateOncePerBuildSession && F.Kind == MK_Module))
2260 N = NumInputs;
2261
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002262 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002263 InputFile IF = getInputFile(F, I+1, Complain);
2264 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002265 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002266 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002267 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002268
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002269 if (Listener)
2270 Listener->visitModuleFile(F.FileName);
2271
Ben Langmuircb69b572014-03-07 06:40:32 +00002272 if (Listener && Listener->needsInputFileVisitation()) {
2273 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2274 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002275 for (unsigned I = 0; I < N; ++I) {
2276 bool IsSystem = I >= NumUserInputs;
2277 InputFileInfo FI = readInputFileInfo(F, I+1);
2278 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2279 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002280 }
2281
Guy Benyei11169dd2012-12-18 14:30:41 +00002282 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002283 }
2284
Chris Lattnere7b154b2013-01-19 21:39:22 +00002285 case llvm::BitstreamEntry::SubBlock:
2286 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002287 case INPUT_FILES_BLOCK_ID:
2288 F.InputFilesCursor = Stream;
2289 if (Stream.SkipBlock() || // Skip with the main cursor
2290 // Read the abbreviations
2291 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2292 Error("malformed block record in AST file");
2293 return Failure;
2294 }
2295 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002296
Guy Benyei11169dd2012-12-18 14:30:41 +00002297 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002298 if (Stream.SkipBlock()) {
2299 Error("malformed block record in AST file");
2300 return Failure;
2301 }
2302 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002303 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002304
2305 case llvm::BitstreamEntry::Record:
2306 // The interesting case.
2307 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002308 }
2309
2310 // Read and process a record.
2311 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002312 StringRef Blob;
2313 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002314 case METADATA: {
2315 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2316 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002317 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2318 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002319 return VersionMismatch;
2320 }
2321
2322 bool hasErrors = Record[5];
2323 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2324 Diag(diag::err_pch_with_compiler_errors);
2325 return HadErrors;
2326 }
2327
2328 F.RelocatablePCH = Record[4];
2329
2330 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002331 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002332 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2333 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002334 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002335 return VersionMismatch;
2336 }
2337 break;
2338 }
2339
2340 case IMPORTS: {
2341 // Load each of the imported PCH files.
2342 unsigned Idx = 0, N = Record.size();
2343 while (Idx < N) {
2344 // Read information about the AST file.
2345 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2346 // The import location will be the local one for now; we will adjust
2347 // all import locations of module imports after the global source
2348 // location info are setup.
2349 SourceLocation ImportLoc =
2350 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002351 off_t StoredSize = (off_t)Record[Idx++];
2352 time_t StoredModTime = (time_t)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002353 unsigned Length = Record[Idx++];
2354 SmallString<128> ImportedFile(Record.begin() + Idx,
2355 Record.begin() + Idx + Length);
2356 Idx += Length;
2357
2358 // Load the AST file.
2359 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00002360 StoredSize, StoredModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00002361 ClientLoadCapabilities)) {
2362 case Failure: return Failure;
2363 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002364 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002365 case OutOfDate: return OutOfDate;
2366 case VersionMismatch: return VersionMismatch;
2367 case ConfigurationMismatch: return ConfigurationMismatch;
2368 case HadErrors: return HadErrors;
2369 case Success: break;
2370 }
2371 }
2372 break;
2373 }
2374
2375 case LANGUAGE_OPTIONS: {
2376 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2377 if (Listener && &F == *ModuleMgr.begin() &&
2378 ParseLanguageOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002379 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002380 return ConfigurationMismatch;
2381 break;
2382 }
2383
2384 case TARGET_OPTIONS: {
2385 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2386 if (Listener && &F == *ModuleMgr.begin() &&
2387 ParseTargetOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002388 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002389 return ConfigurationMismatch;
2390 break;
2391 }
2392
2393 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002394 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002395 if (Listener && &F == *ModuleMgr.begin() &&
2396 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002397 !DisableValidation)
2398 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002399 break;
2400 }
2401
2402 case FILE_SYSTEM_OPTIONS: {
2403 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2404 if (Listener && &F == *ModuleMgr.begin() &&
2405 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002406 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002407 return ConfigurationMismatch;
2408 break;
2409 }
2410
2411 case HEADER_SEARCH_OPTIONS: {
2412 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2413 if (Listener && &F == *ModuleMgr.begin() &&
2414 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002415 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002416 return ConfigurationMismatch;
2417 break;
2418 }
2419
2420 case PREPROCESSOR_OPTIONS: {
2421 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2422 if (Listener && &F == *ModuleMgr.begin() &&
2423 ParsePreprocessorOptions(Record, Complain, *Listener,
2424 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002425 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002426 return ConfigurationMismatch;
2427 break;
2428 }
2429
2430 case ORIGINAL_FILE:
2431 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002432 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002433 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2434 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
2435 break;
2436
2437 case ORIGINAL_FILE_ID:
2438 F.OriginalSourceFileID = FileID::get(Record[0]);
2439 break;
2440
2441 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002442 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002443 break;
2444
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002445 case MODULE_NAME:
2446 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002447 if (Listener)
2448 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002449 break;
2450
2451 case MODULE_MAP_FILE:
2452 F.ModuleMapPath = Blob;
2453
2454 // Try to resolve ModuleName in the current header search context and
2455 // verify that it is found in the same module map file as we saved. If the
2456 // top-level AST file is a main file, skip this check because there is no
2457 // usable header search context.
2458 assert(!F.ModuleName.empty() &&
2459 "MODULE_NAME should come before MOUDLE_MAP_FILE");
2460 if (F.Kind == MK_Module &&
2461 (*ModuleMgr.begin())->Kind != MK_MainFile) {
2462 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2463 if (!M) {
2464 assert(ImportedBy && "top-level import should be verified");
2465 if ((ClientLoadCapabilities & ARR_Missing) == 0)
2466 Diag(diag::err_imported_module_not_found)
2467 << F.ModuleName << ImportedBy->FileName;
2468 return Missing;
2469 }
2470
2471 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
2472 if (StoredModMap == nullptr || StoredModMap != M->ModuleMap) {
2473 assert(M->ModuleMap && "found module is missing module map file");
2474 assert(M->Name == F.ModuleName && "found module with different name");
2475 assert(ImportedBy && "top-level import should be verified");
2476 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2477 Diag(diag::err_imported_module_modmap_changed)
2478 << F.ModuleName << ImportedBy->FileName
2479 << M->ModuleMap->getName() << F.ModuleMapPath;
2480 return OutOfDate;
2481 }
2482 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002483
2484 if (Listener)
2485 Listener->ReadModuleMapFile(F.ModuleMapPath);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002486 break;
2487
Guy Benyei11169dd2012-12-18 14:30:41 +00002488 case INPUT_FILE_OFFSETS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002489 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002490 F.InputFilesLoaded.resize(Record[0]);
2491 break;
2492 }
2493 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002494}
2495
Ben Langmuir2c9af442014-04-10 17:57:43 +00002496ASTReader::ASTReadResult
2497ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002498 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002499
2500 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2501 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002502 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002503 }
2504
2505 // Read all of the records and blocks for the AST file.
2506 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002507 while (1) {
2508 llvm::BitstreamEntry Entry = Stream.advance();
2509
2510 switch (Entry.Kind) {
2511 case llvm::BitstreamEntry::Error:
2512 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002513 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002514 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002515 // Outside of C++, we do not store a lookup map for the translation unit.
2516 // Instead, mark it as needing a lookup map to be built if this module
2517 // contains any declarations lexically within it (which it always does!).
2518 // This usually has no cost, since we very rarely need the lookup map for
2519 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002520 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002521 if (DC->hasExternalLexicalStorage() &&
2522 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002523 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002524
Ben Langmuir2c9af442014-04-10 17:57:43 +00002525 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002526 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002527 case llvm::BitstreamEntry::SubBlock:
2528 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002529 case DECLTYPES_BLOCK_ID:
2530 // We lazily load the decls block, but we want to set up the
2531 // DeclsCursor cursor to point into it. Clone our current bitcode
2532 // cursor to it, enter the block and read the abbrevs in that block.
2533 // With the main cursor, we just skip over it.
2534 F.DeclsCursor = Stream;
2535 if (Stream.SkipBlock() || // Skip with the main cursor.
2536 // Read the abbrevs.
2537 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2538 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002539 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002540 }
2541 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002542
Guy Benyei11169dd2012-12-18 14:30:41 +00002543 case PREPROCESSOR_BLOCK_ID:
2544 F.MacroCursor = Stream;
2545 if (!PP.getExternalSource())
2546 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002547
Guy Benyei11169dd2012-12-18 14:30:41 +00002548 if (Stream.SkipBlock() ||
2549 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2550 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002551 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002552 }
2553 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2554 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002555
Guy Benyei11169dd2012-12-18 14:30:41 +00002556 case PREPROCESSOR_DETAIL_BLOCK_ID:
2557 F.PreprocessorDetailCursor = Stream;
2558 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002559 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002560 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002561 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002562 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002563 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002564 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002565 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2566
Guy Benyei11169dd2012-12-18 14:30:41 +00002567 if (!PP.getPreprocessingRecord())
2568 PP.createPreprocessingRecord();
2569 if (!PP.getPreprocessingRecord()->getExternalSource())
2570 PP.getPreprocessingRecord()->SetExternalSource(*this);
2571 break;
2572
2573 case SOURCE_MANAGER_BLOCK_ID:
2574 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002575 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002576 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002577
Guy Benyei11169dd2012-12-18 14:30:41 +00002578 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002579 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2580 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002581 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002582
Guy Benyei11169dd2012-12-18 14:30:41 +00002583 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002584 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002585 if (Stream.SkipBlock() ||
2586 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2587 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002588 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002589 }
2590 CommentsCursors.push_back(std::make_pair(C, &F));
2591 break;
2592 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002593
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002595 if (Stream.SkipBlock()) {
2596 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002597 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002598 }
2599 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 }
2601 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002602
2603 case llvm::BitstreamEntry::Record:
2604 // The interesting case.
2605 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002606 }
2607
2608 // Read and process a record.
2609 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002610 StringRef Blob;
2611 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002612 default: // Default behavior: ignore.
2613 break;
2614
2615 case TYPE_OFFSET: {
2616 if (F.LocalNumTypes != 0) {
2617 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002618 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002619 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002620 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002621 F.LocalNumTypes = Record[0];
2622 unsigned LocalBaseTypeIndex = Record[1];
2623 F.BaseTypeIndex = getTotalNumTypes();
2624
2625 if (F.LocalNumTypes > 0) {
2626 // Introduce the global -> local mapping for types within this module.
2627 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2628
2629 // Introduce the local -> global mapping for types within this module.
2630 F.TypeRemap.insertOrReplace(
2631 std::make_pair(LocalBaseTypeIndex,
2632 F.BaseTypeIndex - LocalBaseTypeIndex));
2633
2634 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2635 }
2636 break;
2637 }
2638
2639 case DECL_OFFSET: {
2640 if (F.LocalNumDecls != 0) {
2641 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002642 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002643 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002644 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002645 F.LocalNumDecls = Record[0];
2646 unsigned LocalBaseDeclID = Record[1];
2647 F.BaseDeclID = getTotalNumDecls();
2648
2649 if (F.LocalNumDecls > 0) {
2650 // Introduce the global -> local mapping for declarations within this
2651 // module.
2652 GlobalDeclMap.insert(
2653 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2654
2655 // Introduce the local -> global mapping for declarations within this
2656 // module.
2657 F.DeclRemap.insertOrReplace(
2658 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2659
2660 // Introduce the global -> local mapping for declarations within this
2661 // module.
2662 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2663
2664 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2665 }
2666 break;
2667 }
2668
2669 case TU_UPDATE_LEXICAL: {
2670 DeclContext *TU = Context.getTranslationUnitDecl();
2671 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002672 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002673 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002674 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002675 TU->setHasExternalLexicalStorage(true);
2676 break;
2677 }
2678
2679 case UPDATE_VISIBLE: {
2680 unsigned Idx = 0;
2681 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2682 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002683 ASTDeclContextNameLookupTable::Create(
2684 (const unsigned char *)Blob.data() + Record[Idx++],
2685 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2686 (const unsigned char *)Blob.data(),
2687 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002688 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002689 auto *DC = cast<DeclContext>(D);
2690 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002691 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
Richard Smithcd45dbc2014-04-19 03:48:30 +00002692 // FIXME: There should never be an existing lookup table.
Richard Smith52e3fba2014-03-11 07:17:35 +00002693 delete LookupTable;
2694 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002695 } else
2696 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2697 break;
2698 }
2699
2700 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002701 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002702 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002703 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2704 (const unsigned char *)F.IdentifierTableData + Record[0],
2705 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2706 (const unsigned char *)F.IdentifierTableData,
2707 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002708
2709 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2710 }
2711 break;
2712
2713 case IDENTIFIER_OFFSET: {
2714 if (F.LocalNumIdentifiers != 0) {
2715 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002716 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002717 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002718 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002719 F.LocalNumIdentifiers = Record[0];
2720 unsigned LocalBaseIdentifierID = Record[1];
2721 F.BaseIdentifierID = getTotalNumIdentifiers();
2722
2723 if (F.LocalNumIdentifiers > 0) {
2724 // Introduce the global -> local mapping for identifiers within this
2725 // module.
2726 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2727 &F));
2728
2729 // Introduce the local -> global mapping for identifiers within this
2730 // module.
2731 F.IdentifierRemap.insertOrReplace(
2732 std::make_pair(LocalBaseIdentifierID,
2733 F.BaseIdentifierID - LocalBaseIdentifierID));
2734
2735 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2736 + F.LocalNumIdentifiers);
2737 }
2738 break;
2739 }
2740
Ben Langmuir332aafe2014-01-31 01:06:56 +00002741 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002742 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002743 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002744 break;
2745
2746 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002747 if (SpecialTypes.empty()) {
2748 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2749 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2750 break;
2751 }
2752
2753 if (SpecialTypes.size() != Record.size()) {
2754 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002755 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002756 }
2757
2758 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2759 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2760 if (!SpecialTypes[I])
2761 SpecialTypes[I] = ID;
2762 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2763 // merge step?
2764 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002765 break;
2766
2767 case STATISTICS:
2768 TotalNumStatements += Record[0];
2769 TotalNumMacros += Record[1];
2770 TotalLexicalDeclContexts += Record[2];
2771 TotalVisibleDeclContexts += Record[3];
2772 break;
2773
2774 case UNUSED_FILESCOPED_DECLS:
2775 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2776 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2777 break;
2778
2779 case DELEGATING_CTORS:
2780 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2781 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2782 break;
2783
2784 case WEAK_UNDECLARED_IDENTIFIERS:
2785 if (Record.size() % 4 != 0) {
2786 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002787 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002788 }
2789
2790 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2791 // files. This isn't the way to do it :)
2792 WeakUndeclaredIdentifiers.clear();
2793
2794 // Translate the weak, undeclared identifiers into global IDs.
2795 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2796 WeakUndeclaredIdentifiers.push_back(
2797 getGlobalIdentifierID(F, Record[I++]));
2798 WeakUndeclaredIdentifiers.push_back(
2799 getGlobalIdentifierID(F, Record[I++]));
2800 WeakUndeclaredIdentifiers.push_back(
2801 ReadSourceLocation(F, Record, I).getRawEncoding());
2802 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2803 }
2804 break;
2805
Richard Smith78165b52013-01-10 23:43:47 +00002806 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002807 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith78165b52013-01-10 23:43:47 +00002808 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002809 break;
2810
2811 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002812 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002813 F.LocalNumSelectors = Record[0];
2814 unsigned LocalBaseSelectorID = Record[1];
2815 F.BaseSelectorID = getTotalNumSelectors();
2816
2817 if (F.LocalNumSelectors > 0) {
2818 // Introduce the global -> local mapping for selectors within this
2819 // module.
2820 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2821
2822 // Introduce the local -> global mapping for selectors within this
2823 // module.
2824 F.SelectorRemap.insertOrReplace(
2825 std::make_pair(LocalBaseSelectorID,
2826 F.BaseSelectorID - LocalBaseSelectorID));
2827
2828 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2829 }
2830 break;
2831 }
2832
2833 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002834 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002835 if (Record[0])
2836 F.SelectorLookupTable
2837 = ASTSelectorLookupTable::Create(
2838 F.SelectorLookupTableData + Record[0],
2839 F.SelectorLookupTableData,
2840 ASTSelectorLookupTrait(*this, F));
2841 TotalNumMethodPoolEntries += Record[1];
2842 break;
2843
2844 case REFERENCED_SELECTOR_POOL:
2845 if (!Record.empty()) {
2846 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2847 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2848 Record[Idx++]));
2849 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2850 getRawEncoding());
2851 }
2852 }
2853 break;
2854
2855 case PP_COUNTER_VALUE:
2856 if (!Record.empty() && Listener)
2857 Listener->ReadCounter(F, Record[0]);
2858 break;
2859
2860 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002861 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002862 F.NumFileSortedDecls = Record[0];
2863 break;
2864
2865 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002866 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002867 F.LocalNumSLocEntries = Record[0];
2868 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002869 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Guy Benyei11169dd2012-12-18 14:30:41 +00002870 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2871 SLocSpaceSize);
2872 // Make our entry in the range map. BaseID is negative and growing, so
2873 // we invert it. Because we invert it, though, we need the other end of
2874 // the range.
2875 unsigned RangeStart =
2876 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2877 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2878 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2879
2880 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2881 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2882 GlobalSLocOffsetMap.insert(
2883 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2884 - SLocSpaceSize,&F));
2885
2886 // Initialize the remapping table.
2887 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002888 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002889 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002890 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002891 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2892
2893 TotalNumSLocEntries += F.LocalNumSLocEntries;
2894 break;
2895 }
2896
2897 case MODULE_OFFSET_MAP: {
2898 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002899 const unsigned char *Data = (const unsigned char*)Blob.data();
2900 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002901
2902 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2903 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2904 F.SLocRemap.insert(std::make_pair(0U, 0));
2905 F.SLocRemap.insert(std::make_pair(2U, 1));
2906 }
2907
Guy Benyei11169dd2012-12-18 14:30:41 +00002908 // Continuous range maps we may be updating in our module.
2909 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2910 ContinuousRangeMap<uint32_t, int, 2>::Builder
2911 IdentifierRemap(F.IdentifierRemap);
2912 ContinuousRangeMap<uint32_t, int, 2>::Builder
2913 MacroRemap(F.MacroRemap);
2914 ContinuousRangeMap<uint32_t, int, 2>::Builder
2915 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2916 ContinuousRangeMap<uint32_t, int, 2>::Builder
2917 SubmoduleRemap(F.SubmoduleRemap);
2918 ContinuousRangeMap<uint32_t, int, 2>::Builder
2919 SelectorRemap(F.SelectorRemap);
2920 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2921 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2922
2923 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002924 using namespace llvm::support;
2925 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002926 StringRef Name = StringRef((const char*)Data, Len);
2927 Data += Len;
2928 ModuleFile *OM = ModuleMgr.lookup(Name);
2929 if (!OM) {
2930 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002931 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002932 }
2933
Justin Bogner57ba0b22014-03-28 22:03:24 +00002934 uint32_t SLocOffset =
2935 endian::readNext<uint32_t, little, unaligned>(Data);
2936 uint32_t IdentifierIDOffset =
2937 endian::readNext<uint32_t, little, unaligned>(Data);
2938 uint32_t MacroIDOffset =
2939 endian::readNext<uint32_t, little, unaligned>(Data);
2940 uint32_t PreprocessedEntityIDOffset =
2941 endian::readNext<uint32_t, little, unaligned>(Data);
2942 uint32_t SubmoduleIDOffset =
2943 endian::readNext<uint32_t, little, unaligned>(Data);
2944 uint32_t SelectorIDOffset =
2945 endian::readNext<uint32_t, little, unaligned>(Data);
2946 uint32_t DeclIDOffset =
2947 endian::readNext<uint32_t, little, unaligned>(Data);
2948 uint32_t TypeIndexOffset =
2949 endian::readNext<uint32_t, little, unaligned>(Data);
2950
Guy Benyei11169dd2012-12-18 14:30:41 +00002951 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2952 SLocRemap.insert(std::make_pair(SLocOffset,
2953 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2954 IdentifierRemap.insert(
2955 std::make_pair(IdentifierIDOffset,
2956 OM->BaseIdentifierID - IdentifierIDOffset));
2957 MacroRemap.insert(std::make_pair(MacroIDOffset,
2958 OM->BaseMacroID - MacroIDOffset));
2959 PreprocessedEntityRemap.insert(
2960 std::make_pair(PreprocessedEntityIDOffset,
2961 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2962 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2963 OM->BaseSubmoduleID - SubmoduleIDOffset));
2964 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2965 OM->BaseSelectorID - SelectorIDOffset));
2966 DeclRemap.insert(std::make_pair(DeclIDOffset,
2967 OM->BaseDeclID - DeclIDOffset));
2968
2969 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2970 OM->BaseTypeIndex - TypeIndexOffset));
2971
2972 // Global -> local mappings.
2973 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2974 }
2975 break;
2976 }
2977
2978 case SOURCE_MANAGER_LINE_TABLE:
2979 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002980 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002981 break;
2982
2983 case SOURCE_LOCATION_PRELOADS: {
2984 // Need to transform from the local view (1-based IDs) to the global view,
2985 // which is based off F.SLocEntryBaseID.
2986 if (!F.PreloadSLocEntries.empty()) {
2987 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002988 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002989 }
2990
2991 F.PreloadSLocEntries.swap(Record);
2992 break;
2993 }
2994
2995 case EXT_VECTOR_DECLS:
2996 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2997 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2998 break;
2999
3000 case VTABLE_USES:
3001 if (Record.size() % 3 != 0) {
3002 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003003 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003004 }
3005
3006 // Later tables overwrite earlier ones.
3007 // FIXME: Modules will have some trouble with this. This is clearly not
3008 // the right way to do this.
3009 VTableUses.clear();
3010
3011 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3012 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3013 VTableUses.push_back(
3014 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3015 VTableUses.push_back(Record[Idx++]);
3016 }
3017 break;
3018
3019 case DYNAMIC_CLASSES:
3020 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3021 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
3022 break;
3023
3024 case PENDING_IMPLICIT_INSTANTIATIONS:
3025 if (PendingInstantiations.size() % 2 != 0) {
3026 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003027 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003028 }
3029
3030 if (Record.size() % 2 != 0) {
3031 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003032 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003033 }
3034
3035 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3036 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3037 PendingInstantiations.push_back(
3038 ReadSourceLocation(F, Record, I).getRawEncoding());
3039 }
3040 break;
3041
3042 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00003043 if (Record.size() != 2) {
3044 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003045 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003046 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003047 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3048 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3049 break;
3050
3051 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003052 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3053 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3054 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003055
3056 unsigned LocalBasePreprocessedEntityID = Record[0];
3057
3058 unsigned StartingID;
3059 if (!PP.getPreprocessingRecord())
3060 PP.createPreprocessingRecord();
3061 if (!PP.getPreprocessingRecord()->getExternalSource())
3062 PP.getPreprocessingRecord()->SetExternalSource(*this);
3063 StartingID
3064 = PP.getPreprocessingRecord()
3065 ->allocateLoadedEntities(F.NumPreprocessedEntities);
3066 F.BasePreprocessedEntityID = StartingID;
3067
3068 if (F.NumPreprocessedEntities > 0) {
3069 // Introduce the global -> local mapping for preprocessed entities in
3070 // this module.
3071 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3072
3073 // Introduce the local -> global mapping for preprocessed entities in
3074 // this module.
3075 F.PreprocessedEntityRemap.insertOrReplace(
3076 std::make_pair(LocalBasePreprocessedEntityID,
3077 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3078 }
3079
3080 break;
3081 }
3082
3083 case DECL_UPDATE_OFFSETS: {
3084 if (Record.size() % 2 != 0) {
3085 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003086 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003087 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003088 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3089 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3090 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3091
3092 // If we've already loaded the decl, perform the updates when we finish
3093 // loading this block.
3094 if (Decl *D = GetExistingDecl(ID))
3095 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3096 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003097 break;
3098 }
3099
3100 case DECL_REPLACEMENTS: {
3101 if (Record.size() % 3 != 0) {
3102 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003103 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003104 }
3105 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3106 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3107 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3108 break;
3109 }
3110
3111 case OBJC_CATEGORIES_MAP: {
3112 if (F.LocalNumObjCCategoriesInMap != 0) {
3113 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003114 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003115 }
3116
3117 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003118 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003119 break;
3120 }
3121
3122 case OBJC_CATEGORIES:
3123 F.ObjCCategories.swap(Record);
3124 break;
3125
3126 case CXX_BASE_SPECIFIER_OFFSETS: {
3127 if (F.LocalNumCXXBaseSpecifiers != 0) {
3128 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003129 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003130 }
3131
3132 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003133 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003134 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
3135 break;
3136 }
3137
3138 case DIAG_PRAGMA_MAPPINGS:
3139 if (F.PragmaDiagMappings.empty())
3140 F.PragmaDiagMappings.swap(Record);
3141 else
3142 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3143 Record.begin(), Record.end());
3144 break;
3145
3146 case CUDA_SPECIAL_DECL_REFS:
3147 // Later tables overwrite earlier ones.
3148 // FIXME: Modules will have trouble with this.
3149 CUDASpecialDeclRefs.clear();
3150 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3151 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3152 break;
3153
3154 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003155 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003156 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003157 if (Record[0]) {
3158 F.HeaderFileInfoTable
3159 = HeaderFileInfoLookupTable::Create(
3160 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3161 (const unsigned char *)F.HeaderFileInfoTableData,
3162 HeaderFileInfoTrait(*this, F,
3163 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003164 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003165
3166 PP.getHeaderSearchInfo().SetExternalSource(this);
3167 if (!PP.getHeaderSearchInfo().getExternalLookup())
3168 PP.getHeaderSearchInfo().SetExternalLookup(this);
3169 }
3170 break;
3171 }
3172
3173 case FP_PRAGMA_OPTIONS:
3174 // Later tables overwrite earlier ones.
3175 FPPragmaOptions.swap(Record);
3176 break;
3177
3178 case OPENCL_EXTENSIONS:
3179 // Later tables overwrite earlier ones.
3180 OpenCLExtensions.swap(Record);
3181 break;
3182
3183 case TENTATIVE_DEFINITIONS:
3184 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3185 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3186 break;
3187
3188 case KNOWN_NAMESPACES:
3189 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3190 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3191 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003192
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003193 case UNDEFINED_BUT_USED:
3194 if (UndefinedButUsed.size() % 2 != 0) {
3195 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003196 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003197 }
3198
3199 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003200 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003201 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003202 }
3203 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003204 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3205 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003206 ReadSourceLocation(F, Record, I).getRawEncoding());
3207 }
3208 break;
3209
Guy Benyei11169dd2012-12-18 14:30:41 +00003210 case IMPORTED_MODULES: {
3211 if (F.Kind != MK_Module) {
3212 // If we aren't loading a module (which has its own exports), make
3213 // all of the imported modules visible.
3214 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003215 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3216 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3217 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3218 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003219 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003220 }
3221 }
3222 break;
3223 }
3224
3225 case LOCAL_REDECLARATIONS: {
3226 F.RedeclarationChains.swap(Record);
3227 break;
3228 }
3229
3230 case LOCAL_REDECLARATIONS_MAP: {
3231 if (F.LocalNumRedeclarationsInMap != 0) {
3232 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003233 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003234 }
3235
3236 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003237 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003238 break;
3239 }
3240
3241 case MERGED_DECLARATIONS: {
3242 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3243 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3244 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3245 for (unsigned N = Record[Idx++]; N > 0; --N)
3246 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3247 }
3248 break;
3249 }
3250
3251 case MACRO_OFFSET: {
3252 if (F.LocalNumMacros != 0) {
3253 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003254 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003255 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003256 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003257 F.LocalNumMacros = Record[0];
3258 unsigned LocalBaseMacroID = Record[1];
3259 F.BaseMacroID = getTotalNumMacros();
3260
3261 if (F.LocalNumMacros > 0) {
3262 // Introduce the global -> local mapping for macros within this module.
3263 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3264
3265 // Introduce the local -> global mapping for macros within this module.
3266 F.MacroRemap.insertOrReplace(
3267 std::make_pair(LocalBaseMacroID,
3268 F.BaseMacroID - LocalBaseMacroID));
3269
3270 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3271 }
3272 break;
3273 }
3274
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003275 case MACRO_TABLE: {
3276 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00003277 break;
3278 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00003279
3280 case LATE_PARSED_TEMPLATE: {
3281 LateParsedTemplates.append(Record.begin(), Record.end());
3282 break;
3283 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003284 }
3285 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003286}
3287
Douglas Gregorc1489562013-02-12 23:36:21 +00003288/// \brief Move the given method to the back of the global list of methods.
3289static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3290 // Find the entry for this selector in the method pool.
3291 Sema::GlobalMethodPool::iterator Known
3292 = S.MethodPool.find(Method->getSelector());
3293 if (Known == S.MethodPool.end())
3294 return;
3295
3296 // Retrieve the appropriate method list.
3297 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3298 : Known->second.second;
3299 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003300 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003301 if (!Found) {
3302 if (List->Method == Method) {
3303 Found = true;
3304 } else {
3305 // Keep searching.
3306 continue;
3307 }
3308 }
3309
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003310 if (List->getNext())
3311 List->Method = List->getNext()->Method;
Douglas Gregorc1489562013-02-12 23:36:21 +00003312 else
3313 List->Method = Method;
3314 }
3315}
3316
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003317void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00003318 for (unsigned I = 0, N = Names.HiddenDecls.size(); I != N; ++I) {
3319 Decl *D = Names.HiddenDecls[I];
3320 bool wasHidden = D->Hidden;
3321 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003322
Richard Smith49f906a2014-03-01 00:08:04 +00003323 if (wasHidden && SemaObj) {
3324 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3325 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003326 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003327 }
3328 }
Richard Smith49f906a2014-03-01 00:08:04 +00003329
3330 for (HiddenMacrosMap::const_iterator I = Names.HiddenMacros.begin(),
3331 E = Names.HiddenMacros.end();
3332 I != E; ++I)
3333 installImportedMacro(I->first, I->second, Owner);
Guy Benyei11169dd2012-12-18 14:30:41 +00003334}
3335
Richard Smith49f906a2014-03-01 00:08:04 +00003336void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003337 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003338 SourceLocation ImportLoc,
3339 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003340 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003341 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003342 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003343 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003344 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003345
3346 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003347 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003348 // there is nothing more to do.
3349 continue;
3350 }
Richard Smith49f906a2014-03-01 00:08:04 +00003351
Guy Benyei11169dd2012-12-18 14:30:41 +00003352 if (!Mod->isAvailable()) {
3353 // Modules that aren't available cannot be made visible.
3354 continue;
3355 }
3356
3357 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003358 if (NameVisibility >= Module::MacrosVisible &&
3359 Mod->NameVisibility < Module::MacrosVisible)
3360 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003361 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003362
Guy Benyei11169dd2012-12-18 14:30:41 +00003363 // If we've already deserialized any names from this module,
3364 // mark them as visible.
3365 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3366 if (Hidden != HiddenNamesMap.end()) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003367 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003368 HiddenNamesMap.erase(Hidden);
3369 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003370
Guy Benyei11169dd2012-12-18 14:30:41 +00003371 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003372 SmallVector<Module *, 16> Exports;
3373 Mod->getExportedModules(Exports);
3374 for (SmallVectorImpl<Module *>::iterator
3375 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3376 Module *Exported = *I;
3377 if (Visited.insert(Exported))
3378 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003379 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003380
3381 // Detect any conflicts.
3382 if (Complain) {
3383 assert(ImportLoc.isValid() && "Missing import location");
3384 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3385 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3386 Diag(ImportLoc, diag::warn_module_conflict)
3387 << Mod->getFullModuleName()
3388 << Mod->Conflicts[I].Other->getFullModuleName()
3389 << Mod->Conflicts[I].Message;
3390 // FIXME: Need note where the other module was imported.
3391 }
3392 }
3393 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003394 }
3395}
3396
Douglas Gregore060e572013-01-25 01:03:03 +00003397bool ASTReader::loadGlobalIndex() {
3398 if (GlobalIndex)
3399 return false;
3400
3401 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3402 !Context.getLangOpts().Modules)
3403 return true;
3404
3405 // Try to load the global index.
3406 TriedLoadingGlobalIndex = true;
3407 StringRef ModuleCachePath
3408 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3409 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003410 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003411 if (!Result.first)
3412 return true;
3413
3414 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003415 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003416 return false;
3417}
3418
3419bool ASTReader::isGlobalIndexUnavailable() const {
3420 return Context.getLangOpts().Modules && UseGlobalIndex &&
3421 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3422}
3423
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003424static void updateModuleTimestamp(ModuleFile &MF) {
3425 // Overwrite the timestamp file contents so that file's mtime changes.
3426 std::string TimestampFilename = MF.getTimestampFilename();
3427 std::string ErrorInfo;
Rafael Espindola04a13be2014-02-24 15:06:52 +00003428 llvm::raw_fd_ostream OS(TimestampFilename.c_str(), ErrorInfo,
Rafael Espindola4fbd3732014-02-24 18:20:21 +00003429 llvm::sys::fs::F_Text);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003430 if (!ErrorInfo.empty())
3431 return;
3432 OS << "Timestamp file\n";
3433}
3434
Guy Benyei11169dd2012-12-18 14:30:41 +00003435ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3436 ModuleKind Type,
3437 SourceLocation ImportLoc,
3438 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003439 llvm::SaveAndRestore<SourceLocation>
3440 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3441
Richard Smithd1c46742014-04-30 02:24:17 +00003442 // Defer any pending actions until we get to the end of reading the AST file.
3443 Deserializing AnASTFile(this);
3444
Guy Benyei11169dd2012-12-18 14:30:41 +00003445 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003446 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003447
3448 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003449 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003450 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003451 /*ImportedBy=*/nullptr, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003452 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003453 ClientLoadCapabilities)) {
3454 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003455 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003456 case OutOfDate:
3457 case VersionMismatch:
3458 case ConfigurationMismatch:
3459 case HadErrors:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003460 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
3461 Context.getLangOpts().Modules
3462 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003463 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003464
3465 // If we find that any modules are unusable, the global index is going
3466 // to be out-of-date. Just remove it.
3467 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003468 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003469 return ReadResult;
3470
3471 case Success:
3472 break;
3473 }
3474
3475 // Here comes stuff that we only do once the entire chain is loaded.
3476
3477 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003478 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3479 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003480 M != MEnd; ++M) {
3481 ModuleFile &F = *M->Mod;
3482
3483 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003484 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3485 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003486
3487 // Once read, set the ModuleFile bit base offset and update the size in
3488 // bits of all files we've seen.
3489 F.GlobalBitOffset = TotalModulesSizeInBits;
3490 TotalModulesSizeInBits += F.SizeInBits;
3491 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3492
3493 // Preload SLocEntries.
3494 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3495 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3496 // Load it through the SourceManager and don't call ReadSLocEntry()
3497 // directly because the entry may have already been loaded in which case
3498 // calling ReadSLocEntry() directly would trigger an assertion in
3499 // SourceManager.
3500 SourceMgr.getLoadedSLocEntryByID(Index);
3501 }
3502 }
3503
Douglas Gregor603cd862013-03-22 18:50:14 +00003504 // Setup the import locations and notify the module manager that we've
3505 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003506 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3507 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003508 M != MEnd; ++M) {
3509 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003510
3511 ModuleMgr.moduleFileAccepted(&F);
3512
3513 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003514 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003515 if (!M->ImportedBy)
3516 F.ImportLoc = M->ImportLoc;
3517 else
3518 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3519 M->ImportLoc.getRawEncoding());
3520 }
3521
3522 // Mark all of the identifiers in the identifier table as being out of date,
3523 // so that various accessors know to check the loaded modules when the
3524 // identifier is used.
3525 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3526 IdEnd = PP.getIdentifierTable().end();
3527 Id != IdEnd; ++Id)
3528 Id->second->setOutOfDate(true);
3529
3530 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003531 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3532 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003533 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3534 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003535
3536 switch (Unresolved.Kind) {
3537 case UnresolvedModuleRef::Conflict:
3538 if (ResolvedMod) {
3539 Module::Conflict Conflict;
3540 Conflict.Other = ResolvedMod;
3541 Conflict.Message = Unresolved.String.str();
3542 Unresolved.Mod->Conflicts.push_back(Conflict);
3543 }
3544 continue;
3545
3546 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003547 if (ResolvedMod)
3548 Unresolved.Mod->Imports.push_back(ResolvedMod);
3549 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003550
Douglas Gregorfb912652013-03-20 21:10:35 +00003551 case UnresolvedModuleRef::Export:
3552 if (ResolvedMod || Unresolved.IsWildcard)
3553 Unresolved.Mod->Exports.push_back(
3554 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3555 continue;
3556 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003557 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003558 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003559
3560 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3561 // Might be unnecessary as use declarations are only used to build the
3562 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003563
3564 InitializeContext();
3565
Richard Smith3d8e97e2013-10-18 06:54:39 +00003566 if (SemaObj)
3567 UpdateSema();
3568
Guy Benyei11169dd2012-12-18 14:30:41 +00003569 if (DeserializationListener)
3570 DeserializationListener->ReaderInitialized(this);
3571
3572 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3573 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3574 PrimaryModule.OriginalSourceFileID
3575 = FileID::get(PrimaryModule.SLocEntryBaseID
3576 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3577
3578 // If this AST file is a precompiled preamble, then set the
3579 // preamble file ID of the source manager to the file source file
3580 // from which the preamble was built.
3581 if (Type == MK_Preamble) {
3582 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3583 } else if (Type == MK_MainFile) {
3584 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3585 }
3586 }
3587
3588 // For any Objective-C class definitions we have already loaded, make sure
3589 // that we load any additional categories.
3590 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3591 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3592 ObjCClassesLoaded[I],
3593 PreviousGeneration);
3594 }
Douglas Gregore060e572013-01-25 01:03:03 +00003595
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003596 if (PP.getHeaderSearchInfo()
3597 .getHeaderSearchOpts()
3598 .ModulesValidateOncePerBuildSession) {
3599 // Now we are certain that the module and all modules it depends on are
3600 // up to date. Create or update timestamp files for modules that are
3601 // located in the module cache (not for PCH files that could be anywhere
3602 // in the filesystem).
3603 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3604 ImportedModule &M = Loaded[I];
3605 if (M.Mod->Kind == MK_Module) {
3606 updateModuleTimestamp(*M.Mod);
3607 }
3608 }
3609 }
3610
Guy Benyei11169dd2012-12-18 14:30:41 +00003611 return Success;
3612}
3613
3614ASTReader::ASTReadResult
3615ASTReader::ReadASTCore(StringRef FileName,
3616 ModuleKind Type,
3617 SourceLocation ImportLoc,
3618 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003619 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003620 off_t ExpectedSize, time_t ExpectedModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00003621 unsigned ClientLoadCapabilities) {
3622 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003623 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003624 ModuleManager::AddModuleResult AddResult
3625 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003626 getGeneration(), ExpectedSize, ExpectedModTime,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003627 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003628
Douglas Gregor7029ce12013-03-19 00:28:20 +00003629 switch (AddResult) {
3630 case ModuleManager::AlreadyLoaded:
3631 return Success;
3632
3633 case ModuleManager::NewlyLoaded:
3634 // Load module file below.
3635 break;
3636
3637 case ModuleManager::Missing:
3638 // The module file was missing; if the client handle handle, that, return
3639 // it.
3640 if (ClientLoadCapabilities & ARR_Missing)
3641 return Missing;
3642
3643 // Otherwise, return an error.
3644 {
3645 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3646 + ErrorStr;
3647 Error(Msg);
3648 }
3649 return Failure;
3650
3651 case ModuleManager::OutOfDate:
3652 // We couldn't load the module file because it is out-of-date. If the
3653 // client can handle out-of-date, return it.
3654 if (ClientLoadCapabilities & ARR_OutOfDate)
3655 return OutOfDate;
3656
3657 // Otherwise, return an error.
3658 {
3659 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3660 + ErrorStr;
3661 Error(Msg);
3662 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003663 return Failure;
3664 }
3665
Douglas Gregor7029ce12013-03-19 00:28:20 +00003666 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003667
3668 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3669 // module?
3670 if (FileName != "-") {
3671 CurrentDir = llvm::sys::path::parent_path(FileName);
3672 if (CurrentDir.empty()) CurrentDir = ".";
3673 }
3674
3675 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003676 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003677 Stream.init(F.StreamFile);
3678 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3679
3680 // Sniff for the signature.
3681 if (Stream.Read(8) != 'C' ||
3682 Stream.Read(8) != 'P' ||
3683 Stream.Read(8) != 'C' ||
3684 Stream.Read(8) != 'H') {
3685 Diag(diag::err_not_a_pch_file) << FileName;
3686 return Failure;
3687 }
3688
3689 // This is used for compatibility with older PCH formats.
3690 bool HaveReadControlBlock = false;
3691
Chris Lattnerefa77172013-01-20 00:00:22 +00003692 while (1) {
3693 llvm::BitstreamEntry Entry = Stream.advance();
3694
3695 switch (Entry.Kind) {
3696 case llvm::BitstreamEntry::Error:
3697 case llvm::BitstreamEntry::EndBlock:
3698 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003699 Error("invalid record at top-level of AST file");
3700 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003701
3702 case llvm::BitstreamEntry::SubBlock:
3703 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003704 }
3705
Guy Benyei11169dd2012-12-18 14:30:41 +00003706 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003707 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003708 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3709 if (Stream.ReadBlockInfoBlock()) {
3710 Error("malformed BlockInfoBlock in AST file");
3711 return Failure;
3712 }
3713 break;
3714 case CONTROL_BLOCK_ID:
3715 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003716 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003717 case Success:
3718 break;
3719
3720 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003721 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003722 case OutOfDate: return OutOfDate;
3723 case VersionMismatch: return VersionMismatch;
3724 case ConfigurationMismatch: return ConfigurationMismatch;
3725 case HadErrors: return HadErrors;
3726 }
3727 break;
3728 case AST_BLOCK_ID:
3729 if (!HaveReadControlBlock) {
3730 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003731 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003732 return VersionMismatch;
3733 }
3734
3735 // Record that we've loaded this module.
3736 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3737 return Success;
3738
3739 default:
3740 if (Stream.SkipBlock()) {
3741 Error("malformed block record in AST file");
3742 return Failure;
3743 }
3744 break;
3745 }
3746 }
3747
3748 return Success;
3749}
3750
3751void ASTReader::InitializeContext() {
3752 // If there's a listener, notify them that we "read" the translation unit.
3753 if (DeserializationListener)
3754 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3755 Context.getTranslationUnitDecl());
3756
Guy Benyei11169dd2012-12-18 14:30:41 +00003757 // FIXME: Find a better way to deal with collisions between these
3758 // built-in types. Right now, we just ignore the problem.
3759
3760 // Load the special types.
3761 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3762 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3763 if (!Context.CFConstantStringTypeDecl)
3764 Context.setCFConstantStringType(GetType(String));
3765 }
3766
3767 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3768 QualType FileType = GetType(File);
3769 if (FileType.isNull()) {
3770 Error("FILE type is NULL");
3771 return;
3772 }
3773
3774 if (!Context.FILEDecl) {
3775 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3776 Context.setFILEDecl(Typedef->getDecl());
3777 else {
3778 const TagType *Tag = FileType->getAs<TagType>();
3779 if (!Tag) {
3780 Error("Invalid FILE type in AST file");
3781 return;
3782 }
3783 Context.setFILEDecl(Tag->getDecl());
3784 }
3785 }
3786 }
3787
3788 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3789 QualType Jmp_bufType = GetType(Jmp_buf);
3790 if (Jmp_bufType.isNull()) {
3791 Error("jmp_buf type is NULL");
3792 return;
3793 }
3794
3795 if (!Context.jmp_bufDecl) {
3796 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3797 Context.setjmp_bufDecl(Typedef->getDecl());
3798 else {
3799 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3800 if (!Tag) {
3801 Error("Invalid jmp_buf type in AST file");
3802 return;
3803 }
3804 Context.setjmp_bufDecl(Tag->getDecl());
3805 }
3806 }
3807 }
3808
3809 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3810 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3811 if (Sigjmp_bufType.isNull()) {
3812 Error("sigjmp_buf type is NULL");
3813 return;
3814 }
3815
3816 if (!Context.sigjmp_bufDecl) {
3817 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3818 Context.setsigjmp_bufDecl(Typedef->getDecl());
3819 else {
3820 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3821 assert(Tag && "Invalid sigjmp_buf type in AST file");
3822 Context.setsigjmp_bufDecl(Tag->getDecl());
3823 }
3824 }
3825 }
3826
3827 if (unsigned ObjCIdRedef
3828 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3829 if (Context.ObjCIdRedefinitionType.isNull())
3830 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3831 }
3832
3833 if (unsigned ObjCClassRedef
3834 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3835 if (Context.ObjCClassRedefinitionType.isNull())
3836 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3837 }
3838
3839 if (unsigned ObjCSelRedef
3840 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3841 if (Context.ObjCSelRedefinitionType.isNull())
3842 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3843 }
3844
3845 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3846 QualType Ucontext_tType = GetType(Ucontext_t);
3847 if (Ucontext_tType.isNull()) {
3848 Error("ucontext_t type is NULL");
3849 return;
3850 }
3851
3852 if (!Context.ucontext_tDecl) {
3853 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3854 Context.setucontext_tDecl(Typedef->getDecl());
3855 else {
3856 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3857 assert(Tag && "Invalid ucontext_t type in AST file");
3858 Context.setucontext_tDecl(Tag->getDecl());
3859 }
3860 }
3861 }
3862 }
3863
3864 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3865
3866 // If there were any CUDA special declarations, deserialize them.
3867 if (!CUDASpecialDeclRefs.empty()) {
3868 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3869 Context.setcudaConfigureCallDecl(
3870 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3871 }
Richard Smith56be7542014-03-21 00:33:59 +00003872
Guy Benyei11169dd2012-12-18 14:30:41 +00003873 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00003874 // FIXME: This does not make macro-only imports visible again. It also doesn't
3875 // make #includes mapped to module imports visible.
3876 for (auto &Import : ImportedModules) {
3877 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003878 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00003879 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00003880 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00003881 }
3882 ImportedModules.clear();
3883}
3884
3885void ASTReader::finalizeForWriting() {
3886 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3887 HiddenEnd = HiddenNamesMap.end();
3888 Hidden != HiddenEnd; ++Hidden) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00003889 makeNamesVisible(Hidden->second, Hidden->first);
Guy Benyei11169dd2012-12-18 14:30:41 +00003890 }
3891 HiddenNamesMap.clear();
3892}
3893
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003894/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3895/// cursor into the start of the given block ID, returning false on success and
3896/// true on failure.
3897static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003898 while (1) {
3899 llvm::BitstreamEntry Entry = Cursor.advance();
3900 switch (Entry.Kind) {
3901 case llvm::BitstreamEntry::Error:
3902 case llvm::BitstreamEntry::EndBlock:
3903 return true;
3904
3905 case llvm::BitstreamEntry::Record:
3906 // Ignore top-level records.
3907 Cursor.skipRecord(Entry.ID);
3908 break;
3909
3910 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003911 if (Entry.ID == BlockID) {
3912 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003913 return true;
3914 // Found it!
3915 return false;
3916 }
3917
3918 if (Cursor.SkipBlock())
3919 return true;
3920 }
3921 }
3922}
3923
Guy Benyei11169dd2012-12-18 14:30:41 +00003924/// \brief Retrieve the name of the original source file name
3925/// directly from the AST file, without actually loading the AST
3926/// file.
3927std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3928 FileManager &FileMgr,
3929 DiagnosticsEngine &Diags) {
3930 // Open the AST file.
3931 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003932 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00003933 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3934 if (!Buffer) {
3935 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3936 return std::string();
3937 }
3938
3939 // Initialize the stream
3940 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003941 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003942 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3943 (const unsigned char *)Buffer->getBufferEnd());
3944 Stream.init(StreamFile);
3945
3946 // Sniff for the signature.
3947 if (Stream.Read(8) != 'C' ||
3948 Stream.Read(8) != 'P' ||
3949 Stream.Read(8) != 'C' ||
3950 Stream.Read(8) != 'H') {
3951 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3952 return std::string();
3953 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003954
Chris Lattnere7b154b2013-01-19 21:39:22 +00003955 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003956 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003957 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3958 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003959 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003960
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003961 // Scan for ORIGINAL_FILE inside the control block.
3962 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003963 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003964 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003965 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3966 return std::string();
3967
3968 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3969 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3970 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003971 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003972
Guy Benyei11169dd2012-12-18 14:30:41 +00003973 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003974 StringRef Blob;
3975 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3976 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003977 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003978}
3979
3980namespace {
3981 class SimplePCHValidator : public ASTReaderListener {
3982 const LangOptions &ExistingLangOpts;
3983 const TargetOptions &ExistingTargetOpts;
3984 const PreprocessorOptions &ExistingPPOpts;
3985 FileManager &FileMgr;
3986
3987 public:
3988 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3989 const TargetOptions &ExistingTargetOpts,
3990 const PreprocessorOptions &ExistingPPOpts,
3991 FileManager &FileMgr)
3992 : ExistingLangOpts(ExistingLangOpts),
3993 ExistingTargetOpts(ExistingTargetOpts),
3994 ExistingPPOpts(ExistingPPOpts),
3995 FileMgr(FileMgr)
3996 {
3997 }
3998
Craig Topper3e89dfe2014-03-13 02:13:41 +00003999 bool ReadLanguageOptions(const LangOptions &LangOpts,
4000 bool Complain) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004001 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004002 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004003 bool ReadTargetOptions(const TargetOptions &TargetOpts,
4004 bool Complain) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004005 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004006 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004007 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4008 bool Complain,
4009 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004010 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004011 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004012 }
4013 };
4014}
4015
4016bool ASTReader::readASTFileControlBlock(StringRef Filename,
4017 FileManager &FileMgr,
4018 ASTReaderListener &Listener) {
4019 // Open the AST file.
4020 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004021 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00004022 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
4023 if (!Buffer) {
4024 return true;
4025 }
4026
4027 // Initialize the stream
4028 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004029 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00004030 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
4031 (const unsigned char *)Buffer->getBufferEnd());
4032 Stream.init(StreamFile);
4033
4034 // Sniff for the signature.
4035 if (Stream.Read(8) != 'C' ||
4036 Stream.Read(8) != 'P' ||
4037 Stream.Read(8) != 'C' ||
4038 Stream.Read(8) != 'H') {
4039 return true;
4040 }
4041
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004042 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004043 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004044 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004045
4046 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004047 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004048 BitstreamCursor InputFilesCursor;
4049 if (NeedsInputFiles) {
4050 InputFilesCursor = Stream;
4051 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4052 return true;
4053
4054 // Read the abbreviations
4055 while (true) {
4056 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4057 unsigned Code = InputFilesCursor.ReadCode();
4058
4059 // We expect all abbrevs to be at the start of the block.
4060 if (Code != llvm::bitc::DEFINE_ABBREV) {
4061 InputFilesCursor.JumpToBit(Offset);
4062 break;
4063 }
4064 InputFilesCursor.ReadAbbrevRecord();
4065 }
4066 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004067
4068 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004069 RecordData Record;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004070 while (1) {
4071 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4072 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4073 return false;
4074
4075 if (Entry.Kind != llvm::BitstreamEntry::Record)
4076 return true;
4077
Guy Benyei11169dd2012-12-18 14:30:41 +00004078 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004079 StringRef Blob;
4080 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004081 switch ((ControlRecordTypes)RecCode) {
4082 case METADATA: {
4083 if (Record[0] != VERSION_MAJOR)
4084 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004085
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004086 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004087 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004088
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004089 break;
4090 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004091 case MODULE_NAME:
4092 Listener.ReadModuleName(Blob);
4093 break;
4094 case MODULE_MAP_FILE:
4095 Listener.ReadModuleMapFile(Blob);
4096 break;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004097 case LANGUAGE_OPTIONS:
4098 if (ParseLanguageOptions(Record, false, Listener))
4099 return true;
4100 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004101
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004102 case TARGET_OPTIONS:
4103 if (ParseTargetOptions(Record, false, Listener))
4104 return true;
4105 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004106
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004107 case DIAGNOSTIC_OPTIONS:
4108 if (ParseDiagnosticOptions(Record, false, Listener))
4109 return true;
4110 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004111
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004112 case FILE_SYSTEM_OPTIONS:
4113 if (ParseFileSystemOptions(Record, false, Listener))
4114 return true;
4115 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004116
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004117 case HEADER_SEARCH_OPTIONS:
4118 if (ParseHeaderSearchOptions(Record, false, Listener))
4119 return true;
4120 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004121
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004122 case PREPROCESSOR_OPTIONS: {
4123 std::string IgnoredSuggestedPredefines;
4124 if (ParsePreprocessorOptions(Record, false, Listener,
4125 IgnoredSuggestedPredefines))
4126 return true;
4127 break;
4128 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004129
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004130 case INPUT_FILE_OFFSETS: {
4131 if (!NeedsInputFiles)
4132 break;
4133
4134 unsigned NumInputFiles = Record[0];
4135 unsigned NumUserFiles = Record[1];
4136 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
4137 for (unsigned I = 0; I != NumInputFiles; ++I) {
4138 // Go find this input file.
4139 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004140
4141 if (isSystemFile && !NeedsSystemInputFiles)
4142 break; // the rest are system input files
4143
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004144 BitstreamCursor &Cursor = InputFilesCursor;
4145 SavedStreamPosition SavedPosition(Cursor);
4146 Cursor.JumpToBit(InputFileOffs[I]);
4147
4148 unsigned Code = Cursor.ReadCode();
4149 RecordData Record;
4150 StringRef Blob;
4151 bool shouldContinue = false;
4152 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4153 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004154 bool Overridden = static_cast<bool>(Record[3]);
4155 shouldContinue = Listener.visitInputFile(Blob, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004156 break;
4157 }
4158 if (!shouldContinue)
4159 break;
4160 }
4161 break;
4162 }
4163
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004164 default:
4165 // No other validation to perform.
4166 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004167 }
4168 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004169}
4170
4171
4172bool ASTReader::isAcceptableASTFile(StringRef Filename,
4173 FileManager &FileMgr,
4174 const LangOptions &LangOpts,
4175 const TargetOptions &TargetOpts,
4176 const PreprocessorOptions &PPOpts) {
4177 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
4178 return !readASTFileControlBlock(Filename, FileMgr, validator);
4179}
4180
Ben Langmuir2c9af442014-04-10 17:57:43 +00004181ASTReader::ASTReadResult
4182ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004183 // Enter the submodule block.
4184 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4185 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004186 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004187 }
4188
4189 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4190 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004191 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004192 RecordData Record;
4193 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004194 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4195
4196 switch (Entry.Kind) {
4197 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4198 case llvm::BitstreamEntry::Error:
4199 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004200 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004201 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004202 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004203 case llvm::BitstreamEntry::Record:
4204 // The interesting case.
4205 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004206 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004207
Guy Benyei11169dd2012-12-18 14:30:41 +00004208 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004209 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004210 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004211 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004212 default: // Default behavior: ignore.
4213 break;
4214
4215 case SUBMODULE_DEFINITION: {
4216 if (First) {
4217 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004218 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004219 }
4220
Douglas Gregor8d932422013-03-20 03:59:18 +00004221 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004222 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004223 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004224 }
4225
Chris Lattner0e6c9402013-01-20 02:38:54 +00004226 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004227 unsigned Idx = 0;
4228 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4229 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4230 bool IsFramework = Record[Idx++];
4231 bool IsExplicit = Record[Idx++];
4232 bool IsSystem = Record[Idx++];
4233 bool IsExternC = Record[Idx++];
4234 bool InferSubmodules = Record[Idx++];
4235 bool InferExplicitSubmodules = Record[Idx++];
4236 bool InferExportWildcard = Record[Idx++];
4237 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004238
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004239 Module *ParentModule = nullptr;
4240 const FileEntry *ModuleMap = nullptr;
4241 if (Parent) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004242 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004243 ModuleMap = ParentModule->ModuleMap;
4244 }
4245
4246 if (!F.ModuleMapPath.empty())
4247 ModuleMap = FileMgr.getFile(F.ModuleMapPath);
4248
Guy Benyei11169dd2012-12-18 14:30:41 +00004249 // Retrieve this (sub)module from the module map, creating it if
4250 // necessary.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004251 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, ModuleMap,
Guy Benyei11169dd2012-12-18 14:30:41 +00004252 IsFramework,
4253 IsExplicit).first;
4254 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4255 if (GlobalIndex >= SubmodulesLoaded.size() ||
4256 SubmodulesLoaded[GlobalIndex]) {
4257 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004258 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004259 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004260
Douglas Gregor7029ce12013-03-19 00:28:20 +00004261 if (!ParentModule) {
4262 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4263 if (CurFile != F.File) {
4264 if (!Diags.isDiagnosticInFlight()) {
4265 Diag(diag::err_module_file_conflict)
4266 << CurrentModule->getTopLevelModuleName()
4267 << CurFile->getName()
4268 << F.File->getName();
4269 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004270 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004271 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004272 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004273
4274 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004275 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004276
Guy Benyei11169dd2012-12-18 14:30:41 +00004277 CurrentModule->IsFromModuleFile = true;
4278 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004279 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004280 CurrentModule->InferSubmodules = InferSubmodules;
4281 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4282 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004283 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004284 if (DeserializationListener)
4285 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4286
4287 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004288
Douglas Gregorfb912652013-03-20 21:10:35 +00004289 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004290 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004291 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004292 CurrentModule->UnresolvedConflicts.clear();
4293 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004294 break;
4295 }
4296
4297 case SUBMODULE_UMBRELLA_HEADER: {
4298 if (First) {
4299 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004300 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004301 }
4302
4303 if (!CurrentModule)
4304 break;
4305
Chris Lattner0e6c9402013-01-20 02:38:54 +00004306 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004307 if (!CurrentModule->getUmbrellaHeader())
4308 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4309 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004310 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4311 Error("mismatched umbrella headers in submodule");
4312 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004313 }
4314 }
4315 break;
4316 }
4317
4318 case SUBMODULE_HEADER: {
4319 if (First) {
4320 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004321 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004322 }
4323
4324 if (!CurrentModule)
4325 break;
4326
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004327 // We lazily associate headers with their modules via the HeaderInfoTable.
4328 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4329 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004330 break;
4331 }
4332
4333 case SUBMODULE_EXCLUDED_HEADER: {
4334 if (First) {
4335 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004336 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004337 }
4338
4339 if (!CurrentModule)
4340 break;
4341
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004342 // We lazily associate headers with their modules via the HeaderInfoTable.
4343 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4344 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004345 break;
4346 }
4347
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004348 case SUBMODULE_PRIVATE_HEADER: {
4349 if (First) {
4350 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004351 return Failure;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004352 }
4353
4354 if (!CurrentModule)
4355 break;
4356
4357 // We lazily associate headers with their modules via the HeaderInfoTable.
4358 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4359 // of complete filenames or remove it entirely.
4360 break;
4361 }
4362
Guy Benyei11169dd2012-12-18 14:30:41 +00004363 case SUBMODULE_TOPHEADER: {
4364 if (First) {
4365 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004366 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004367 }
4368
4369 if (!CurrentModule)
4370 break;
4371
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004372 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004373 break;
4374 }
4375
4376 case SUBMODULE_UMBRELLA_DIR: {
4377 if (First) {
4378 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004379 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004380 }
4381
4382 if (!CurrentModule)
4383 break;
4384
Guy Benyei11169dd2012-12-18 14:30:41 +00004385 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004386 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004387 if (!CurrentModule->getUmbrellaDir())
4388 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4389 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004390 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4391 Error("mismatched umbrella directories in submodule");
4392 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004393 }
4394 }
4395 break;
4396 }
4397
4398 case SUBMODULE_METADATA: {
4399 if (!First) {
4400 Error("submodule metadata record not at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004401 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004402 }
4403 First = false;
4404
4405 F.BaseSubmoduleID = getTotalNumSubmodules();
4406 F.LocalNumSubmodules = Record[0];
4407 unsigned LocalBaseSubmoduleID = Record[1];
4408 if (F.LocalNumSubmodules > 0) {
4409 // Introduce the global -> local mapping for submodules within this
4410 // module.
4411 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4412
4413 // Introduce the local -> global mapping for submodules within this
4414 // module.
4415 F.SubmoduleRemap.insertOrReplace(
4416 std::make_pair(LocalBaseSubmoduleID,
4417 F.BaseSubmoduleID - LocalBaseSubmoduleID));
4418
4419 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4420 }
4421 break;
4422 }
4423
4424 case SUBMODULE_IMPORTS: {
4425 if (First) {
4426 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004427 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004428 }
4429
4430 if (!CurrentModule)
4431 break;
4432
4433 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004434 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004435 Unresolved.File = &F;
4436 Unresolved.Mod = CurrentModule;
4437 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004438 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004439 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004440 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004441 }
4442 break;
4443 }
4444
4445 case SUBMODULE_EXPORTS: {
4446 if (First) {
4447 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004448 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004449 }
4450
4451 if (!CurrentModule)
4452 break;
4453
4454 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004455 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004456 Unresolved.File = &F;
4457 Unresolved.Mod = CurrentModule;
4458 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004459 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004460 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004461 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004462 }
4463
4464 // Once we've loaded the set of exports, there's no reason to keep
4465 // the parsed, unresolved exports around.
4466 CurrentModule->UnresolvedExports.clear();
4467 break;
4468 }
4469 case SUBMODULE_REQUIRES: {
4470 if (First) {
4471 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004472 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004473 }
4474
4475 if (!CurrentModule)
4476 break;
4477
Richard Smitha3feee22013-10-28 22:18:19 +00004478 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004479 Context.getTargetInfo());
4480 break;
4481 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004482
4483 case SUBMODULE_LINK_LIBRARY:
4484 if (First) {
4485 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004486 return Failure;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004487 }
4488
4489 if (!CurrentModule)
4490 break;
4491
4492 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004493 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004494 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004495
4496 case SUBMODULE_CONFIG_MACRO:
4497 if (First) {
4498 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004499 return Failure;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004500 }
4501
4502 if (!CurrentModule)
4503 break;
4504
4505 CurrentModule->ConfigMacros.push_back(Blob.str());
4506 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004507
4508 case SUBMODULE_CONFLICT: {
4509 if (First) {
4510 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004511 return Failure;
Douglas Gregorfb912652013-03-20 21:10:35 +00004512 }
4513
4514 if (!CurrentModule)
4515 break;
4516
4517 UnresolvedModuleRef Unresolved;
4518 Unresolved.File = &F;
4519 Unresolved.Mod = CurrentModule;
4520 Unresolved.ID = Record[0];
4521 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4522 Unresolved.IsWildcard = false;
4523 Unresolved.String = Blob;
4524 UnresolvedModuleRefs.push_back(Unresolved);
4525 break;
4526 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004527 }
4528 }
4529}
4530
4531/// \brief Parse the record that corresponds to a LangOptions data
4532/// structure.
4533///
4534/// This routine parses the language options from the AST file and then gives
4535/// them to the AST listener if one is set.
4536///
4537/// \returns true if the listener deems the file unacceptable, false otherwise.
4538bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4539 bool Complain,
4540 ASTReaderListener &Listener) {
4541 LangOptions LangOpts;
4542 unsigned Idx = 0;
4543#define LANGOPT(Name, Bits, Default, Description) \
4544 LangOpts.Name = Record[Idx++];
4545#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4546 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4547#include "clang/Basic/LangOptions.def"
Will Dietzf54319c2013-01-18 11:30:38 +00004548#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
4549#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004550
4551 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4552 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4553 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4554
4555 unsigned Length = Record[Idx++];
4556 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4557 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004558
4559 Idx += Length;
4560
4561 // Comment options.
4562 for (unsigned N = Record[Idx++]; N; --N) {
4563 LangOpts.CommentOpts.BlockCommandNames.push_back(
4564 ReadString(Record, Idx));
4565 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004566 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004567
Guy Benyei11169dd2012-12-18 14:30:41 +00004568 return Listener.ReadLanguageOptions(LangOpts, Complain);
4569}
4570
4571bool ASTReader::ParseTargetOptions(const RecordData &Record,
4572 bool Complain,
4573 ASTReaderListener &Listener) {
4574 unsigned Idx = 0;
4575 TargetOptions TargetOpts;
4576 TargetOpts.Triple = ReadString(Record, Idx);
4577 TargetOpts.CPU = ReadString(Record, Idx);
4578 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004579 for (unsigned N = Record[Idx++]; N; --N) {
4580 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4581 }
4582 for (unsigned N = Record[Idx++]; N; --N) {
4583 TargetOpts.Features.push_back(ReadString(Record, Idx));
4584 }
4585
4586 return Listener.ReadTargetOptions(TargetOpts, Complain);
4587}
4588
4589bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4590 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004591 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004592 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004593#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004594#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004595 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004596#include "clang/Basic/DiagnosticOptions.def"
4597
4598 for (unsigned N = Record[Idx++]; N; --N) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004599 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004600 }
4601
4602 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4603}
4604
4605bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4606 ASTReaderListener &Listener) {
4607 FileSystemOptions FSOpts;
4608 unsigned Idx = 0;
4609 FSOpts.WorkingDir = ReadString(Record, Idx);
4610 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4611}
4612
4613bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4614 bool Complain,
4615 ASTReaderListener &Listener) {
4616 HeaderSearchOptions HSOpts;
4617 unsigned Idx = 0;
4618 HSOpts.Sysroot = ReadString(Record, Idx);
4619
4620 // Include entries.
4621 for (unsigned N = Record[Idx++]; N; --N) {
4622 std::string Path = ReadString(Record, Idx);
4623 frontend::IncludeDirGroup Group
4624 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004625 bool IsFramework = Record[Idx++];
4626 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004627 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004628 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004629 }
4630
4631 // System header prefixes.
4632 for (unsigned N = Record[Idx++]; N; --N) {
4633 std::string Prefix = ReadString(Record, Idx);
4634 bool IsSystemHeader = Record[Idx++];
4635 HSOpts.SystemHeaderPrefixes.push_back(
4636 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4637 }
4638
4639 HSOpts.ResourceDir = ReadString(Record, Idx);
4640 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004641 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004642 HSOpts.DisableModuleHash = Record[Idx++];
4643 HSOpts.UseBuiltinIncludes = Record[Idx++];
4644 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4645 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4646 HSOpts.UseLibcxx = Record[Idx++];
4647
4648 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4649}
4650
4651bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4652 bool Complain,
4653 ASTReaderListener &Listener,
4654 std::string &SuggestedPredefines) {
4655 PreprocessorOptions PPOpts;
4656 unsigned Idx = 0;
4657
4658 // Macro definitions/undefs
4659 for (unsigned N = Record[Idx++]; N; --N) {
4660 std::string Macro = ReadString(Record, Idx);
4661 bool IsUndef = Record[Idx++];
4662 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4663 }
4664
4665 // Includes
4666 for (unsigned N = Record[Idx++]; N; --N) {
4667 PPOpts.Includes.push_back(ReadString(Record, Idx));
4668 }
4669
4670 // Macro Includes
4671 for (unsigned N = Record[Idx++]; N; --N) {
4672 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4673 }
4674
4675 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004676 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004677 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4678 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4679 PPOpts.ObjCXXARCStandardLibrary =
4680 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4681 SuggestedPredefines.clear();
4682 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4683 SuggestedPredefines);
4684}
4685
4686std::pair<ModuleFile *, unsigned>
4687ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4688 GlobalPreprocessedEntityMapType::iterator
4689 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4690 assert(I != GlobalPreprocessedEntityMap.end() &&
4691 "Corrupted global preprocessed entity map");
4692 ModuleFile *M = I->second;
4693 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4694 return std::make_pair(M, LocalIndex);
4695}
4696
4697std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4698ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4699 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4700 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4701 Mod.NumPreprocessedEntities);
4702
4703 return std::make_pair(PreprocessingRecord::iterator(),
4704 PreprocessingRecord::iterator());
4705}
4706
4707std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4708ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4709 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4710 ModuleDeclIterator(this, &Mod,
4711 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4712}
4713
4714PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4715 PreprocessedEntityID PPID = Index+1;
4716 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4717 ModuleFile &M = *PPInfo.first;
4718 unsigned LocalIndex = PPInfo.second;
4719 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4720
Guy Benyei11169dd2012-12-18 14:30:41 +00004721 if (!PP.getPreprocessingRecord()) {
4722 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004723 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004724 }
4725
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004726 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4727 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4728
4729 llvm::BitstreamEntry Entry =
4730 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4731 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004732 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004733
Guy Benyei11169dd2012-12-18 14:30:41 +00004734 // Read the record.
4735 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4736 ReadSourceLocation(M, PPOffs.End));
4737 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004738 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004739 RecordData Record;
4740 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004741 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4742 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004743 switch (RecType) {
4744 case PPD_MACRO_EXPANSION: {
4745 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004746 IdentifierInfo *Name = nullptr;
4747 MacroDefinition *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004748 if (isBuiltin)
4749 Name = getLocalIdentifier(M, Record[1]);
4750 else {
4751 PreprocessedEntityID
4752 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4753 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4754 }
4755
4756 MacroExpansion *ME;
4757 if (isBuiltin)
4758 ME = new (PPRec) MacroExpansion(Name, Range);
4759 else
4760 ME = new (PPRec) MacroExpansion(Def, Range);
4761
4762 return ME;
4763 }
4764
4765 case PPD_MACRO_DEFINITION: {
4766 // Decode the identifier info and then check again; if the macro is
4767 // still defined and associated with the identifier,
4768 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4769 MacroDefinition *MD
4770 = new (PPRec) MacroDefinition(II, Range);
4771
4772 if (DeserializationListener)
4773 DeserializationListener->MacroDefinitionRead(PPID, MD);
4774
4775 return MD;
4776 }
4777
4778 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004779 const char *FullFileNameStart = Blob.data() + Record[0];
4780 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004781 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004782 if (!FullFileName.empty())
4783 File = PP.getFileManager().getFile(FullFileName);
4784
4785 // FIXME: Stable encoding
4786 InclusionDirective::InclusionKind Kind
4787 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4788 InclusionDirective *ID
4789 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004790 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004791 Record[1], Record[3],
4792 File,
4793 Range);
4794 return ID;
4795 }
4796 }
4797
4798 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4799}
4800
4801/// \brief \arg SLocMapI points at a chunk of a module that contains no
4802/// preprocessed entities or the entities it contains are not the ones we are
4803/// looking for. Find the next module that contains entities and return the ID
4804/// of the first entry.
4805PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4806 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4807 ++SLocMapI;
4808 for (GlobalSLocOffsetMapType::const_iterator
4809 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4810 ModuleFile &M = *SLocMapI->second;
4811 if (M.NumPreprocessedEntities)
4812 return M.BasePreprocessedEntityID;
4813 }
4814
4815 return getTotalNumPreprocessedEntities();
4816}
4817
4818namespace {
4819
4820template <unsigned PPEntityOffset::*PPLoc>
4821struct PPEntityComp {
4822 const ASTReader &Reader;
4823 ModuleFile &M;
4824
4825 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4826
4827 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4828 SourceLocation LHS = getLoc(L);
4829 SourceLocation RHS = getLoc(R);
4830 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4831 }
4832
4833 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4834 SourceLocation LHS = getLoc(L);
4835 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4836 }
4837
4838 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4839 SourceLocation RHS = getLoc(R);
4840 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4841 }
4842
4843 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4844 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4845 }
4846};
4847
4848}
4849
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004850PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4851 bool EndsAfter) const {
4852 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004853 return getTotalNumPreprocessedEntities();
4854
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004855 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4856 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004857 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4858 "Corrupted global sloc offset map");
4859
4860 if (SLocMapI->second->NumPreprocessedEntities == 0)
4861 return findNextPreprocessedEntity(SLocMapI);
4862
4863 ModuleFile &M = *SLocMapI->second;
4864 typedef const PPEntityOffset *pp_iterator;
4865 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4866 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4867
4868 size_t Count = M.NumPreprocessedEntities;
4869 size_t Half;
4870 pp_iterator First = pp_begin;
4871 pp_iterator PPI;
4872
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004873 if (EndsAfter) {
4874 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4875 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4876 } else {
4877 // Do a binary search manually instead of using std::lower_bound because
4878 // The end locations of entities may be unordered (when a macro expansion
4879 // is inside another macro argument), but for this case it is not important
4880 // whether we get the first macro expansion or its containing macro.
4881 while (Count > 0) {
4882 Half = Count / 2;
4883 PPI = First;
4884 std::advance(PPI, Half);
4885 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4886 Loc)) {
4887 First = PPI;
4888 ++First;
4889 Count = Count - Half - 1;
4890 } else
4891 Count = Half;
4892 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004893 }
4894
4895 if (PPI == pp_end)
4896 return findNextPreprocessedEntity(SLocMapI);
4897
4898 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4899}
4900
Guy Benyei11169dd2012-12-18 14:30:41 +00004901/// \brief Returns a pair of [Begin, End) indices of preallocated
4902/// preprocessed entities that \arg Range encompasses.
4903std::pair<unsigned, unsigned>
4904 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4905 if (Range.isInvalid())
4906 return std::make_pair(0,0);
4907 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4908
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004909 PreprocessedEntityID BeginID =
4910 findPreprocessedEntity(Range.getBegin(), false);
4911 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004912 return std::make_pair(BeginID, EndID);
4913}
4914
4915/// \brief Optionally returns true or false if the preallocated preprocessed
4916/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004917Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004918 FileID FID) {
4919 if (FID.isInvalid())
4920 return false;
4921
4922 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4923 ModuleFile &M = *PPInfo.first;
4924 unsigned LocalIndex = PPInfo.second;
4925 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4926
4927 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4928 if (Loc.isInvalid())
4929 return false;
4930
4931 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4932 return true;
4933 else
4934 return false;
4935}
4936
4937namespace {
4938 /// \brief Visitor used to search for information about a header file.
4939 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004940 const FileEntry *FE;
4941
David Blaikie05785d12013-02-20 22:23:23 +00004942 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004943
4944 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004945 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4946 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004947
4948 static bool visit(ModuleFile &M, void *UserData) {
4949 HeaderFileInfoVisitor *This
4950 = static_cast<HeaderFileInfoVisitor *>(UserData);
4951
Guy Benyei11169dd2012-12-18 14:30:41 +00004952 HeaderFileInfoLookupTable *Table
4953 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4954 if (!Table)
4955 return false;
4956
4957 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00004958 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004959 if (Pos == Table->end())
4960 return false;
4961
4962 This->HFI = *Pos;
4963 return true;
4964 }
4965
David Blaikie05785d12013-02-20 22:23:23 +00004966 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004967 };
4968}
4969
4970HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004971 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004972 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004973 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004974 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004975
4976 return HeaderFileInfo();
4977}
4978
4979void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4980 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004981 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004982 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4983 ModuleFile &F = *(*I);
4984 unsigned Idx = 0;
4985 DiagStates.clear();
4986 assert(!Diag.DiagStates.empty());
4987 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4988 while (Idx < F.PragmaDiagMappings.size()) {
4989 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4990 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4991 if (DiagStateID != 0) {
4992 Diag.DiagStatePoints.push_back(
4993 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4994 FullSourceLoc(Loc, SourceMgr)));
4995 continue;
4996 }
4997
4998 assert(DiagStateID == 0);
4999 // A new DiagState was created here.
5000 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5001 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5002 DiagStates.push_back(NewState);
5003 Diag.DiagStatePoints.push_back(
5004 DiagnosticsEngine::DiagStatePoint(NewState,
5005 FullSourceLoc(Loc, SourceMgr)));
5006 while (1) {
5007 assert(Idx < F.PragmaDiagMappings.size() &&
5008 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5009 if (Idx >= F.PragmaDiagMappings.size()) {
5010 break; // Something is messed up but at least avoid infinite loop in
5011 // release build.
5012 }
5013 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5014 if (DiagID == (unsigned)-1) {
5015 break; // no more diag/map pairs for this location.
5016 }
5017 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
5018 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
5019 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
5020 }
5021 }
5022 }
5023}
5024
5025/// \brief Get the correct cursor and offset for loading a type.
5026ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5027 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5028 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5029 ModuleFile *M = I->second;
5030 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5031}
5032
5033/// \brief Read and return the type with the given index..
5034///
5035/// The index is the type ID, shifted and minus the number of predefs. This
5036/// routine actually reads the record corresponding to the type at the given
5037/// location. It is a helper routine for GetType, which deals with reading type
5038/// IDs.
5039QualType ASTReader::readTypeRecord(unsigned Index) {
5040 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005041 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005042
5043 // Keep track of where we are in the stream, then jump back there
5044 // after reading this type.
5045 SavedStreamPosition SavedPosition(DeclsCursor);
5046
5047 ReadingKindTracker ReadingKind(Read_Type, *this);
5048
5049 // Note that we are loading a type record.
5050 Deserializing AType(this);
5051
5052 unsigned Idx = 0;
5053 DeclsCursor.JumpToBit(Loc.Offset);
5054 RecordData Record;
5055 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005056 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005057 case TYPE_EXT_QUAL: {
5058 if (Record.size() != 2) {
5059 Error("Incorrect encoding of extended qualifier type");
5060 return QualType();
5061 }
5062 QualType Base = readType(*Loc.F, Record, Idx);
5063 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5064 return Context.getQualifiedType(Base, Quals);
5065 }
5066
5067 case TYPE_COMPLEX: {
5068 if (Record.size() != 1) {
5069 Error("Incorrect encoding of complex type");
5070 return QualType();
5071 }
5072 QualType ElemType = readType(*Loc.F, Record, Idx);
5073 return Context.getComplexType(ElemType);
5074 }
5075
5076 case TYPE_POINTER: {
5077 if (Record.size() != 1) {
5078 Error("Incorrect encoding of pointer type");
5079 return QualType();
5080 }
5081 QualType PointeeType = readType(*Loc.F, Record, Idx);
5082 return Context.getPointerType(PointeeType);
5083 }
5084
Reid Kleckner8a365022013-06-24 17:51:48 +00005085 case TYPE_DECAYED: {
5086 if (Record.size() != 1) {
5087 Error("Incorrect encoding of decayed type");
5088 return QualType();
5089 }
5090 QualType OriginalType = readType(*Loc.F, Record, Idx);
5091 QualType DT = Context.getAdjustedParameterType(OriginalType);
5092 if (!isa<DecayedType>(DT))
5093 Error("Decayed type does not decay");
5094 return DT;
5095 }
5096
Reid Kleckner0503a872013-12-05 01:23:43 +00005097 case TYPE_ADJUSTED: {
5098 if (Record.size() != 2) {
5099 Error("Incorrect encoding of adjusted type");
5100 return QualType();
5101 }
5102 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5103 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5104 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5105 }
5106
Guy Benyei11169dd2012-12-18 14:30:41 +00005107 case TYPE_BLOCK_POINTER: {
5108 if (Record.size() != 1) {
5109 Error("Incorrect encoding of block pointer type");
5110 return QualType();
5111 }
5112 QualType PointeeType = readType(*Loc.F, Record, Idx);
5113 return Context.getBlockPointerType(PointeeType);
5114 }
5115
5116 case TYPE_LVALUE_REFERENCE: {
5117 if (Record.size() != 2) {
5118 Error("Incorrect encoding of lvalue reference type");
5119 return QualType();
5120 }
5121 QualType PointeeType = readType(*Loc.F, Record, Idx);
5122 return Context.getLValueReferenceType(PointeeType, Record[1]);
5123 }
5124
5125 case TYPE_RVALUE_REFERENCE: {
5126 if (Record.size() != 1) {
5127 Error("Incorrect encoding of rvalue reference type");
5128 return QualType();
5129 }
5130 QualType PointeeType = readType(*Loc.F, Record, Idx);
5131 return Context.getRValueReferenceType(PointeeType);
5132 }
5133
5134 case TYPE_MEMBER_POINTER: {
5135 if (Record.size() != 2) {
5136 Error("Incorrect encoding of member pointer type");
5137 return QualType();
5138 }
5139 QualType PointeeType = readType(*Loc.F, Record, Idx);
5140 QualType ClassType = readType(*Loc.F, Record, Idx);
5141 if (PointeeType.isNull() || ClassType.isNull())
5142 return QualType();
5143
5144 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5145 }
5146
5147 case TYPE_CONSTANT_ARRAY: {
5148 QualType ElementType = readType(*Loc.F, Record, Idx);
5149 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5150 unsigned IndexTypeQuals = Record[2];
5151 unsigned Idx = 3;
5152 llvm::APInt Size = ReadAPInt(Record, Idx);
5153 return Context.getConstantArrayType(ElementType, Size,
5154 ASM, IndexTypeQuals);
5155 }
5156
5157 case TYPE_INCOMPLETE_ARRAY: {
5158 QualType ElementType = readType(*Loc.F, Record, Idx);
5159 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5160 unsigned IndexTypeQuals = Record[2];
5161 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5162 }
5163
5164 case TYPE_VARIABLE_ARRAY: {
5165 QualType ElementType = readType(*Loc.F, Record, Idx);
5166 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5167 unsigned IndexTypeQuals = Record[2];
5168 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5169 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5170 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5171 ASM, IndexTypeQuals,
5172 SourceRange(LBLoc, RBLoc));
5173 }
5174
5175 case TYPE_VECTOR: {
5176 if (Record.size() != 3) {
5177 Error("incorrect encoding of vector type in AST file");
5178 return QualType();
5179 }
5180
5181 QualType ElementType = readType(*Loc.F, Record, Idx);
5182 unsigned NumElements = Record[1];
5183 unsigned VecKind = Record[2];
5184 return Context.getVectorType(ElementType, NumElements,
5185 (VectorType::VectorKind)VecKind);
5186 }
5187
5188 case TYPE_EXT_VECTOR: {
5189 if (Record.size() != 3) {
5190 Error("incorrect encoding of extended vector type in AST file");
5191 return QualType();
5192 }
5193
5194 QualType ElementType = readType(*Loc.F, Record, Idx);
5195 unsigned NumElements = Record[1];
5196 return Context.getExtVectorType(ElementType, NumElements);
5197 }
5198
5199 case TYPE_FUNCTION_NO_PROTO: {
5200 if (Record.size() != 6) {
5201 Error("incorrect encoding of no-proto function type");
5202 return QualType();
5203 }
5204 QualType ResultType = readType(*Loc.F, Record, Idx);
5205 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5206 (CallingConv)Record[4], Record[5]);
5207 return Context.getFunctionNoProtoType(ResultType, Info);
5208 }
5209
5210 case TYPE_FUNCTION_PROTO: {
5211 QualType ResultType = readType(*Loc.F, Record, Idx);
5212
5213 FunctionProtoType::ExtProtoInfo EPI;
5214 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5215 /*hasregparm*/ Record[2],
5216 /*regparm*/ Record[3],
5217 static_cast<CallingConv>(Record[4]),
5218 /*produces*/ Record[5]);
5219
5220 unsigned Idx = 6;
5221 unsigned NumParams = Record[Idx++];
5222 SmallVector<QualType, 16> ParamTypes;
5223 for (unsigned I = 0; I != NumParams; ++I)
5224 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5225
5226 EPI.Variadic = Record[Idx++];
5227 EPI.HasTrailingReturn = Record[Idx++];
5228 EPI.TypeQuals = Record[Idx++];
5229 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005230 SmallVector<QualType, 8> ExceptionStorage;
5231 readExceptionSpec(*Loc.F, ExceptionStorage, EPI, Record, Idx);
Jordan Rose5c382722013-03-08 21:51:21 +00005232 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005233 }
5234
5235 case TYPE_UNRESOLVED_USING: {
5236 unsigned Idx = 0;
5237 return Context.getTypeDeclType(
5238 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5239 }
5240
5241 case TYPE_TYPEDEF: {
5242 if (Record.size() != 2) {
5243 Error("incorrect encoding of typedef type");
5244 return QualType();
5245 }
5246 unsigned Idx = 0;
5247 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5248 QualType Canonical = readType(*Loc.F, Record, Idx);
5249 if (!Canonical.isNull())
5250 Canonical = Context.getCanonicalType(Canonical);
5251 return Context.getTypedefType(Decl, Canonical);
5252 }
5253
5254 case TYPE_TYPEOF_EXPR:
5255 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5256
5257 case TYPE_TYPEOF: {
5258 if (Record.size() != 1) {
5259 Error("incorrect encoding of typeof(type) in AST file");
5260 return QualType();
5261 }
5262 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5263 return Context.getTypeOfType(UnderlyingType);
5264 }
5265
5266 case TYPE_DECLTYPE: {
5267 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5268 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5269 }
5270
5271 case TYPE_UNARY_TRANSFORM: {
5272 QualType BaseType = readType(*Loc.F, Record, Idx);
5273 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5274 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5275 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5276 }
5277
Richard Smith74aeef52013-04-26 16:15:35 +00005278 case TYPE_AUTO: {
5279 QualType Deduced = readType(*Loc.F, Record, Idx);
5280 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005281 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005282 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005283 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005284
5285 case TYPE_RECORD: {
5286 if (Record.size() != 2) {
5287 Error("incorrect encoding of record type");
5288 return QualType();
5289 }
5290 unsigned Idx = 0;
5291 bool IsDependent = Record[Idx++];
5292 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5293 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5294 QualType T = Context.getRecordType(RD);
5295 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5296 return T;
5297 }
5298
5299 case TYPE_ENUM: {
5300 if (Record.size() != 2) {
5301 Error("incorrect encoding of enum type");
5302 return QualType();
5303 }
5304 unsigned Idx = 0;
5305 bool IsDependent = Record[Idx++];
5306 QualType T
5307 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5308 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5309 return T;
5310 }
5311
5312 case TYPE_ATTRIBUTED: {
5313 if (Record.size() != 3) {
5314 Error("incorrect encoding of attributed type");
5315 return QualType();
5316 }
5317 QualType modifiedType = readType(*Loc.F, Record, Idx);
5318 QualType equivalentType = readType(*Loc.F, Record, Idx);
5319 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5320 return Context.getAttributedType(kind, modifiedType, equivalentType);
5321 }
5322
5323 case TYPE_PAREN: {
5324 if (Record.size() != 1) {
5325 Error("incorrect encoding of paren type");
5326 return QualType();
5327 }
5328 QualType InnerType = readType(*Loc.F, Record, Idx);
5329 return Context.getParenType(InnerType);
5330 }
5331
5332 case TYPE_PACK_EXPANSION: {
5333 if (Record.size() != 2) {
5334 Error("incorrect encoding of pack expansion type");
5335 return QualType();
5336 }
5337 QualType Pattern = readType(*Loc.F, Record, Idx);
5338 if (Pattern.isNull())
5339 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005340 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005341 if (Record[1])
5342 NumExpansions = Record[1] - 1;
5343 return Context.getPackExpansionType(Pattern, NumExpansions);
5344 }
5345
5346 case TYPE_ELABORATED: {
5347 unsigned Idx = 0;
5348 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5349 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5350 QualType NamedType = readType(*Loc.F, Record, Idx);
5351 return Context.getElaboratedType(Keyword, NNS, NamedType);
5352 }
5353
5354 case TYPE_OBJC_INTERFACE: {
5355 unsigned Idx = 0;
5356 ObjCInterfaceDecl *ItfD
5357 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5358 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5359 }
5360
5361 case TYPE_OBJC_OBJECT: {
5362 unsigned Idx = 0;
5363 QualType Base = readType(*Loc.F, Record, Idx);
5364 unsigned NumProtos = Record[Idx++];
5365 SmallVector<ObjCProtocolDecl*, 4> Protos;
5366 for (unsigned I = 0; I != NumProtos; ++I)
5367 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5368 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5369 }
5370
5371 case TYPE_OBJC_OBJECT_POINTER: {
5372 unsigned Idx = 0;
5373 QualType Pointee = readType(*Loc.F, Record, Idx);
5374 return Context.getObjCObjectPointerType(Pointee);
5375 }
5376
5377 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5378 unsigned Idx = 0;
5379 QualType Parm = readType(*Loc.F, Record, Idx);
5380 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005381 return Context.getSubstTemplateTypeParmType(
5382 cast<TemplateTypeParmType>(Parm),
5383 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005384 }
5385
5386 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5387 unsigned Idx = 0;
5388 QualType Parm = readType(*Loc.F, Record, Idx);
5389 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5390 return Context.getSubstTemplateTypeParmPackType(
5391 cast<TemplateTypeParmType>(Parm),
5392 ArgPack);
5393 }
5394
5395 case TYPE_INJECTED_CLASS_NAME: {
5396 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5397 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5398 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5399 // for AST reading, too much interdependencies.
Richard Smithf17fdbd2014-04-24 02:25:27 +00005400 const Type *T;
5401 if (const Type *Existing = D->getTypeForDecl())
5402 T = Existing;
5403 else if (auto *Prev = D->getPreviousDecl())
5404 T = Prev->getTypeForDecl();
5405 else
5406 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
5407 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005408 }
5409
5410 case TYPE_TEMPLATE_TYPE_PARM: {
5411 unsigned Idx = 0;
5412 unsigned Depth = Record[Idx++];
5413 unsigned Index = Record[Idx++];
5414 bool Pack = Record[Idx++];
5415 TemplateTypeParmDecl *D
5416 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5417 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5418 }
5419
5420 case TYPE_DEPENDENT_NAME: {
5421 unsigned Idx = 0;
5422 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5423 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5424 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5425 QualType Canon = readType(*Loc.F, Record, Idx);
5426 if (!Canon.isNull())
5427 Canon = Context.getCanonicalType(Canon);
5428 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5429 }
5430
5431 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5432 unsigned Idx = 0;
5433 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5434 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5435 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5436 unsigned NumArgs = Record[Idx++];
5437 SmallVector<TemplateArgument, 8> Args;
5438 Args.reserve(NumArgs);
5439 while (NumArgs--)
5440 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5441 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5442 Args.size(), Args.data());
5443 }
5444
5445 case TYPE_DEPENDENT_SIZED_ARRAY: {
5446 unsigned Idx = 0;
5447
5448 // ArrayType
5449 QualType ElementType = readType(*Loc.F, Record, Idx);
5450 ArrayType::ArraySizeModifier ASM
5451 = (ArrayType::ArraySizeModifier)Record[Idx++];
5452 unsigned IndexTypeQuals = Record[Idx++];
5453
5454 // DependentSizedArrayType
5455 Expr *NumElts = ReadExpr(*Loc.F);
5456 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5457
5458 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5459 IndexTypeQuals, Brackets);
5460 }
5461
5462 case TYPE_TEMPLATE_SPECIALIZATION: {
5463 unsigned Idx = 0;
5464 bool IsDependent = Record[Idx++];
5465 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5466 SmallVector<TemplateArgument, 8> Args;
5467 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5468 QualType Underlying = readType(*Loc.F, Record, Idx);
5469 QualType T;
5470 if (Underlying.isNull())
5471 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5472 Args.size());
5473 else
5474 T = Context.getTemplateSpecializationType(Name, Args.data(),
5475 Args.size(), Underlying);
5476 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5477 return T;
5478 }
5479
5480 case TYPE_ATOMIC: {
5481 if (Record.size() != 1) {
5482 Error("Incorrect encoding of atomic type");
5483 return QualType();
5484 }
5485 QualType ValueType = readType(*Loc.F, Record, Idx);
5486 return Context.getAtomicType(ValueType);
5487 }
5488 }
5489 llvm_unreachable("Invalid TypeCode!");
5490}
5491
Richard Smith564417a2014-03-20 21:47:22 +00005492void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5493 SmallVectorImpl<QualType> &Exceptions,
5494 FunctionProtoType::ExtProtoInfo &EPI,
5495 const RecordData &Record, unsigned &Idx) {
5496 ExceptionSpecificationType EST =
5497 static_cast<ExceptionSpecificationType>(Record[Idx++]);
5498 EPI.ExceptionSpecType = EST;
5499 if (EST == EST_Dynamic) {
5500 EPI.NumExceptions = Record[Idx++];
5501 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
5502 Exceptions.push_back(readType(ModuleFile, Record, Idx));
5503 EPI.Exceptions = Exceptions.data();
5504 } else if (EST == EST_ComputedNoexcept) {
5505 EPI.NoexceptExpr = ReadExpr(ModuleFile);
5506 } else if (EST == EST_Uninstantiated) {
5507 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5508 EPI.ExceptionSpecTemplate =
5509 ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5510 } else if (EST == EST_Unevaluated) {
5511 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5512 }
5513}
5514
Guy Benyei11169dd2012-12-18 14:30:41 +00005515class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5516 ASTReader &Reader;
5517 ModuleFile &F;
5518 const ASTReader::RecordData &Record;
5519 unsigned &Idx;
5520
5521 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5522 unsigned &I) {
5523 return Reader.ReadSourceLocation(F, R, I);
5524 }
5525
5526 template<typename T>
5527 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5528 return Reader.ReadDeclAs<T>(F, Record, Idx);
5529 }
5530
5531public:
5532 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5533 const ASTReader::RecordData &Record, unsigned &Idx)
5534 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5535 { }
5536
5537 // We want compile-time assurance that we've enumerated all of
5538 // these, so unfortunately we have to declare them first, then
5539 // define them out-of-line.
5540#define ABSTRACT_TYPELOC(CLASS, PARENT)
5541#define TYPELOC(CLASS, PARENT) \
5542 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5543#include "clang/AST/TypeLocNodes.def"
5544
5545 void VisitFunctionTypeLoc(FunctionTypeLoc);
5546 void VisitArrayTypeLoc(ArrayTypeLoc);
5547};
5548
5549void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5550 // nothing to do
5551}
5552void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5553 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5554 if (TL.needsExtraLocalData()) {
5555 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5556 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5557 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5558 TL.setModeAttr(Record[Idx++]);
5559 }
5560}
5561void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5562 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5563}
5564void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5565 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5566}
Reid Kleckner8a365022013-06-24 17:51:48 +00005567void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5568 // nothing to do
5569}
Reid Kleckner0503a872013-12-05 01:23:43 +00005570void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5571 // nothing to do
5572}
Guy Benyei11169dd2012-12-18 14:30:41 +00005573void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5574 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5575}
5576void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5577 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5578}
5579void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5580 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5581}
5582void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5583 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5584 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5585}
5586void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5587 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5588 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5589 if (Record[Idx++])
5590 TL.setSizeExpr(Reader.ReadExpr(F));
5591 else
Craig Toppera13603a2014-05-22 05:54:18 +00005592 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005593}
5594void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5595 VisitArrayTypeLoc(TL);
5596}
5597void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5598 VisitArrayTypeLoc(TL);
5599}
5600void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5601 VisitArrayTypeLoc(TL);
5602}
5603void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5604 DependentSizedArrayTypeLoc TL) {
5605 VisitArrayTypeLoc(TL);
5606}
5607void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5608 DependentSizedExtVectorTypeLoc TL) {
5609 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5610}
5611void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5612 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5613}
5614void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5615 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5616}
5617void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5618 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5619 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5620 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5621 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005622 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5623 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005624 }
5625}
5626void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5627 VisitFunctionTypeLoc(TL);
5628}
5629void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5630 VisitFunctionTypeLoc(TL);
5631}
5632void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5633 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5634}
5635void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5636 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5637}
5638void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5639 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5640 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5641 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5642}
5643void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5644 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5645 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5646 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5647 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5648}
5649void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5650 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5651}
5652void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5653 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5654 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5655 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5656 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5657}
5658void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5659 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5660}
5661void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5662 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5663}
5664void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5665 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5666}
5667void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5668 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5669 if (TL.hasAttrOperand()) {
5670 SourceRange range;
5671 range.setBegin(ReadSourceLocation(Record, Idx));
5672 range.setEnd(ReadSourceLocation(Record, Idx));
5673 TL.setAttrOperandParensRange(range);
5674 }
5675 if (TL.hasAttrExprOperand()) {
5676 if (Record[Idx++])
5677 TL.setAttrExprOperand(Reader.ReadExpr(F));
5678 else
Craig Toppera13603a2014-05-22 05:54:18 +00005679 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005680 } else if (TL.hasAttrEnumOperand())
5681 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5682}
5683void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5684 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5685}
5686void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5687 SubstTemplateTypeParmTypeLoc TL) {
5688 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5689}
5690void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5691 SubstTemplateTypeParmPackTypeLoc TL) {
5692 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5693}
5694void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5695 TemplateSpecializationTypeLoc TL) {
5696 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5697 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5698 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5699 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5700 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5701 TL.setArgLocInfo(i,
5702 Reader.GetTemplateArgumentLocInfo(F,
5703 TL.getTypePtr()->getArg(i).getKind(),
5704 Record, Idx));
5705}
5706void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5707 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5708 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5709}
5710void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5711 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5712 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5713}
5714void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5715 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5716}
5717void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5718 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5719 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5720 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5721}
5722void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5723 DependentTemplateSpecializationTypeLoc TL) {
5724 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5725 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5726 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5727 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5728 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5729 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5730 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5731 TL.setArgLocInfo(I,
5732 Reader.GetTemplateArgumentLocInfo(F,
5733 TL.getTypePtr()->getArg(I).getKind(),
5734 Record, Idx));
5735}
5736void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5737 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5738}
5739void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5740 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5741}
5742void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5743 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5744 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5745 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5746 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5747 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5748}
5749void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5750 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5751}
5752void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5753 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5754 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5755 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5756}
5757
5758TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5759 const RecordData &Record,
5760 unsigned &Idx) {
5761 QualType InfoTy = readType(F, Record, Idx);
5762 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005763 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005764
5765 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5766 TypeLocReader TLR(*this, F, Record, Idx);
5767 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5768 TLR.Visit(TL);
5769 return TInfo;
5770}
5771
5772QualType ASTReader::GetType(TypeID ID) {
5773 unsigned FastQuals = ID & Qualifiers::FastMask;
5774 unsigned Index = ID >> Qualifiers::FastWidth;
5775
5776 if (Index < NUM_PREDEF_TYPE_IDS) {
5777 QualType T;
5778 switch ((PredefinedTypeIDs)Index) {
5779 case PREDEF_TYPE_NULL_ID: return QualType();
5780 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5781 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5782
5783 case PREDEF_TYPE_CHAR_U_ID:
5784 case PREDEF_TYPE_CHAR_S_ID:
5785 // FIXME: Check that the signedness of CharTy is correct!
5786 T = Context.CharTy;
5787 break;
5788
5789 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5790 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5791 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5792 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5793 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5794 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5795 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5796 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5797 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5798 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5799 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5800 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5801 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5802 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5803 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5804 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5805 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5806 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5807 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5808 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5809 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5810 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5811 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5812 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5813 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5814 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5815 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5816 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005817 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5818 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5819 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5820 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5821 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5822 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005823 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005824 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005825 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5826
5827 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5828 T = Context.getAutoRRefDeductType();
5829 break;
5830
5831 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5832 T = Context.ARCUnbridgedCastTy;
5833 break;
5834
5835 case PREDEF_TYPE_VA_LIST_TAG:
5836 T = Context.getVaListTagType();
5837 break;
5838
5839 case PREDEF_TYPE_BUILTIN_FN:
5840 T = Context.BuiltinFnTy;
5841 break;
5842 }
5843
5844 assert(!T.isNull() && "Unknown predefined type");
5845 return T.withFastQualifiers(FastQuals);
5846 }
5847
5848 Index -= NUM_PREDEF_TYPE_IDS;
5849 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5850 if (TypesLoaded[Index].isNull()) {
5851 TypesLoaded[Index] = readTypeRecord(Index);
5852 if (TypesLoaded[Index].isNull())
5853 return QualType();
5854
5855 TypesLoaded[Index]->setFromAST();
5856 if (DeserializationListener)
5857 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5858 TypesLoaded[Index]);
5859 }
5860
5861 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5862}
5863
5864QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5865 return GetType(getGlobalTypeID(F, LocalID));
5866}
5867
5868serialization::TypeID
5869ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5870 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5871 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5872
5873 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5874 return LocalID;
5875
5876 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5877 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5878 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5879
5880 unsigned GlobalIndex = LocalIndex + I->second;
5881 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5882}
5883
5884TemplateArgumentLocInfo
5885ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5886 TemplateArgument::ArgKind Kind,
5887 const RecordData &Record,
5888 unsigned &Index) {
5889 switch (Kind) {
5890 case TemplateArgument::Expression:
5891 return ReadExpr(F);
5892 case TemplateArgument::Type:
5893 return GetTypeSourceInfo(F, Record, Index);
5894 case TemplateArgument::Template: {
5895 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5896 Index);
5897 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5898 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5899 SourceLocation());
5900 }
5901 case TemplateArgument::TemplateExpansion: {
5902 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5903 Index);
5904 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5905 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5906 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5907 EllipsisLoc);
5908 }
5909 case TemplateArgument::Null:
5910 case TemplateArgument::Integral:
5911 case TemplateArgument::Declaration:
5912 case TemplateArgument::NullPtr:
5913 case TemplateArgument::Pack:
5914 // FIXME: Is this right?
5915 return TemplateArgumentLocInfo();
5916 }
5917 llvm_unreachable("unexpected template argument loc");
5918}
5919
5920TemplateArgumentLoc
5921ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5922 const RecordData &Record, unsigned &Index) {
5923 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5924
5925 if (Arg.getKind() == TemplateArgument::Expression) {
5926 if (Record[Index++]) // bool InfoHasSameExpr.
5927 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5928 }
5929 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5930 Record, Index));
5931}
5932
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005933const ASTTemplateArgumentListInfo*
5934ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5935 const RecordData &Record,
5936 unsigned &Index) {
5937 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5938 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5939 unsigned NumArgsAsWritten = Record[Index++];
5940 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5941 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5942 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5943 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5944}
5945
Guy Benyei11169dd2012-12-18 14:30:41 +00005946Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5947 return GetDecl(ID);
5948}
5949
Richard Smith053f6c62014-05-16 23:01:30 +00005950void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005951 if (NumCurrentElementsDeserializing) {
5952 // We arrange to not care about the complete redeclaration chain while we're
5953 // deserializing. Just remember that the AST has marked this one as complete
5954 // but that it's not actually complete yet, so we know we still need to
5955 // complete it later.
5956 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5957 return;
5958 }
5959
Richard Smith053f6c62014-05-16 23:01:30 +00005960 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5961
5962 // Recursively ensure that the decl context itself is complete
5963 // (in particular, this matters if the decl context is a namespace).
5964 //
5965 // FIXME: This should be performed by lookup instead of here.
5966 cast<Decl>(DC)->getMostRecentDecl();
5967
5968 // If this is a named declaration, complete it by looking it up
5969 // within its context.
5970 //
5971 // FIXME: We don't currently handle the cases where we can't do this;
5972 // merging a class definition that contains unnamed entities should merge
5973 // those entities. Likewise, merging a function definition should merge
5974 // all mergeable entities within it.
5975 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5976 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5977 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
5978 auto *II = Name.getAsIdentifierInfo();
5979 if (isa<TranslationUnitDecl>(DC) && II) {
5980 // Outside of C++, we don't have a lookup table for the TU, so update
5981 // the identifier instead. In C++, either way should work fine.
5982 if (II->isOutOfDate())
5983 updateOutOfDateIdentifier(*II);
5984 } else
5985 DC->lookup(Name);
5986 }
5987 }
5988}
5989
Richard Smithcd45dbc2014-04-19 03:48:30 +00005990uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
5991 const RecordData &Record,
5992 unsigned &Idx) {
5993 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
5994 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005995 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00005996 }
5997
Guy Benyei11169dd2012-12-18 14:30:41 +00005998 unsigned LocalID = Record[Idx++];
5999 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6000}
6001
6002CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6003 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006004 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006005 SavedStreamPosition SavedPosition(Cursor);
6006 Cursor.JumpToBit(Loc.Offset);
6007 ReadingKindTracker ReadingKind(Read_Decl, *this);
6008 RecordData Record;
6009 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006010 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006011 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006012 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006013 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006014 }
6015
6016 unsigned Idx = 0;
6017 unsigned NumBases = Record[Idx++];
6018 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6019 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6020 for (unsigned I = 0; I != NumBases; ++I)
6021 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6022 return Bases;
6023}
6024
6025serialization::DeclID
6026ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6027 if (LocalID < NUM_PREDEF_DECL_IDS)
6028 return LocalID;
6029
6030 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6031 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6032 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6033
6034 return LocalID + I->second;
6035}
6036
6037bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6038 ModuleFile &M) const {
6039 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6040 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6041 return &M == I->second;
6042}
6043
Douglas Gregor9f782892013-01-21 15:25:38 +00006044ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006045 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006046 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006047 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6048 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6049 return I->second;
6050}
6051
6052SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6053 if (ID < NUM_PREDEF_DECL_IDS)
6054 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006055
Guy Benyei11169dd2012-12-18 14:30:41 +00006056 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6057
6058 if (Index > DeclsLoaded.size()) {
6059 Error("declaration ID out-of-range for AST file");
6060 return SourceLocation();
6061 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006062
Guy Benyei11169dd2012-12-18 14:30:41 +00006063 if (Decl *D = DeclsLoaded[Index])
6064 return D->getLocation();
6065
6066 unsigned RawLocation = 0;
6067 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6068 return ReadSourceLocation(*Rec.F, RawLocation);
6069}
6070
Richard Smithcd45dbc2014-04-19 03:48:30 +00006071Decl *ASTReader::GetExistingDecl(DeclID ID) {
6072 if (ID < NUM_PREDEF_DECL_IDS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006073 switch ((PredefinedDeclIDs)ID) {
6074 case PREDEF_DECL_NULL_ID:
Craig Toppera13603a2014-05-22 05:54:18 +00006075 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006076
Guy Benyei11169dd2012-12-18 14:30:41 +00006077 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6078 return Context.getTranslationUnitDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006079
Guy Benyei11169dd2012-12-18 14:30:41 +00006080 case PREDEF_DECL_OBJC_ID_ID:
6081 return Context.getObjCIdDecl();
6082
6083 case PREDEF_DECL_OBJC_SEL_ID:
6084 return Context.getObjCSelDecl();
6085
6086 case PREDEF_DECL_OBJC_CLASS_ID:
6087 return Context.getObjCClassDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006088
Guy Benyei11169dd2012-12-18 14:30:41 +00006089 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6090 return Context.getObjCProtocolDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006091
Guy Benyei11169dd2012-12-18 14:30:41 +00006092 case PREDEF_DECL_INT_128_ID:
6093 return Context.getInt128Decl();
6094
6095 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6096 return Context.getUInt128Decl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006097
Guy Benyei11169dd2012-12-18 14:30:41 +00006098 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6099 return Context.getObjCInstanceTypeDecl();
6100
6101 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6102 return Context.getBuiltinVaListDecl();
6103 }
6104 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006105
Guy Benyei11169dd2012-12-18 14:30:41 +00006106 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6107
6108 if (Index >= DeclsLoaded.size()) {
6109 assert(0 && "declaration ID out-of-range for AST file");
6110 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006111 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006112 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006113
6114 return DeclsLoaded[Index];
6115}
6116
6117Decl *ASTReader::GetDecl(DeclID ID) {
6118 if (ID < NUM_PREDEF_DECL_IDS)
6119 return GetExistingDecl(ID);
6120
6121 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6122
6123 if (Index >= DeclsLoaded.size()) {
6124 assert(0 && "declaration ID out-of-range for AST file");
6125 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006126 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006127 }
6128
Guy Benyei11169dd2012-12-18 14:30:41 +00006129 if (!DeclsLoaded[Index]) {
6130 ReadDeclRecord(ID);
6131 if (DeserializationListener)
6132 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6133 }
6134
6135 return DeclsLoaded[Index];
6136}
6137
6138DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6139 DeclID GlobalID) {
6140 if (GlobalID < NUM_PREDEF_DECL_IDS)
6141 return GlobalID;
6142
6143 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6144 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6145 ModuleFile *Owner = I->second;
6146
6147 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6148 = M.GlobalToLocalDeclIDs.find(Owner);
6149 if (Pos == M.GlobalToLocalDeclIDs.end())
6150 return 0;
6151
6152 return GlobalID - Owner->BaseDeclID + Pos->second;
6153}
6154
6155serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6156 const RecordData &Record,
6157 unsigned &Idx) {
6158 if (Idx >= Record.size()) {
6159 Error("Corrupted AST file");
6160 return 0;
6161 }
6162
6163 return getGlobalDeclID(F, Record[Idx++]);
6164}
6165
6166/// \brief Resolve the offset of a statement into a statement.
6167///
6168/// This operation will read a new statement from the external
6169/// source each time it is called, and is meant to be used via a
6170/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6171Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6172 // Switch case IDs are per Decl.
6173 ClearSwitchCaseIDs();
6174
6175 // Offset here is a global offset across the entire chain.
6176 RecordLocation Loc = getLocalBitOffset(Offset);
6177 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6178 return ReadStmtFromStream(*Loc.F);
6179}
6180
6181namespace {
6182 class FindExternalLexicalDeclsVisitor {
6183 ASTReader &Reader;
6184 const DeclContext *DC;
6185 bool (*isKindWeWant)(Decl::Kind);
6186
6187 SmallVectorImpl<Decl*> &Decls;
6188 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6189
6190 public:
6191 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6192 bool (*isKindWeWant)(Decl::Kind),
6193 SmallVectorImpl<Decl*> &Decls)
6194 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6195 {
6196 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6197 PredefsVisited[I] = false;
6198 }
6199
6200 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6201 if (Preorder)
6202 return false;
6203
6204 FindExternalLexicalDeclsVisitor *This
6205 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6206
6207 ModuleFile::DeclContextInfosMap::iterator Info
6208 = M.DeclContextInfos.find(This->DC);
6209 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6210 return false;
6211
6212 // Load all of the declaration IDs
6213 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6214 *IDE = ID + Info->second.NumLexicalDecls;
6215 ID != IDE; ++ID) {
6216 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6217 continue;
6218
6219 // Don't add predefined declarations to the lexical context more
6220 // than once.
6221 if (ID->second < NUM_PREDEF_DECL_IDS) {
6222 if (This->PredefsVisited[ID->second])
6223 continue;
6224
6225 This->PredefsVisited[ID->second] = true;
6226 }
6227
6228 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6229 if (!This->DC->isDeclInLexicalTraversal(D))
6230 This->Decls.push_back(D);
6231 }
6232 }
6233
6234 return false;
6235 }
6236 };
6237}
6238
6239ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6240 bool (*isKindWeWant)(Decl::Kind),
6241 SmallVectorImpl<Decl*> &Decls) {
6242 // There might be lexical decls in multiple modules, for the TU at
6243 // least. Walk all of the modules in the order they were loaded.
6244 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6245 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6246 ++NumLexicalDeclContextsRead;
6247 return ELR_Success;
6248}
6249
6250namespace {
6251
6252class DeclIDComp {
6253 ASTReader &Reader;
6254 ModuleFile &Mod;
6255
6256public:
6257 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6258
6259 bool operator()(LocalDeclID L, LocalDeclID R) const {
6260 SourceLocation LHS = getLocation(L);
6261 SourceLocation RHS = getLocation(R);
6262 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6263 }
6264
6265 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6266 SourceLocation RHS = getLocation(R);
6267 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6268 }
6269
6270 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6271 SourceLocation LHS = getLocation(L);
6272 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6273 }
6274
6275 SourceLocation getLocation(LocalDeclID ID) const {
6276 return Reader.getSourceManager().getFileLoc(
6277 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6278 }
6279};
6280
6281}
6282
6283void ASTReader::FindFileRegionDecls(FileID File,
6284 unsigned Offset, unsigned Length,
6285 SmallVectorImpl<Decl *> &Decls) {
6286 SourceManager &SM = getSourceManager();
6287
6288 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6289 if (I == FileDeclIDs.end())
6290 return;
6291
6292 FileDeclsInfo &DInfo = I->second;
6293 if (DInfo.Decls.empty())
6294 return;
6295
6296 SourceLocation
6297 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6298 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6299
6300 DeclIDComp DIDComp(*this, *DInfo.Mod);
6301 ArrayRef<serialization::LocalDeclID>::iterator
6302 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6303 BeginLoc, DIDComp);
6304 if (BeginIt != DInfo.Decls.begin())
6305 --BeginIt;
6306
6307 // If we are pointing at a top-level decl inside an objc container, we need
6308 // to backtrack until we find it otherwise we will fail to report that the
6309 // region overlaps with an objc container.
6310 while (BeginIt != DInfo.Decls.begin() &&
6311 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6312 ->isTopLevelDeclInObjCContainer())
6313 --BeginIt;
6314
6315 ArrayRef<serialization::LocalDeclID>::iterator
6316 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6317 EndLoc, DIDComp);
6318 if (EndIt != DInfo.Decls.end())
6319 ++EndIt;
6320
6321 for (ArrayRef<serialization::LocalDeclID>::iterator
6322 DIt = BeginIt; DIt != EndIt; ++DIt)
6323 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6324}
6325
6326namespace {
6327 /// \brief ModuleFile visitor used to perform name lookup into a
6328 /// declaration context.
6329 class DeclContextNameLookupVisitor {
6330 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006331 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006332 DeclarationName Name;
6333 SmallVectorImpl<NamedDecl *> &Decls;
6334
6335 public:
6336 DeclContextNameLookupVisitor(ASTReader &Reader,
6337 SmallVectorImpl<const DeclContext *> &Contexts,
6338 DeclarationName Name,
6339 SmallVectorImpl<NamedDecl *> &Decls)
6340 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
6341
6342 static bool visit(ModuleFile &M, void *UserData) {
6343 DeclContextNameLookupVisitor *This
6344 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6345
6346 // Check whether we have any visible declaration information for
6347 // this context in this module.
6348 ModuleFile::DeclContextInfosMap::iterator Info;
6349 bool FoundInfo = false;
6350 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6351 Info = M.DeclContextInfos.find(This->Contexts[I]);
6352 if (Info != M.DeclContextInfos.end() &&
6353 Info->second.NameLookupTableData) {
6354 FoundInfo = true;
6355 break;
6356 }
6357 }
6358
6359 if (!FoundInfo)
6360 return false;
6361
6362 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006363 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006364 Info->second.NameLookupTableData;
6365 ASTDeclContextNameLookupTable::iterator Pos
6366 = LookupTable->find(This->Name);
6367 if (Pos == LookupTable->end())
6368 return false;
6369
6370 bool FoundAnything = false;
6371 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6372 for (; Data.first != Data.second; ++Data.first) {
6373 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6374 if (!ND)
6375 continue;
6376
6377 if (ND->getDeclName() != This->Name) {
6378 // A name might be null because the decl's redeclarable part is
6379 // currently read before reading its name. The lookup is triggered by
6380 // building that decl (likely indirectly), and so it is later in the
6381 // sense of "already existing" and can be ignored here.
6382 continue;
6383 }
6384
6385 // Record this declaration.
6386 FoundAnything = true;
6387 This->Decls.push_back(ND);
6388 }
6389
6390 return FoundAnything;
6391 }
6392 };
6393}
6394
Douglas Gregor9f782892013-01-21 15:25:38 +00006395/// \brief Retrieve the "definitive" module file for the definition of the
6396/// given declaration context, if there is one.
6397///
6398/// The "definitive" module file is the only place where we need to look to
6399/// find information about the declarations within the given declaration
6400/// context. For example, C++ and Objective-C classes, C structs/unions, and
6401/// Objective-C protocols, categories, and extensions are all defined in a
6402/// single place in the source code, so they have definitive module files
6403/// associated with them. C++ namespaces, on the other hand, can have
6404/// definitions in multiple different module files.
6405///
6406/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6407/// NDEBUG checking.
6408static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6409 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006410 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6411 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006412
Craig Toppera13603a2014-05-22 05:54:18 +00006413 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006414}
6415
Richard Smith9ce12e32013-02-07 03:30:24 +00006416bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006417ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6418 DeclarationName Name) {
6419 assert(DC->hasExternalVisibleStorage() &&
6420 "DeclContext has no visible decls in storage");
6421 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006422 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006423
6424 SmallVector<NamedDecl *, 64> Decls;
6425
6426 // Compute the declaration contexts we need to look into. Multiple such
6427 // declaration contexts occur when two declaration contexts from disjoint
6428 // modules get merged, e.g., when two namespaces with the same name are
6429 // independently defined in separate modules.
6430 SmallVector<const DeclContext *, 2> Contexts;
6431 Contexts.push_back(DC);
6432
6433 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006434 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006435 if (Merged != MergedDecls.end()) {
6436 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6437 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6438 }
6439 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006440 if (isa<CXXRecordDecl>(DC)) {
6441 auto Merged = MergedLookups.find(DC);
6442 if (Merged != MergedLookups.end())
6443 Contexts.insert(Contexts.end(), Merged->second.begin(),
6444 Merged->second.end());
6445 }
6446
Guy Benyei11169dd2012-12-18 14:30:41 +00006447 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor9f782892013-01-21 15:25:38 +00006448
6449 // If we can definitively determine which module file to look into,
6450 // only look there. Otherwise, look in all module files.
6451 ModuleFile *Definitive;
6452 if (Contexts.size() == 1 &&
6453 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
6454 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6455 } else {
6456 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6457 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006458 ++NumVisibleDeclContextsRead;
6459 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006460 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006461}
6462
6463namespace {
6464 /// \brief ModuleFile visitor used to retrieve all visible names in a
6465 /// declaration context.
6466 class DeclContextAllNamesVisitor {
6467 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006468 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006469 DeclsMap &Decls;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006470 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006471
6472 public:
6473 DeclContextAllNamesVisitor(ASTReader &Reader,
6474 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006475 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006476 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006477
6478 static bool visit(ModuleFile &M, void *UserData) {
6479 DeclContextAllNamesVisitor *This
6480 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6481
6482 // Check whether we have any visible declaration information for
6483 // this context in this module.
6484 ModuleFile::DeclContextInfosMap::iterator Info;
6485 bool FoundInfo = false;
6486 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6487 Info = M.DeclContextInfos.find(This->Contexts[I]);
6488 if (Info != M.DeclContextInfos.end() &&
6489 Info->second.NameLookupTableData) {
6490 FoundInfo = true;
6491 break;
6492 }
6493 }
6494
6495 if (!FoundInfo)
6496 return false;
6497
Richard Smith52e3fba2014-03-11 07:17:35 +00006498 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006499 Info->second.NameLookupTableData;
6500 bool FoundAnything = false;
6501 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006502 I = LookupTable->data_begin(), E = LookupTable->data_end();
6503 I != E;
6504 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006505 ASTDeclContextNameLookupTrait::data_type Data = *I;
6506 for (; Data.first != Data.second; ++Data.first) {
6507 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6508 *Data.first);
6509 if (!ND)
6510 continue;
6511
6512 // Record this declaration.
6513 FoundAnything = true;
6514 This->Decls[ND->getDeclName()].push_back(ND);
6515 }
6516 }
6517
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006518 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006519 }
6520 };
6521}
6522
6523void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6524 if (!DC->hasExternalVisibleStorage())
6525 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006526 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006527
6528 // Compute the declaration contexts we need to look into. Multiple such
6529 // declaration contexts occur when two declaration contexts from disjoint
6530 // modules get merged, e.g., when two namespaces with the same name are
6531 // independently defined in separate modules.
6532 SmallVector<const DeclContext *, 2> Contexts;
6533 Contexts.push_back(DC);
6534
6535 if (DC->isNamespace()) {
6536 MergedDeclsMap::iterator Merged
6537 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6538 if (Merged != MergedDecls.end()) {
6539 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6540 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6541 }
6542 }
6543
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006544 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6545 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006546 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6547 ++NumVisibleDeclContextsRead;
6548
Craig Topper79be4cd2013-07-05 04:33:53 +00006549 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006550 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6551 }
6552 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6553}
6554
6555/// \brief Under non-PCH compilation the consumer receives the objc methods
6556/// before receiving the implementation, and codegen depends on this.
6557/// We simulate this by deserializing and passing to consumer the methods of the
6558/// implementation before passing the deserialized implementation decl.
6559static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6560 ASTConsumer *Consumer) {
6561 assert(ImplD && Consumer);
6562
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006563 for (auto *I : ImplD->methods())
6564 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006565
6566 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6567}
6568
6569void ASTReader::PassInterestingDeclsToConsumer() {
6570 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006571
6572 if (PassingDeclsToConsumer)
6573 return;
6574
6575 // Guard variable to avoid recursively redoing the process of passing
6576 // decls to consumer.
6577 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6578 true);
6579
Guy Benyei11169dd2012-12-18 14:30:41 +00006580 while (!InterestingDecls.empty()) {
6581 Decl *D = InterestingDecls.front();
6582 InterestingDecls.pop_front();
6583
6584 PassInterestingDeclToConsumer(D);
6585 }
6586}
6587
6588void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6589 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6590 PassObjCImplDeclToConsumer(ImplD, Consumer);
6591 else
6592 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6593}
6594
6595void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6596 this->Consumer = Consumer;
6597
6598 if (!Consumer)
6599 return;
6600
Ben Langmuir332aafe2014-01-31 01:06:56 +00006601 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006602 // Force deserialization of this decl, which will cause it to be queued for
6603 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006604 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006605 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006606 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006607
6608 PassInterestingDeclsToConsumer();
6609}
6610
6611void ASTReader::PrintStats() {
6612 std::fprintf(stderr, "*** AST File Statistics:\n");
6613
6614 unsigned NumTypesLoaded
6615 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6616 QualType());
6617 unsigned NumDeclsLoaded
6618 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006619 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006620 unsigned NumIdentifiersLoaded
6621 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6622 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006623 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006624 unsigned NumMacrosLoaded
6625 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6626 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006627 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006628 unsigned NumSelectorsLoaded
6629 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6630 SelectorsLoaded.end(),
6631 Selector());
6632
6633 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6634 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6635 NumSLocEntriesRead, TotalNumSLocEntries,
6636 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6637 if (!TypesLoaded.empty())
6638 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6639 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6640 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6641 if (!DeclsLoaded.empty())
6642 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6643 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6644 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6645 if (!IdentifiersLoaded.empty())
6646 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6647 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6648 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6649 if (!MacrosLoaded.empty())
6650 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6651 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6652 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6653 if (!SelectorsLoaded.empty())
6654 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6655 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6656 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6657 if (TotalNumStatements)
6658 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6659 NumStatementsRead, TotalNumStatements,
6660 ((float)NumStatementsRead/TotalNumStatements * 100));
6661 if (TotalNumMacros)
6662 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6663 NumMacrosRead, TotalNumMacros,
6664 ((float)NumMacrosRead/TotalNumMacros * 100));
6665 if (TotalLexicalDeclContexts)
6666 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6667 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6668 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6669 * 100));
6670 if (TotalVisibleDeclContexts)
6671 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6672 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6673 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6674 * 100));
6675 if (TotalNumMethodPoolEntries) {
6676 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6677 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6678 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6679 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006680 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006681 if (NumMethodPoolLookups) {
6682 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6683 NumMethodPoolHits, NumMethodPoolLookups,
6684 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6685 }
6686 if (NumMethodPoolTableLookups) {
6687 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6688 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6689 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6690 * 100.0));
6691 }
6692
Douglas Gregor00a50f72013-01-25 00:38:33 +00006693 if (NumIdentifierLookupHits) {
6694 std::fprintf(stderr,
6695 " %u / %u identifier table lookups succeeded (%f%%)\n",
6696 NumIdentifierLookupHits, NumIdentifierLookups,
6697 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6698 }
6699
Douglas Gregore060e572013-01-25 01:03:03 +00006700 if (GlobalIndex) {
6701 std::fprintf(stderr, "\n");
6702 GlobalIndex->printStats();
6703 }
6704
Guy Benyei11169dd2012-12-18 14:30:41 +00006705 std::fprintf(stderr, "\n");
6706 dump();
6707 std::fprintf(stderr, "\n");
6708}
6709
6710template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6711static void
6712dumpModuleIDMap(StringRef Name,
6713 const ContinuousRangeMap<Key, ModuleFile *,
6714 InitialCapacity> &Map) {
6715 if (Map.begin() == Map.end())
6716 return;
6717
6718 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6719 llvm::errs() << Name << ":\n";
6720 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6721 I != IEnd; ++I) {
6722 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6723 << "\n";
6724 }
6725}
6726
6727void ASTReader::dump() {
6728 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6729 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6730 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6731 dumpModuleIDMap("Global type map", GlobalTypeMap);
6732 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6733 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6734 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6735 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6736 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6737 dumpModuleIDMap("Global preprocessed entity map",
6738 GlobalPreprocessedEntityMap);
6739
6740 llvm::errs() << "\n*** PCH/Modules Loaded:";
6741 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6742 MEnd = ModuleMgr.end();
6743 M != MEnd; ++M)
6744 (*M)->dump();
6745}
6746
6747/// Return the amount of memory used by memory buffers, breaking down
6748/// by heap-backed versus mmap'ed memory.
6749void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6750 for (ModuleConstIterator I = ModuleMgr.begin(),
6751 E = ModuleMgr.end(); I != E; ++I) {
6752 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6753 size_t bytes = buf->getBufferSize();
6754 switch (buf->getBufferKind()) {
6755 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6756 sizes.malloc_bytes += bytes;
6757 break;
6758 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6759 sizes.mmap_bytes += bytes;
6760 break;
6761 }
6762 }
6763 }
6764}
6765
6766void ASTReader::InitializeSema(Sema &S) {
6767 SemaObj = &S;
6768 S.addExternalSource(this);
6769
6770 // Makes sure any declarations that were deserialized "too early"
6771 // still get added to the identifier's declaration chains.
6772 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006773 pushExternalDeclIntoScope(PreloadedDecls[I],
6774 PreloadedDecls[I]->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006775 }
6776 PreloadedDecls.clear();
6777
Richard Smith3d8e97e2013-10-18 06:54:39 +00006778 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006779 if (!FPPragmaOptions.empty()) {
6780 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6781 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6782 }
6783
Richard Smith3d8e97e2013-10-18 06:54:39 +00006784 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006785 if (!OpenCLExtensions.empty()) {
6786 unsigned I = 0;
6787#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6788#include "clang/Basic/OpenCLExtensions.def"
6789
6790 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6791 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006792
6793 UpdateSema();
6794}
6795
6796void ASTReader::UpdateSema() {
6797 assert(SemaObj && "no Sema to update");
6798
6799 // Load the offsets of the declarations that Sema references.
6800 // They will be lazily deserialized when needed.
6801 if (!SemaDeclRefs.empty()) {
6802 assert(SemaDeclRefs.size() % 2 == 0);
6803 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6804 if (!SemaObj->StdNamespace)
6805 SemaObj->StdNamespace = SemaDeclRefs[I];
6806 if (!SemaObj->StdBadAlloc)
6807 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6808 }
6809 SemaDeclRefs.clear();
6810 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006811}
6812
6813IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6814 // Note that we are loading an identifier.
6815 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006816 StringRef Name(NameStart, NameEnd - NameStart);
6817
6818 // If there is a global index, look there first to determine which modules
6819 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006820 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00006821 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00006822 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006823 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6824 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006825 }
6826 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006827 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006828 NumIdentifierLookups,
6829 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006830 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006831 IdentifierInfo *II = Visitor.getIdentifierInfo();
6832 markIdentifierUpToDate(II);
6833 return II;
6834}
6835
6836namespace clang {
6837 /// \brief An identifier-lookup iterator that enumerates all of the
6838 /// identifiers stored within a set of AST files.
6839 class ASTIdentifierIterator : public IdentifierIterator {
6840 /// \brief The AST reader whose identifiers are being enumerated.
6841 const ASTReader &Reader;
6842
6843 /// \brief The current index into the chain of AST files stored in
6844 /// the AST reader.
6845 unsigned Index;
6846
6847 /// \brief The current position within the identifier lookup table
6848 /// of the current AST file.
6849 ASTIdentifierLookupTable::key_iterator Current;
6850
6851 /// \brief The end position within the identifier lookup table of
6852 /// the current AST file.
6853 ASTIdentifierLookupTable::key_iterator End;
6854
6855 public:
6856 explicit ASTIdentifierIterator(const ASTReader &Reader);
6857
Craig Topper3e89dfe2014-03-13 02:13:41 +00006858 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006859 };
6860}
6861
6862ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6863 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6864 ASTIdentifierLookupTable *IdTable
6865 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6866 Current = IdTable->key_begin();
6867 End = IdTable->key_end();
6868}
6869
6870StringRef ASTIdentifierIterator::Next() {
6871 while (Current == End) {
6872 // If we have exhausted all of our AST files, we're done.
6873 if (Index == 0)
6874 return StringRef();
6875
6876 --Index;
6877 ASTIdentifierLookupTable *IdTable
6878 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6879 IdentifierLookupTable;
6880 Current = IdTable->key_begin();
6881 End = IdTable->key_end();
6882 }
6883
6884 // We have any identifiers remaining in the current AST file; return
6885 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006886 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006887 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006888 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006889}
6890
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006891IdentifierIterator *ASTReader::getIdentifiers() {
6892 if (!loadGlobalIndex())
6893 return GlobalIndex->createIdentifierIterator();
6894
Guy Benyei11169dd2012-12-18 14:30:41 +00006895 return new ASTIdentifierIterator(*this);
6896}
6897
6898namespace clang { namespace serialization {
6899 class ReadMethodPoolVisitor {
6900 ASTReader &Reader;
6901 Selector Sel;
6902 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006903 unsigned InstanceBits;
6904 unsigned FactoryBits;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006905 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6906 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006907
6908 public:
6909 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6910 unsigned PriorGeneration)
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006911 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6912 InstanceBits(0), FactoryBits(0) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006913
6914 static bool visit(ModuleFile &M, void *UserData) {
6915 ReadMethodPoolVisitor *This
6916 = static_cast<ReadMethodPoolVisitor *>(UserData);
6917
6918 if (!M.SelectorLookupTable)
6919 return false;
6920
6921 // If we've already searched this module file, skip it now.
6922 if (M.Generation <= This->PriorGeneration)
6923 return true;
6924
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006925 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006926 ASTSelectorLookupTable *PoolTable
6927 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6928 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6929 if (Pos == PoolTable->end())
6930 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006931
6932 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006933 ++This->Reader.NumSelectorsRead;
6934 // FIXME: Not quite happy with the statistics here. We probably should
6935 // disable this tracking when called via LoadSelector.
6936 // Also, should entries without methods count as misses?
6937 ++This->Reader.NumMethodPoolEntriesRead;
6938 ASTSelectorLookupTrait::data_type Data = *Pos;
6939 if (This->Reader.DeserializationListener)
6940 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6941 This->Sel);
6942
6943 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6944 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006945 This->InstanceBits = Data.InstanceBits;
6946 This->FactoryBits = Data.FactoryBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006947 return true;
6948 }
6949
6950 /// \brief Retrieve the instance methods found by this visitor.
6951 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6952 return InstanceMethods;
6953 }
6954
6955 /// \brief Retrieve the instance methods found by this visitor.
6956 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6957 return FactoryMethods;
6958 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006959
6960 unsigned getInstanceBits() const { return InstanceBits; }
6961 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006962 };
6963} } // end namespace clang::serialization
6964
6965/// \brief Add the given set of methods to the method list.
6966static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6967 ObjCMethodList &List) {
6968 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6969 S.addMethodToGlobalList(&List, Methods[I]);
6970 }
6971}
6972
6973void ASTReader::ReadMethodPool(Selector Sel) {
6974 // Get the selector generation and update it to the current generation.
6975 unsigned &Generation = SelectorGeneration[Sel];
6976 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00006977 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00006978
6979 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006980 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006981 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6982 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6983
6984 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006985 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00006986 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006987
6988 ++NumMethodPoolHits;
6989
Guy Benyei11169dd2012-12-18 14:30:41 +00006990 if (!getSema())
6991 return;
6992
6993 Sema &S = *getSema();
6994 Sema::GlobalMethodPool::iterator Pos
6995 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6996
6997 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6998 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006999 Pos->second.first.setBits(Visitor.getInstanceBits());
7000 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei11169dd2012-12-18 14:30:41 +00007001}
7002
7003void ASTReader::ReadKnownNamespaces(
7004 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7005 Namespaces.clear();
7006
7007 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7008 if (NamespaceDecl *Namespace
7009 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7010 Namespaces.push_back(Namespace);
7011 }
7012}
7013
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007014void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007015 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007016 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7017 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007018 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007019 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007020 Undefined.insert(std::make_pair(D, Loc));
7021 }
7022}
Nick Lewycky8334af82013-01-26 00:35:08 +00007023
Guy Benyei11169dd2012-12-18 14:30:41 +00007024void ASTReader::ReadTentativeDefinitions(
7025 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7026 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7027 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7028 if (Var)
7029 TentativeDefs.push_back(Var);
7030 }
7031 TentativeDefinitions.clear();
7032}
7033
7034void ASTReader::ReadUnusedFileScopedDecls(
7035 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7036 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7037 DeclaratorDecl *D
7038 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7039 if (D)
7040 Decls.push_back(D);
7041 }
7042 UnusedFileScopedDecls.clear();
7043}
7044
7045void ASTReader::ReadDelegatingConstructors(
7046 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7047 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7048 CXXConstructorDecl *D
7049 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7050 if (D)
7051 Decls.push_back(D);
7052 }
7053 DelegatingCtorDecls.clear();
7054}
7055
7056void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7057 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7058 TypedefNameDecl *D
7059 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7060 if (D)
7061 Decls.push_back(D);
7062 }
7063 ExtVectorDecls.clear();
7064}
7065
7066void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
7067 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
7068 CXXRecordDecl *D
7069 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
7070 if (D)
7071 Decls.push_back(D);
7072 }
7073 DynamicClasses.clear();
7074}
7075
7076void
Richard Smith78165b52013-01-10 23:43:47 +00007077ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
7078 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
7079 NamedDecl *D
7080 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007081 if (D)
7082 Decls.push_back(D);
7083 }
Richard Smith78165b52013-01-10 23:43:47 +00007084 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007085}
7086
7087void ASTReader::ReadReferencedSelectors(
7088 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7089 if (ReferencedSelectorsData.empty())
7090 return;
7091
7092 // If there are @selector references added them to its pool. This is for
7093 // implementation of -Wselector.
7094 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7095 unsigned I = 0;
7096 while (I < DataSize) {
7097 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7098 SourceLocation SelLoc
7099 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7100 Sels.push_back(std::make_pair(Sel, SelLoc));
7101 }
7102 ReferencedSelectorsData.clear();
7103}
7104
7105void ASTReader::ReadWeakUndeclaredIdentifiers(
7106 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7107 if (WeakUndeclaredIdentifiers.empty())
7108 return;
7109
7110 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7111 IdentifierInfo *WeakId
7112 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7113 IdentifierInfo *AliasId
7114 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7115 SourceLocation Loc
7116 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7117 bool Used = WeakUndeclaredIdentifiers[I++];
7118 WeakInfo WI(AliasId, Loc);
7119 WI.setUsed(Used);
7120 WeakIDs.push_back(std::make_pair(WeakId, WI));
7121 }
7122 WeakUndeclaredIdentifiers.clear();
7123}
7124
7125void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7126 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7127 ExternalVTableUse VT;
7128 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7129 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7130 VT.DefinitionRequired = VTableUses[Idx++];
7131 VTables.push_back(VT);
7132 }
7133
7134 VTableUses.clear();
7135}
7136
7137void ASTReader::ReadPendingInstantiations(
7138 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7139 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7140 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7141 SourceLocation Loc
7142 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7143
7144 Pending.push_back(std::make_pair(D, Loc));
7145 }
7146 PendingInstantiations.clear();
7147}
7148
Richard Smithe40f2ba2013-08-07 21:41:30 +00007149void ASTReader::ReadLateParsedTemplates(
7150 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7151 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7152 /* In loop */) {
7153 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7154
7155 LateParsedTemplate *LT = new LateParsedTemplate;
7156 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7157
7158 ModuleFile *F = getOwningModuleFile(LT->D);
7159 assert(F && "No module");
7160
7161 unsigned TokN = LateParsedTemplates[Idx++];
7162 LT->Toks.reserve(TokN);
7163 for (unsigned T = 0; T < TokN; ++T)
7164 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7165
7166 LPTMap[FD] = LT;
7167 }
7168
7169 LateParsedTemplates.clear();
7170}
7171
Guy Benyei11169dd2012-12-18 14:30:41 +00007172void ASTReader::LoadSelector(Selector Sel) {
7173 // It would be complicated to avoid reading the methods anyway. So don't.
7174 ReadMethodPool(Sel);
7175}
7176
7177void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7178 assert(ID && "Non-zero identifier ID required");
7179 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7180 IdentifiersLoaded[ID - 1] = II;
7181 if (DeserializationListener)
7182 DeserializationListener->IdentifierRead(ID, II);
7183}
7184
7185/// \brief Set the globally-visible declarations associated with the given
7186/// identifier.
7187///
7188/// If the AST reader is currently in a state where the given declaration IDs
7189/// cannot safely be resolved, they are queued until it is safe to resolve
7190/// them.
7191///
7192/// \param II an IdentifierInfo that refers to one or more globally-visible
7193/// declarations.
7194///
7195/// \param DeclIDs the set of declaration IDs with the name @p II that are
7196/// visible at global scope.
7197///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007198/// \param Decls if non-null, this vector will be populated with the set of
7199/// deserialized declarations. These declarations will not be pushed into
7200/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007201void
7202ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7203 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007204 SmallVectorImpl<Decl *> *Decls) {
7205 if (NumCurrentElementsDeserializing && !Decls) {
7206 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007207 return;
7208 }
7209
7210 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
7211 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7212 if (SemaObj) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007213 // If we're simply supposed to record the declarations, do so now.
7214 if (Decls) {
7215 Decls->push_back(D);
7216 continue;
7217 }
7218
Guy Benyei11169dd2012-12-18 14:30:41 +00007219 // Introduce this declaration into the translation-unit scope
7220 // and add it to the declaration chain for this identifier, so
7221 // that (unqualified) name lookup will find it.
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007222 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007223 } else {
7224 // Queue this declaration so that it will be added to the
7225 // translation unit scope and identifier's declaration chain
7226 // once a Sema object is known.
7227 PreloadedDecls.push_back(D);
7228 }
7229 }
7230}
7231
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007232IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007233 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007234 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007235
7236 if (IdentifiersLoaded.empty()) {
7237 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007238 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007239 }
7240
7241 ID -= 1;
7242 if (!IdentifiersLoaded[ID]) {
7243 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7244 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7245 ModuleFile *M = I->second;
7246 unsigned Index = ID - M->BaseIdentifierID;
7247 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7248
7249 // All of the strings in the AST file are preceded by a 16-bit length.
7250 // Extract that 16-bit length to avoid having to execute strlen().
7251 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7252 // unsigned integers. This is important to avoid integer overflow when
7253 // we cast them to 'unsigned'.
7254 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7255 unsigned StrLen = (((unsigned) StrLenPtr[0])
7256 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007257 IdentifiersLoaded[ID]
7258 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007259 if (DeserializationListener)
7260 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7261 }
7262
7263 return IdentifiersLoaded[ID];
7264}
7265
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007266IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7267 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007268}
7269
7270IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7271 if (LocalID < NUM_PREDEF_IDENT_IDS)
7272 return LocalID;
7273
7274 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7275 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7276 assert(I != M.IdentifierRemap.end()
7277 && "Invalid index into identifier index remap");
7278
7279 return LocalID + I->second;
7280}
7281
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007282MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007283 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007284 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007285
7286 if (MacrosLoaded.empty()) {
7287 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007288 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007289 }
7290
7291 ID -= NUM_PREDEF_MACRO_IDS;
7292 if (!MacrosLoaded[ID]) {
7293 GlobalMacroMapType::iterator I
7294 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7295 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7296 ModuleFile *M = I->second;
7297 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007298 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7299
7300 if (DeserializationListener)
7301 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7302 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007303 }
7304
7305 return MacrosLoaded[ID];
7306}
7307
7308MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7309 if (LocalID < NUM_PREDEF_MACRO_IDS)
7310 return LocalID;
7311
7312 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7313 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7314 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7315
7316 return LocalID + I->second;
7317}
7318
7319serialization::SubmoduleID
7320ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7321 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7322 return LocalID;
7323
7324 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7325 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7326 assert(I != M.SubmoduleRemap.end()
7327 && "Invalid index into submodule index remap");
7328
7329 return LocalID + I->second;
7330}
7331
7332Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7333 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7334 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007335 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007336 }
7337
7338 if (GlobalID > SubmodulesLoaded.size()) {
7339 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007340 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007341 }
7342
7343 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7344}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007345
7346Module *ASTReader::getModule(unsigned ID) {
7347 return getSubmodule(ID);
7348}
7349
Guy Benyei11169dd2012-12-18 14:30:41 +00007350Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7351 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7352}
7353
7354Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7355 if (ID == 0)
7356 return Selector();
7357
7358 if (ID > SelectorsLoaded.size()) {
7359 Error("selector ID out of range in AST file");
7360 return Selector();
7361 }
7362
Craig Toppera13603a2014-05-22 05:54:18 +00007363 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007364 // Load this selector from the selector table.
7365 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7366 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7367 ModuleFile &M = *I->second;
7368 ASTSelectorLookupTrait Trait(*this, M);
7369 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7370 SelectorsLoaded[ID - 1] =
7371 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7372 if (DeserializationListener)
7373 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7374 }
7375
7376 return SelectorsLoaded[ID - 1];
7377}
7378
7379Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7380 return DecodeSelector(ID);
7381}
7382
7383uint32_t ASTReader::GetNumExternalSelectors() {
7384 // ID 0 (the null selector) is considered an external selector.
7385 return getTotalNumSelectors() + 1;
7386}
7387
7388serialization::SelectorID
7389ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7390 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7391 return LocalID;
7392
7393 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7394 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7395 assert(I != M.SelectorRemap.end()
7396 && "Invalid index into selector index remap");
7397
7398 return LocalID + I->second;
7399}
7400
7401DeclarationName
7402ASTReader::ReadDeclarationName(ModuleFile &F,
7403 const RecordData &Record, unsigned &Idx) {
7404 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7405 switch (Kind) {
7406 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007407 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007408
7409 case DeclarationName::ObjCZeroArgSelector:
7410 case DeclarationName::ObjCOneArgSelector:
7411 case DeclarationName::ObjCMultiArgSelector:
7412 return DeclarationName(ReadSelector(F, Record, Idx));
7413
7414 case DeclarationName::CXXConstructorName:
7415 return Context.DeclarationNames.getCXXConstructorName(
7416 Context.getCanonicalType(readType(F, Record, Idx)));
7417
7418 case DeclarationName::CXXDestructorName:
7419 return Context.DeclarationNames.getCXXDestructorName(
7420 Context.getCanonicalType(readType(F, Record, Idx)));
7421
7422 case DeclarationName::CXXConversionFunctionName:
7423 return Context.DeclarationNames.getCXXConversionFunctionName(
7424 Context.getCanonicalType(readType(F, Record, Idx)));
7425
7426 case DeclarationName::CXXOperatorName:
7427 return Context.DeclarationNames.getCXXOperatorName(
7428 (OverloadedOperatorKind)Record[Idx++]);
7429
7430 case DeclarationName::CXXLiteralOperatorName:
7431 return Context.DeclarationNames.getCXXLiteralOperatorName(
7432 GetIdentifierInfo(F, Record, Idx));
7433
7434 case DeclarationName::CXXUsingDirective:
7435 return DeclarationName::getUsingDirectiveName();
7436 }
7437
7438 llvm_unreachable("Invalid NameKind!");
7439}
7440
7441void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7442 DeclarationNameLoc &DNLoc,
7443 DeclarationName Name,
7444 const RecordData &Record, unsigned &Idx) {
7445 switch (Name.getNameKind()) {
7446 case DeclarationName::CXXConstructorName:
7447 case DeclarationName::CXXDestructorName:
7448 case DeclarationName::CXXConversionFunctionName:
7449 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7450 break;
7451
7452 case DeclarationName::CXXOperatorName:
7453 DNLoc.CXXOperatorName.BeginOpNameLoc
7454 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7455 DNLoc.CXXOperatorName.EndOpNameLoc
7456 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7457 break;
7458
7459 case DeclarationName::CXXLiteralOperatorName:
7460 DNLoc.CXXLiteralOperatorName.OpNameLoc
7461 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7462 break;
7463
7464 case DeclarationName::Identifier:
7465 case DeclarationName::ObjCZeroArgSelector:
7466 case DeclarationName::ObjCOneArgSelector:
7467 case DeclarationName::ObjCMultiArgSelector:
7468 case DeclarationName::CXXUsingDirective:
7469 break;
7470 }
7471}
7472
7473void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7474 DeclarationNameInfo &NameInfo,
7475 const RecordData &Record, unsigned &Idx) {
7476 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7477 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7478 DeclarationNameLoc DNLoc;
7479 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7480 NameInfo.setInfo(DNLoc);
7481}
7482
7483void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7484 const RecordData &Record, unsigned &Idx) {
7485 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7486 unsigned NumTPLists = Record[Idx++];
7487 Info.NumTemplParamLists = NumTPLists;
7488 if (NumTPLists) {
7489 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7490 for (unsigned i=0; i != NumTPLists; ++i)
7491 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7492 }
7493}
7494
7495TemplateName
7496ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7497 unsigned &Idx) {
7498 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7499 switch (Kind) {
7500 case TemplateName::Template:
7501 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7502
7503 case TemplateName::OverloadedTemplate: {
7504 unsigned size = Record[Idx++];
7505 UnresolvedSet<8> Decls;
7506 while (size--)
7507 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7508
7509 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7510 }
7511
7512 case TemplateName::QualifiedTemplate: {
7513 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7514 bool hasTemplKeyword = Record[Idx++];
7515 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7516 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7517 }
7518
7519 case TemplateName::DependentTemplate: {
7520 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7521 if (Record[Idx++]) // isIdentifier
7522 return Context.getDependentTemplateName(NNS,
7523 GetIdentifierInfo(F, Record,
7524 Idx));
7525 return Context.getDependentTemplateName(NNS,
7526 (OverloadedOperatorKind)Record[Idx++]);
7527 }
7528
7529 case TemplateName::SubstTemplateTemplateParm: {
7530 TemplateTemplateParmDecl *param
7531 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7532 if (!param) return TemplateName();
7533 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7534 return Context.getSubstTemplateTemplateParm(param, replacement);
7535 }
7536
7537 case TemplateName::SubstTemplateTemplateParmPack: {
7538 TemplateTemplateParmDecl *Param
7539 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7540 if (!Param)
7541 return TemplateName();
7542
7543 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7544 if (ArgPack.getKind() != TemplateArgument::Pack)
7545 return TemplateName();
7546
7547 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7548 }
7549 }
7550
7551 llvm_unreachable("Unhandled template name kind!");
7552}
7553
7554TemplateArgument
7555ASTReader::ReadTemplateArgument(ModuleFile &F,
7556 const RecordData &Record, unsigned &Idx) {
7557 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7558 switch (Kind) {
7559 case TemplateArgument::Null:
7560 return TemplateArgument();
7561 case TemplateArgument::Type:
7562 return TemplateArgument(readType(F, Record, Idx));
7563 case TemplateArgument::Declaration: {
7564 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7565 bool ForReferenceParam = Record[Idx++];
7566 return TemplateArgument(D, ForReferenceParam);
7567 }
7568 case TemplateArgument::NullPtr:
7569 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7570 case TemplateArgument::Integral: {
7571 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7572 QualType T = readType(F, Record, Idx);
7573 return TemplateArgument(Context, Value, T);
7574 }
7575 case TemplateArgument::Template:
7576 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7577 case TemplateArgument::TemplateExpansion: {
7578 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007579 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007580 if (unsigned NumExpansions = Record[Idx++])
7581 NumTemplateExpansions = NumExpansions - 1;
7582 return TemplateArgument(Name, NumTemplateExpansions);
7583 }
7584 case TemplateArgument::Expression:
7585 return TemplateArgument(ReadExpr(F));
7586 case TemplateArgument::Pack: {
7587 unsigned NumArgs = Record[Idx++];
7588 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7589 for (unsigned I = 0; I != NumArgs; ++I)
7590 Args[I] = ReadTemplateArgument(F, Record, Idx);
7591 return TemplateArgument(Args, NumArgs);
7592 }
7593 }
7594
7595 llvm_unreachable("Unhandled template argument kind!");
7596}
7597
7598TemplateParameterList *
7599ASTReader::ReadTemplateParameterList(ModuleFile &F,
7600 const RecordData &Record, unsigned &Idx) {
7601 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7602 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7603 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7604
7605 unsigned NumParams = Record[Idx++];
7606 SmallVector<NamedDecl *, 16> Params;
7607 Params.reserve(NumParams);
7608 while (NumParams--)
7609 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7610
7611 TemplateParameterList* TemplateParams =
7612 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7613 Params.data(), Params.size(), RAngleLoc);
7614 return TemplateParams;
7615}
7616
7617void
7618ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007619ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007620 ModuleFile &F, const RecordData &Record,
7621 unsigned &Idx) {
7622 unsigned NumTemplateArgs = Record[Idx++];
7623 TemplArgs.reserve(NumTemplateArgs);
7624 while (NumTemplateArgs--)
7625 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7626}
7627
7628/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007629void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007630 const RecordData &Record, unsigned &Idx) {
7631 unsigned NumDecls = Record[Idx++];
7632 Set.reserve(Context, NumDecls);
7633 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007634 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007635 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007636 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007637 }
7638}
7639
7640CXXBaseSpecifier
7641ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7642 const RecordData &Record, unsigned &Idx) {
7643 bool isVirtual = static_cast<bool>(Record[Idx++]);
7644 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7645 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7646 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7647 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7648 SourceRange Range = ReadSourceRange(F, Record, Idx);
7649 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7650 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7651 EllipsisLoc);
7652 Result.setInheritConstructors(inheritConstructors);
7653 return Result;
7654}
7655
7656std::pair<CXXCtorInitializer **, unsigned>
7657ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7658 unsigned &Idx) {
Craig Toppera13603a2014-05-22 05:54:18 +00007659 CXXCtorInitializer **CtorInitializers = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007660 unsigned NumInitializers = Record[Idx++];
7661 if (NumInitializers) {
7662 CtorInitializers
7663 = new (Context) CXXCtorInitializer*[NumInitializers];
7664 for (unsigned i=0; i != NumInitializers; ++i) {
Craig Toppera13603a2014-05-22 05:54:18 +00007665 TypeSourceInfo *TInfo = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007666 bool IsBaseVirtual = false;
Craig Toppera13603a2014-05-22 05:54:18 +00007667 FieldDecl *Member = nullptr;
7668 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007669
7670 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7671 switch (Type) {
7672 case CTOR_INITIALIZER_BASE:
7673 TInfo = GetTypeSourceInfo(F, Record, Idx);
7674 IsBaseVirtual = Record[Idx++];
7675 break;
7676
7677 case CTOR_INITIALIZER_DELEGATING:
7678 TInfo = GetTypeSourceInfo(F, Record, Idx);
7679 break;
7680
7681 case CTOR_INITIALIZER_MEMBER:
7682 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7683 break;
7684
7685 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7686 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7687 break;
7688 }
7689
7690 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7691 Expr *Init = ReadExpr(F);
7692 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7693 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7694 bool IsWritten = Record[Idx++];
7695 unsigned SourceOrderOrNumArrayIndices;
7696 SmallVector<VarDecl *, 8> Indices;
7697 if (IsWritten) {
7698 SourceOrderOrNumArrayIndices = Record[Idx++];
7699 } else {
7700 SourceOrderOrNumArrayIndices = Record[Idx++];
7701 Indices.reserve(SourceOrderOrNumArrayIndices);
7702 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7703 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7704 }
7705
7706 CXXCtorInitializer *BOMInit;
7707 if (Type == CTOR_INITIALIZER_BASE) {
7708 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7709 LParenLoc, Init, RParenLoc,
7710 MemberOrEllipsisLoc);
7711 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7712 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7713 Init, RParenLoc);
7714 } else if (IsWritten) {
7715 if (Member)
7716 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7717 LParenLoc, Init, RParenLoc);
7718 else
7719 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7720 MemberOrEllipsisLoc, LParenLoc,
7721 Init, RParenLoc);
7722 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007723 if (IndirectMember) {
7724 assert(Indices.empty() && "Indirect field improperly initialized");
7725 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7726 MemberOrEllipsisLoc, LParenLoc,
7727 Init, RParenLoc);
7728 } else {
7729 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7730 LParenLoc, Init, RParenLoc,
7731 Indices.data(), Indices.size());
7732 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007733 }
7734
7735 if (IsWritten)
7736 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7737 CtorInitializers[i] = BOMInit;
7738 }
7739 }
7740
7741 return std::make_pair(CtorInitializers, NumInitializers);
7742}
7743
7744NestedNameSpecifier *
7745ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7746 const RecordData &Record, unsigned &Idx) {
7747 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007748 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007749 for (unsigned I = 0; I != N; ++I) {
7750 NestedNameSpecifier::SpecifierKind Kind
7751 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7752 switch (Kind) {
7753 case NestedNameSpecifier::Identifier: {
7754 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7755 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7756 break;
7757 }
7758
7759 case NestedNameSpecifier::Namespace: {
7760 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7761 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7762 break;
7763 }
7764
7765 case NestedNameSpecifier::NamespaceAlias: {
7766 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7767 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7768 break;
7769 }
7770
7771 case NestedNameSpecifier::TypeSpec:
7772 case NestedNameSpecifier::TypeSpecWithTemplate: {
7773 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7774 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007775 return nullptr;
7776
Guy Benyei11169dd2012-12-18 14:30:41 +00007777 bool Template = Record[Idx++];
7778 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7779 break;
7780 }
7781
7782 case NestedNameSpecifier::Global: {
7783 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7784 // No associated value, and there can't be a prefix.
7785 break;
7786 }
7787 }
7788 Prev = NNS;
7789 }
7790 return NNS;
7791}
7792
7793NestedNameSpecifierLoc
7794ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7795 unsigned &Idx) {
7796 unsigned N = Record[Idx++];
7797 NestedNameSpecifierLocBuilder Builder;
7798 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 SourceRange Range = ReadSourceRange(F, Record, Idx);
7805 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7806 break;
7807 }
7808
7809 case NestedNameSpecifier::Namespace: {
7810 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7811 SourceRange Range = ReadSourceRange(F, Record, Idx);
7812 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7813 break;
7814 }
7815
7816 case NestedNameSpecifier::NamespaceAlias: {
7817 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7818 SourceRange Range = ReadSourceRange(F, Record, Idx);
7819 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7820 break;
7821 }
7822
7823 case NestedNameSpecifier::TypeSpec:
7824 case NestedNameSpecifier::TypeSpecWithTemplate: {
7825 bool Template = Record[Idx++];
7826 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7827 if (!T)
7828 return NestedNameSpecifierLoc();
7829 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7830
7831 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7832 Builder.Extend(Context,
7833 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7834 T->getTypeLoc(), ColonColonLoc);
7835 break;
7836 }
7837
7838 case NestedNameSpecifier::Global: {
7839 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7840 Builder.MakeGlobal(Context, ColonColonLoc);
7841 break;
7842 }
7843 }
7844 }
7845
7846 return Builder.getWithLocInContext(Context);
7847}
7848
7849SourceRange
7850ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7851 unsigned &Idx) {
7852 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7853 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7854 return SourceRange(beg, end);
7855}
7856
7857/// \brief Read an integral value
7858llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7859 unsigned BitWidth = Record[Idx++];
7860 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7861 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7862 Idx += NumWords;
7863 return Result;
7864}
7865
7866/// \brief Read a signed integral value
7867llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7868 bool isUnsigned = Record[Idx++];
7869 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7870}
7871
7872/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007873llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7874 const llvm::fltSemantics &Sem,
7875 unsigned &Idx) {
7876 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007877}
7878
7879// \brief Read a string
7880std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7881 unsigned Len = Record[Idx++];
7882 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7883 Idx += Len;
7884 return Result;
7885}
7886
7887VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7888 unsigned &Idx) {
7889 unsigned Major = Record[Idx++];
7890 unsigned Minor = Record[Idx++];
7891 unsigned Subminor = Record[Idx++];
7892 if (Minor == 0)
7893 return VersionTuple(Major);
7894 if (Subminor == 0)
7895 return VersionTuple(Major, Minor - 1);
7896 return VersionTuple(Major, Minor - 1, Subminor - 1);
7897}
7898
7899CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7900 const RecordData &Record,
7901 unsigned &Idx) {
7902 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7903 return CXXTemporary::Create(Context, Decl);
7904}
7905
7906DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007907 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007908}
7909
7910DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7911 return Diags.Report(Loc, DiagID);
7912}
7913
7914/// \brief Retrieve the identifier table associated with the
7915/// preprocessor.
7916IdentifierTable &ASTReader::getIdentifierTable() {
7917 return PP.getIdentifierTable();
7918}
7919
7920/// \brief Record that the given ID maps to the given switch-case
7921/// statement.
7922void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007923 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007924 "Already have a SwitchCase with this ID");
7925 (*CurrSwitchCaseStmts)[ID] = SC;
7926}
7927
7928/// \brief Retrieve the switch-case statement with the given ID.
7929SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007930 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00007931 return (*CurrSwitchCaseStmts)[ID];
7932}
7933
7934void ASTReader::ClearSwitchCaseIDs() {
7935 CurrSwitchCaseStmts->clear();
7936}
7937
7938void ASTReader::ReadComments() {
7939 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007940 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007941 serialization::ModuleFile *> >::iterator
7942 I = CommentsCursors.begin(),
7943 E = CommentsCursors.end();
7944 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007945 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007946 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007947 serialization::ModuleFile &F = *I->second;
7948 SavedStreamPosition SavedPosition(Cursor);
7949
7950 RecordData Record;
7951 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007952 llvm::BitstreamEntry Entry =
7953 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007954
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007955 switch (Entry.Kind) {
7956 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7957 case llvm::BitstreamEntry::Error:
7958 Error("malformed block record in AST file");
7959 return;
7960 case llvm::BitstreamEntry::EndBlock:
7961 goto NextCursor;
7962 case llvm::BitstreamEntry::Record:
7963 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00007964 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007965 }
7966
7967 // Read a record.
7968 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007969 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007970 case COMMENTS_RAW_COMMENT: {
7971 unsigned Idx = 0;
7972 SourceRange SR = ReadSourceRange(F, Record, Idx);
7973 RawComment::CommentKind Kind =
7974 (RawComment::CommentKind) Record[Idx++];
7975 bool IsTrailingComment = Record[Idx++];
7976 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00007977 Comments.push_back(new (Context) RawComment(
7978 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
7979 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00007980 break;
7981 }
7982 }
7983 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007984 NextCursor:
7985 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00007986 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007987}
7988
Richard Smithcd45dbc2014-04-19 03:48:30 +00007989std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
7990 // If we know the owning module, use it.
7991 if (Module *M = D->getOwningModule())
7992 return M->getFullModuleName();
7993
7994 // Otherwise, use the name of the top-level module the decl is within.
7995 if (ModuleFile *M = getOwningModuleFile(D))
7996 return M->ModuleName;
7997
7998 // Not from a module.
7999 return "";
8000}
8001
Guy Benyei11169dd2012-12-18 14:30:41 +00008002void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008003 while (!PendingIdentifierInfos.empty() ||
8004 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008005 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smith93914a92014-05-08 00:25:01 +00008006 !PendingUpdateRecords.empty() || !PendingOdrMergeChecks.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008007 // If any identifiers with corresponding top-level declarations have
8008 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008009 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8010 TopLevelDeclsMap;
8011 TopLevelDeclsMap TopLevelDecls;
8012
Guy Benyei11169dd2012-12-18 14:30:41 +00008013 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008014 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008015 SmallVector<uint32_t, 4> DeclIDs =
8016 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008017 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008018
8019 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008020 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008021
Richard Smith851072e2014-05-19 20:59:20 +00008022 // For each decl chain that we wanted to complete while deserializing, mark
8023 // it as "still needs to be completed".
8024 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8025 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8026 }
8027 PendingIncompleteDeclChains.clear();
8028
Guy Benyei11169dd2012-12-18 14:30:41 +00008029 // Load pending declaration chains.
8030 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
8031 loadPendingDeclChain(PendingDeclChains[I]);
8032 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
8033 }
8034 PendingDeclChains.clear();
8035
Douglas Gregor6168bd22013-02-18 15:53:43 +00008036 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008037 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8038 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008039 IdentifierInfo *II = TLD->first;
8040 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008041 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008042 }
8043 }
8044
Guy Benyei11169dd2012-12-18 14:30:41 +00008045 // Load any pending macro definitions.
8046 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008047 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8048 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8049 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8050 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008051 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008052 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008053 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8054 if (Info.M->Kind != MK_Module)
8055 resolvePendingMacro(II, Info);
8056 }
8057 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008058 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008059 ++IDIdx) {
8060 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8061 if (Info.M->Kind == MK_Module)
8062 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008063 }
8064 }
8065 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008066
8067 // Wire up the DeclContexts for Decls that we delayed setting until
8068 // recursive loading is completed.
8069 while (!PendingDeclContextInfos.empty()) {
8070 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8071 PendingDeclContextInfos.pop_front();
8072 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8073 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8074 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8075 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008076
Richard Smithd1c46742014-04-30 02:24:17 +00008077 // Perform any pending declaration updates.
8078 while (!PendingUpdateRecords.empty()) {
8079 auto Update = PendingUpdateRecords.pop_back_val();
8080 ReadingKindTracker ReadingKind(Read_Decl, *this);
8081 loadDeclUpdateRecords(Update.first, Update.second);
8082 }
8083
Richard Smithcd45dbc2014-04-19 03:48:30 +00008084 // Trigger the import of the full definition of each class that had any
8085 // odr-merging problems, so we can produce better diagnostics for them.
8086 for (auto &Merge : PendingOdrMergeFailures) {
8087 Merge.first->buildLookup();
8088 Merge.first->decls_begin();
8089 Merge.first->bases_begin();
8090 Merge.first->vbases_begin();
8091 for (auto *RD : Merge.second) {
8092 RD->decls_begin();
8093 RD->bases_begin();
8094 RD->vbases_begin();
8095 }
8096 }
8097
Richard Smith2b9e3e32013-10-18 06:05:18 +00008098 // For each declaration from a merged context, check that the canonical
8099 // definition of that context also contains a declaration of the same
8100 // entity.
8101 while (!PendingOdrMergeChecks.empty()) {
8102 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8103
8104 // FIXME: Skip over implicit declarations for now. This matters for things
8105 // like implicitly-declared special member functions. This isn't entirely
8106 // correct; we can end up with multiple unmerged declarations of the same
8107 // implicit entity.
8108 if (D->isImplicit())
8109 continue;
8110
8111 DeclContext *CanonDef = D->getDeclContext();
8112 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
8113
8114 bool Found = false;
8115 const Decl *DCanon = D->getCanonicalDecl();
8116
8117 llvm::SmallVector<const NamedDecl*, 4> Candidates;
8118 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8119 !Found && I != E; ++I) {
Aaron Ballman86c93902014-03-06 23:45:36 +00008120 for (auto RI : (*I)->redecls()) {
8121 if (RI->getLexicalDeclContext() == CanonDef) {
Richard Smith2b9e3e32013-10-18 06:05:18 +00008122 // This declaration is present in the canonical definition. If it's
8123 // in the same redecl chain, it's the one we're looking for.
Aaron Ballman86c93902014-03-06 23:45:36 +00008124 if (RI->getCanonicalDecl() == DCanon)
Richard Smith2b9e3e32013-10-18 06:05:18 +00008125 Found = true;
8126 else
Aaron Ballman86c93902014-03-06 23:45:36 +00008127 Candidates.push_back(cast<NamedDecl>(RI));
Richard Smith2b9e3e32013-10-18 06:05:18 +00008128 break;
8129 }
8130 }
8131 }
8132
8133 if (!Found) {
8134 D->setInvalidDecl();
8135
Richard Smithcd45dbc2014-04-19 03:48:30 +00008136 std::string CanonDefModule =
8137 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
Richard Smith2b9e3e32013-10-18 06:05:18 +00008138 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008139 << D << getOwningModuleNameForDiagnostic(D)
8140 << CanonDef << CanonDefModule.empty() << CanonDefModule;
Richard Smith2b9e3e32013-10-18 06:05:18 +00008141
8142 if (Candidates.empty())
8143 Diag(cast<Decl>(CanonDef)->getLocation(),
8144 diag::note_module_odr_violation_no_possible_decls) << D;
8145 else {
8146 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8147 Diag(Candidates[I]->getLocation(),
8148 diag::note_module_odr_violation_possible_decl)
8149 << Candidates[I];
8150 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008151
8152 DiagnosedOdrMergeFailures.insert(CanonDef);
Richard Smith2b9e3e32013-10-18 06:05:18 +00008153 }
8154 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008155 }
8156
8157 // If we deserialized any C++ or Objective-C class definitions, any
8158 // Objective-C protocol definitions, or any redeclarable templates, make sure
8159 // that all redeclarations point to the definitions. Note that this can only
8160 // happen now, after the redeclaration chains have been fully wired.
8161 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
8162 DEnd = PendingDefinitions.end();
8163 D != DEnd; ++D) {
8164 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008165 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008166 // Make sure that the TagType points at the definition.
8167 const_cast<TagType*>(TagT)->decl = TD;
8168 }
8169
Aaron Ballman86c93902014-03-06 23:45:36 +00008170 if (auto RD = dyn_cast<CXXRecordDecl>(*D)) {
8171 for (auto R : RD->redecls())
8172 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Guy Benyei11169dd2012-12-18 14:30:41 +00008173 }
8174
8175 continue;
8176 }
8177
Aaron Ballman86c93902014-03-06 23:45:36 +00008178 if (auto ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008179 // Make sure that the ObjCInterfaceType points at the definition.
8180 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8181 ->Decl = ID;
8182
Aaron Ballman86c93902014-03-06 23:45:36 +00008183 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008184 R->Data = ID->Data;
8185
8186 continue;
8187 }
8188
Aaron Ballman86c93902014-03-06 23:45:36 +00008189 if (auto PD = dyn_cast<ObjCProtocolDecl>(*D)) {
8190 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008191 R->Data = PD->Data;
8192
8193 continue;
8194 }
8195
Aaron Ballman86c93902014-03-06 23:45:36 +00008196 auto RTD = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
8197 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008198 R->Common = RTD->Common;
8199 }
8200 PendingDefinitions.clear();
8201
8202 // Load the bodies of any functions or methods we've encountered. We do
8203 // this now (delayed) so that we can be sure that the declaration chains
8204 // have been fully wired up.
8205 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8206 PBEnd = PendingBodies.end();
8207 PB != PBEnd; ++PB) {
8208 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8209 // FIXME: Check for =delete/=default?
8210 // FIXME: Complain about ODR violations here?
8211 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8212 FD->setLazyBody(PB->second);
8213 continue;
8214 }
8215
8216 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8217 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8218 MD->setLazyBody(PB->second);
8219 }
8220 PendingBodies.clear();
Richard Smithcd45dbc2014-04-19 03:48:30 +00008221
8222 // Issue any pending ODR-failure diagnostics.
8223 for (auto &Merge : PendingOdrMergeFailures) {
8224 if (!DiagnosedOdrMergeFailures.insert(Merge.first))
8225 continue;
8226
8227 bool Diagnosed = false;
8228 for (auto *RD : Merge.second) {
8229 // Multiple different declarations got merged together; tell the user
8230 // where they came from.
8231 if (Merge.first != RD) {
8232 // FIXME: Walk the definition, figure out what's different,
8233 // and diagnose that.
8234 if (!Diagnosed) {
8235 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8236 Diag(Merge.first->getLocation(),
8237 diag::err_module_odr_violation_different_definitions)
8238 << Merge.first << Module.empty() << Module;
8239 Diagnosed = true;
8240 }
8241
8242 Diag(RD->getLocation(),
8243 diag::note_module_odr_violation_different_definitions)
8244 << getOwningModuleNameForDiagnostic(RD);
8245 }
8246 }
8247
8248 if (!Diagnosed) {
8249 // All definitions are updates to the same declaration. This happens if a
8250 // module instantiates the declaration of a class template specialization
8251 // and two or more other modules instantiate its definition.
8252 //
8253 // FIXME: Indicate which modules had instantiations of this definition.
8254 // FIXME: How can this even happen?
8255 Diag(Merge.first->getLocation(),
8256 diag::err_module_odr_violation_different_instantiations)
8257 << Merge.first;
8258 }
8259 }
8260 PendingOdrMergeFailures.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00008261}
8262
8263void ASTReader::FinishedDeserializing() {
8264 assert(NumCurrentElementsDeserializing &&
8265 "FinishedDeserializing not paired with StartedDeserializing");
8266 if (NumCurrentElementsDeserializing == 1) {
8267 // We decrease NumCurrentElementsDeserializing only after pending actions
8268 // are finished, to avoid recursively re-calling finishPendingActions().
8269 finishPendingActions();
8270 }
8271 --NumCurrentElementsDeserializing;
8272
Richard Smith04d05b52014-03-23 00:27:18 +00008273 if (NumCurrentElementsDeserializing == 0 && Consumer) {
8274 // We are not in recursive loading, so it's safe to pass the "interesting"
8275 // decls to the consumer.
8276 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008277 }
8278}
8279
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008280void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00008281 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008282
8283 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8284 SemaObj->TUScope->AddDecl(D);
8285 } else if (SemaObj->TUScope) {
8286 // Adding the decl to IdResolver may have failed because it was already in
8287 // (even though it was not added in scope). If it is already in, make sure
8288 // it gets in the scope as well.
8289 if (std::find(SemaObj->IdResolver.begin(Name),
8290 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8291 SemaObj->TUScope->AddDecl(D);
8292 }
8293}
8294
Nico Weber824285e2014-05-08 04:26:47 +00008295ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8296 bool DisableValidation, bool AllowASTWithCompilerErrors,
8297 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008298 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008299 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008300 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Craig Toppera13603a2014-05-22 05:54:18 +00008301 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
8302 SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
8303 ModuleMgr(PP.getFileManager()), isysroot(isysroot),
8304 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008305 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8306 AllowConfigurationMismatch(AllowConfigurationMismatch),
8307 ValidateSystemInputs(ValidateSystemInputs),
8308 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Richard Smith053f6c62014-05-16 23:01:30 +00008309 CurrSwitchCaseStmts(&SwitchCaseStmts),
Nico Weber824285e2014-05-08 04:26:47 +00008310 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8311 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8312 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8313 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8314 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8315 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8316 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8317 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8318 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8319 PassingDeclsToConsumer(false), NumCXXBaseSpecifiersLoaded(0),
8320 ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008321 SourceMgr.setExternalSLocEntrySource(this);
8322}
8323
8324ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008325 if (OwnsDeserializationListener)
8326 delete DeserializationListener;
8327
Guy Benyei11169dd2012-12-18 14:30:41 +00008328 for (DeclContextVisibleUpdatesPending::iterator
8329 I = PendingVisibleUpdates.begin(),
8330 E = PendingVisibleUpdates.end();
8331 I != E; ++I) {
8332 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8333 F = I->second.end();
8334 J != F; ++J)
8335 delete J->first;
8336 }
8337}