blob: f668e28c1af91e99ae951bd288d893fa779dc092 [file] [log] [blame]
Nick Lewyckyf0f56162013-01-31 03:23:57 +00001//===--- ASTReader.cpp - AST File Reader ----------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the ASTReader class, which reads AST files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Serialization/ASTReader.h"
15#include "ASTCommon.h"
16#include "ASTReaderInternals.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/NestedNameSpecifier.h"
23#include "clang/AST/Type.h"
24#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000025#include "clang/Basic/DiagnosticOptions.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000026#include "clang/Basic/FileManager.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000027#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/SourceManagerInternals.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Basic/TargetOptions.h"
31#include "clang/Basic/Version.h"
32#include "clang/Basic/VersionTuple.h"
Ben Langmuirb92de022014-04-29 16:25:26 +000033#include "clang/Frontend/Utils.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000034#include "clang/Lex/HeaderSearch.h"
35#include "clang/Lex/HeaderSearchOptions.h"
36#include "clang/Lex/MacroInfo.h"
37#include "clang/Lex/PreprocessingRecord.h"
38#include "clang/Lex/Preprocessor.h"
39#include "clang/Lex/PreprocessorOptions.h"
40#include "clang/Sema/Scope.h"
41#include "clang/Sema/Sema.h"
42#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000043#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000044#include "clang/Serialization/ModuleManager.h"
45#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000046#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000047#include "llvm/ADT/StringExtras.h"
48#include "llvm/Bitcode/BitstreamReader.h"
49#include "llvm/Support/ErrorHandling.h"
50#include "llvm/Support/FileSystem.h"
51#include "llvm/Support/MemoryBuffer.h"
52#include "llvm/Support/Path.h"
53#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000054#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000055#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000056#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000057#include <iterator>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000058#include <system_error>
Guy Benyei11169dd2012-12-18 14:30:41 +000059
60using namespace clang;
61using namespace clang::serialization;
62using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000063using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000064
Ben Langmuircb69b572014-03-07 06:40:32 +000065
66//===----------------------------------------------------------------------===//
67// ChainedASTReaderListener implementation
68//===----------------------------------------------------------------------===//
69
70bool
71ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
72 return First->ReadFullVersionInformation(FullVersion) ||
73 Second->ReadFullVersionInformation(FullVersion);
74}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000075void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
76 First->ReadModuleName(ModuleName);
77 Second->ReadModuleName(ModuleName);
78}
79void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
80 First->ReadModuleMapFile(ModuleMapPath);
81 Second->ReadModuleMapFile(ModuleMapPath);
82}
Ben Langmuircb69b572014-03-07 06:40:32 +000083bool ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
84 bool Complain) {
85 return First->ReadLanguageOptions(LangOpts, Complain) ||
86 Second->ReadLanguageOptions(LangOpts, Complain);
87}
88bool
89ChainedASTReaderListener::ReadTargetOptions(const TargetOptions &TargetOpts,
90 bool Complain) {
91 return First->ReadTargetOptions(TargetOpts, Complain) ||
92 Second->ReadTargetOptions(TargetOpts, Complain);
93}
94bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +000095 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +000096 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
97 Second->ReadDiagnosticOptions(DiagOpts, Complain);
98}
99bool
100ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
101 bool Complain) {
102 return First->ReadFileSystemOptions(FSOpts, Complain) ||
103 Second->ReadFileSystemOptions(FSOpts, Complain);
104}
105
106bool ChainedASTReaderListener::ReadHeaderSearchOptions(
107 const HeaderSearchOptions &HSOpts, bool Complain) {
108 return First->ReadHeaderSearchOptions(HSOpts, Complain) ||
109 Second->ReadHeaderSearchOptions(HSOpts, Complain);
110}
111bool ChainedASTReaderListener::ReadPreprocessorOptions(
112 const PreprocessorOptions &PPOpts, bool Complain,
113 std::string &SuggestedPredefines) {
114 return First->ReadPreprocessorOptions(PPOpts, Complain,
115 SuggestedPredefines) ||
116 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
117}
118void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
119 unsigned Value) {
120 First->ReadCounter(M, Value);
121 Second->ReadCounter(M, Value);
122}
123bool ChainedASTReaderListener::needsInputFileVisitation() {
124 return First->needsInputFileVisitation() ||
125 Second->needsInputFileVisitation();
126}
127bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
128 return First->needsSystemInputFileVisitation() ||
129 Second->needsSystemInputFileVisitation();
130}
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000131void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
132 First->visitModuleFile(Filename);
133 Second->visitModuleFile(Filename);
134}
Ben Langmuircb69b572014-03-07 06:40:32 +0000135bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000136 bool isSystem,
137 bool isOverridden) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000138 bool Continue = false;
139 if (First->needsInputFileVisitation() &&
140 (!isSystem || First->needsSystemInputFileVisitation()))
141 Continue |= First->visitInputFile(Filename, isSystem, isOverridden);
142 if (Second->needsInputFileVisitation() &&
143 (!isSystem || Second->needsSystemInputFileVisitation()))
144 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden);
145 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000146}
147
Guy Benyei11169dd2012-12-18 14:30:41 +0000148//===----------------------------------------------------------------------===//
149// PCH validator implementation
150//===----------------------------------------------------------------------===//
151
152ASTReaderListener::~ASTReaderListener() {}
153
154/// \brief Compare the given set of language options against an existing set of
155/// language options.
156///
157/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
158///
159/// \returns true if the languagae options mis-match, false otherwise.
160static bool checkLanguageOptions(const LangOptions &LangOpts,
161 const LangOptions &ExistingLangOpts,
162 DiagnosticsEngine *Diags) {
163#define LANGOPT(Name, Bits, Default, Description) \
164 if (ExistingLangOpts.Name != LangOpts.Name) { \
165 if (Diags) \
166 Diags->Report(diag::err_pch_langopt_mismatch) \
167 << Description << LangOpts.Name << ExistingLangOpts.Name; \
168 return true; \
169 }
170
171#define VALUE_LANGOPT(Name, Bits, Default, Description) \
172 if (ExistingLangOpts.Name != LangOpts.Name) { \
173 if (Diags) \
174 Diags->Report(diag::err_pch_langopt_value_mismatch) \
175 << Description; \
176 return true; \
177 }
178
179#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
180 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
181 if (Diags) \
182 Diags->Report(diag::err_pch_langopt_value_mismatch) \
183 << Description; \
184 return true; \
185 }
186
187#define BENIGN_LANGOPT(Name, Bits, Default, Description)
188#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
189#include "clang/Basic/LangOptions.def"
190
191 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
192 if (Diags)
193 Diags->Report(diag::err_pch_langopt_value_mismatch)
194 << "target Objective-C runtime";
195 return true;
196 }
197
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000198 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
199 LangOpts.CommentOpts.BlockCommandNames) {
200 if (Diags)
201 Diags->Report(diag::err_pch_langopt_value_mismatch)
202 << "block command names";
203 return true;
204 }
205
Guy Benyei11169dd2012-12-18 14:30:41 +0000206 return false;
207}
208
209/// \brief Compare the given set of target options against an existing set of
210/// target options.
211///
212/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
213///
214/// \returns true if the target options mis-match, false otherwise.
215static bool checkTargetOptions(const TargetOptions &TargetOpts,
216 const TargetOptions &ExistingTargetOpts,
217 DiagnosticsEngine *Diags) {
218#define CHECK_TARGET_OPT(Field, Name) \
219 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
220 if (Diags) \
221 Diags->Report(diag::err_pch_targetopt_mismatch) \
222 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
223 return true; \
224 }
225
226 CHECK_TARGET_OPT(Triple, "target");
227 CHECK_TARGET_OPT(CPU, "target CPU");
228 CHECK_TARGET_OPT(ABI, "target ABI");
Guy Benyei11169dd2012-12-18 14:30:41 +0000229#undef CHECK_TARGET_OPT
230
231 // Compare feature sets.
232 SmallVector<StringRef, 4> ExistingFeatures(
233 ExistingTargetOpts.FeaturesAsWritten.begin(),
234 ExistingTargetOpts.FeaturesAsWritten.end());
235 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
236 TargetOpts.FeaturesAsWritten.end());
237 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
238 std::sort(ReadFeatures.begin(), ReadFeatures.end());
239
240 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
241 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
242 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
243 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
244 ++ExistingIdx;
245 ++ReadIdx;
246 continue;
247 }
248
249 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
250 if (Diags)
251 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
252 << false << ReadFeatures[ReadIdx];
253 return true;
254 }
255
256 if (Diags)
257 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
258 << true << ExistingFeatures[ExistingIdx];
259 return true;
260 }
261
262 if (ExistingIdx < ExistingN) {
263 if (Diags)
264 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
265 << true << ExistingFeatures[ExistingIdx];
266 return true;
267 }
268
269 if (ReadIdx < ReadN) {
270 if (Diags)
271 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
272 << false << ReadFeatures[ReadIdx];
273 return true;
274 }
275
276 return false;
277}
278
279bool
280PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
281 bool Complain) {
282 const LangOptions &ExistingLangOpts = PP.getLangOpts();
283 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000284 Complain? &Reader.Diags : nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000285}
286
287bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
288 bool Complain) {
289 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
290 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000291 Complain? &Reader.Diags : nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000292}
293
294namespace {
295 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
296 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000297 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
298 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000299}
300
Ben Langmuirb92de022014-04-29 16:25:26 +0000301static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
302 DiagnosticsEngine &Diags,
303 bool Complain) {
304 typedef DiagnosticsEngine::Level Level;
305
306 // Check current mappings for new -Werror mappings, and the stored mappings
307 // for cases that were explicitly mapped to *not* be errors that are now
308 // errors because of options like -Werror.
309 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
310
311 for (DiagnosticsEngine *MappingSource : MappingSources) {
312 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
313 diag::kind DiagID = DiagIDMappingPair.first;
314 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
315 if (CurLevel < DiagnosticsEngine::Error)
316 continue; // not significant
317 Level StoredLevel =
318 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
319 if (StoredLevel < DiagnosticsEngine::Error) {
320 if (Complain)
321 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
322 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
323 return true;
324 }
325 }
326 }
327
328 return false;
329}
330
Alp Tokerac4e8e52014-06-22 21:58:33 +0000331static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
332 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
333 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
334 return true;
335 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000336}
337
338static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
339 DiagnosticsEngine &Diags,
340 bool IsSystem, bool Complain) {
341 // Top-level options
342 if (IsSystem) {
343 if (Diags.getSuppressSystemWarnings())
344 return false;
345 // If -Wsystem-headers was not enabled before, be conservative
346 if (StoredDiags.getSuppressSystemWarnings()) {
347 if (Complain)
348 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
349 return true;
350 }
351 }
352
353 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
354 if (Complain)
355 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
356 return true;
357 }
358
359 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
360 !StoredDiags.getEnableAllWarnings()) {
361 if (Complain)
362 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
363 return true;
364 }
365
366 if (isExtHandlingFromDiagsError(Diags) &&
367 !isExtHandlingFromDiagsError(StoredDiags)) {
368 if (Complain)
369 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
370 return true;
371 }
372
373 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
374}
375
376bool PCHValidator::ReadDiagnosticOptions(
377 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
378 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
379 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
380 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000381 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000382 // This should never fail, because we would have processed these options
383 // before writing them to an ASTFile.
384 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
385
386 ModuleManager &ModuleMgr = Reader.getModuleManager();
387 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
388
389 // If the original import came from a file explicitly generated by the user,
390 // don't check the diagnostic mappings.
391 // FIXME: currently this is approximated by checking whether this is not a
392 // module import.
393 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
394 // the transitive closure of its imports, since unrelated modules cannot be
395 // imported until after this module finishes validation.
396 ModuleFile *TopImport = *ModuleMgr.rbegin();
397 while (!TopImport->ImportedBy.empty())
398 TopImport = TopImport->ImportedBy[0];
399 if (TopImport->Kind != MK_Module)
400 return false;
401
402 StringRef ModuleName = TopImport->ModuleName;
403 assert(!ModuleName.empty() && "diagnostic options read before module name");
404
405 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
406 assert(M && "missing module");
407
408 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
409 // contains the union of their flags.
410 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
411}
412
Guy Benyei11169dd2012-12-18 14:30:41 +0000413/// \brief Collect the macro definitions provided by the given preprocessor
414/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000415static void
416collectMacroDefinitions(const PreprocessorOptions &PPOpts,
417 MacroDefinitionsMap &Macros,
418 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000419 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
420 StringRef Macro = PPOpts.Macros[I].first;
421 bool IsUndef = PPOpts.Macros[I].second;
422
423 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
424 StringRef MacroName = MacroPair.first;
425 StringRef MacroBody = MacroPair.second;
426
427 // For an #undef'd macro, we only care about the name.
428 if (IsUndef) {
429 if (MacroNames && !Macros.count(MacroName))
430 MacroNames->push_back(MacroName);
431
432 Macros[MacroName] = std::make_pair("", true);
433 continue;
434 }
435
436 // For a #define'd macro, figure out the actual definition.
437 if (MacroName.size() == Macro.size())
438 MacroBody = "1";
439 else {
440 // Note: GCC drops anything following an end-of-line character.
441 StringRef::size_type End = MacroBody.find_first_of("\n\r");
442 MacroBody = MacroBody.substr(0, End);
443 }
444
445 if (MacroNames && !Macros.count(MacroName))
446 MacroNames->push_back(MacroName);
447 Macros[MacroName] = std::make_pair(MacroBody, false);
448 }
449}
450
451/// \brief Check the preprocessor options deserialized from the control block
452/// against the preprocessor options in an existing preprocessor.
453///
454/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
455static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
456 const PreprocessorOptions &ExistingPPOpts,
457 DiagnosticsEngine *Diags,
458 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000459 std::string &SuggestedPredefines,
460 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000461 // Check macro definitions.
462 MacroDefinitionsMap ASTFileMacros;
463 collectMacroDefinitions(PPOpts, ASTFileMacros);
464 MacroDefinitionsMap ExistingMacros;
465 SmallVector<StringRef, 4> ExistingMacroNames;
466 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
467
468 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
469 // Dig out the macro definition in the existing preprocessor options.
470 StringRef MacroName = ExistingMacroNames[I];
471 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
472
473 // Check whether we know anything about this macro name or not.
474 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
475 = ASTFileMacros.find(MacroName);
476 if (Known == ASTFileMacros.end()) {
477 // FIXME: Check whether this identifier was referenced anywhere in the
478 // AST file. If so, we should reject the AST file. Unfortunately, this
479 // information isn't in the control block. What shall we do about it?
480
481 if (Existing.second) {
482 SuggestedPredefines += "#undef ";
483 SuggestedPredefines += MacroName.str();
484 SuggestedPredefines += '\n';
485 } else {
486 SuggestedPredefines += "#define ";
487 SuggestedPredefines += MacroName.str();
488 SuggestedPredefines += ' ';
489 SuggestedPredefines += Existing.first.str();
490 SuggestedPredefines += '\n';
491 }
492 continue;
493 }
494
495 // If the macro was defined in one but undef'd in the other, we have a
496 // conflict.
497 if (Existing.second != Known->second.second) {
498 if (Diags) {
499 Diags->Report(diag::err_pch_macro_def_undef)
500 << MacroName << Known->second.second;
501 }
502 return true;
503 }
504
505 // If the macro was #undef'd in both, or if the macro bodies are identical,
506 // it's fine.
507 if (Existing.second || Existing.first == Known->second.first)
508 continue;
509
510 // The macro bodies differ; complain.
511 if (Diags) {
512 Diags->Report(diag::err_pch_macro_def_conflict)
513 << MacroName << Known->second.first << Existing.first;
514 }
515 return true;
516 }
517
518 // Check whether we're using predefines.
519 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
520 if (Diags) {
521 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
522 }
523 return true;
524 }
525
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000526 // Detailed record is important since it is used for the module cache hash.
527 if (LangOpts.Modules &&
528 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
529 if (Diags) {
530 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
531 }
532 return true;
533 }
534
Guy Benyei11169dd2012-12-18 14:30:41 +0000535 // Compute the #include and #include_macros lines we need.
536 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
537 StringRef File = ExistingPPOpts.Includes[I];
538 if (File == ExistingPPOpts.ImplicitPCHInclude)
539 continue;
540
541 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
542 != PPOpts.Includes.end())
543 continue;
544
545 SuggestedPredefines += "#include \"";
546 SuggestedPredefines +=
547 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
548 SuggestedPredefines += "\"\n";
549 }
550
551 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
552 StringRef File = ExistingPPOpts.MacroIncludes[I];
553 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
554 File)
555 != PPOpts.MacroIncludes.end())
556 continue;
557
558 SuggestedPredefines += "#__include_macros \"";
559 SuggestedPredefines +=
560 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
561 SuggestedPredefines += "\"\n##\n";
562 }
563
564 return false;
565}
566
567bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
568 bool Complain,
569 std::string &SuggestedPredefines) {
570 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
571
572 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000573 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000574 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000575 SuggestedPredefines,
576 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000577}
578
Guy Benyei11169dd2012-12-18 14:30:41 +0000579void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
580 PP.setCounterValue(Value);
581}
582
583//===----------------------------------------------------------------------===//
584// AST reader implementation
585//===----------------------------------------------------------------------===//
586
Nico Weber824285e2014-05-08 04:26:47 +0000587void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
588 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000589 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000590 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000591}
592
593
594
595unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
596 return serialization::ComputeHash(Sel);
597}
598
599
600std::pair<unsigned, unsigned>
601ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000602 using namespace llvm::support;
603 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
604 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000605 return std::make_pair(KeyLen, DataLen);
606}
607
608ASTSelectorLookupTrait::internal_key_type
609ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000610 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000611 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000612 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
613 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
614 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000615 if (N == 0)
616 return SelTable.getNullarySelector(FirstII);
617 else if (N == 1)
618 return SelTable.getUnarySelector(FirstII);
619
620 SmallVector<IdentifierInfo *, 16> Args;
621 Args.push_back(FirstII);
622 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000623 Args.push_back(Reader.getLocalIdentifier(
624 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000625
626 return SelTable.getSelector(N, Args.data());
627}
628
629ASTSelectorLookupTrait::data_type
630ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
631 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000632 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000633
634 data_type Result;
635
Justin Bogner57ba0b22014-03-28 22:03:24 +0000636 Result.ID = Reader.getGlobalSelectorID(
637 F, endian::readNext<uint32_t, little, unaligned>(d));
638 unsigned NumInstanceMethodsAndBits =
639 endian::readNext<uint16_t, little, unaligned>(d);
640 unsigned NumFactoryMethodsAndBits =
641 endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +0000642 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
643 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
644 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
645 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
Guy Benyei11169dd2012-12-18 14:30:41 +0000646
647 // Load instance methods
648 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000649 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
650 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000651 Result.Instance.push_back(Method);
652 }
653
654 // Load factory methods
655 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000656 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
657 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000658 Result.Factory.push_back(Method);
659 }
660
661 return Result;
662}
663
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000664unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
665 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000666}
667
668std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000669ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000670 using namespace llvm::support;
671 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
672 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000673 return std::make_pair(KeyLen, DataLen);
674}
675
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000676ASTIdentifierLookupTraitBase::internal_key_type
677ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000678 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000679 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000680}
681
Douglas Gregordcf25082013-02-11 18:16:18 +0000682/// \brief Whether the given identifier is "interesting".
683static bool isInterestingIdentifier(IdentifierInfo &II) {
684 return II.isPoisoned() ||
685 II.isExtensionToken() ||
686 II.getObjCOrBuiltinID() ||
687 II.hasRevertedTokenIDToIdentifier() ||
688 II.hadMacroDefinition() ||
689 II.getFETokenInfo<void>();
690}
691
Guy Benyei11169dd2012-12-18 14:30:41 +0000692IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
693 const unsigned char* d,
694 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000695 using namespace llvm::support;
696 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000697 bool IsInteresting = RawID & 0x01;
698
699 // Wipe out the "is interesting" bit.
700 RawID = RawID >> 1;
701
702 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
703 if (!IsInteresting) {
704 // For uninteresting identifiers, just build the IdentifierInfo
705 // and associate it with the persistent ID.
706 IdentifierInfo *II = KnownII;
707 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000708 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000709 KnownII = II;
710 }
711 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000712 if (!II->isFromAST()) {
713 bool WasInteresting = isInterestingIdentifier(*II);
714 II->setIsFromAST();
715 if (WasInteresting)
716 II->setChangedSinceDeserialization();
717 }
718 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000719 return II;
720 }
721
Justin Bogner57ba0b22014-03-28 22:03:24 +0000722 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
723 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000724 bool CPlusPlusOperatorKeyword = Bits & 0x01;
725 Bits >>= 1;
726 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
727 Bits >>= 1;
728 bool Poisoned = Bits & 0x01;
729 Bits >>= 1;
730 bool ExtensionToken = Bits & 0x01;
731 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000732 bool hasSubmoduleMacros = Bits & 0x01;
733 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000734 bool hadMacroDefinition = Bits & 0x01;
735 Bits >>= 1;
736
737 assert(Bits == 0 && "Extra bits in the identifier?");
738 DataLen -= 8;
739
740 // Build the IdentifierInfo itself and link the identifier ID with
741 // the new IdentifierInfo.
742 IdentifierInfo *II = KnownII;
743 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000744 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000745 KnownII = II;
746 }
747 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000748 if (!II->isFromAST()) {
749 bool WasInteresting = isInterestingIdentifier(*II);
750 II->setIsFromAST();
751 if (WasInteresting)
752 II->setChangedSinceDeserialization();
753 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000754
755 // Set or check the various bits in the IdentifierInfo structure.
756 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000757 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000758 II->RevertTokenIDToIdentifier();
759 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
760 assert(II->isExtensionToken() == ExtensionToken &&
761 "Incorrect extension token flag");
762 (void)ExtensionToken;
763 if (Poisoned)
764 II->setIsPoisoned(true);
765 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
766 "Incorrect C++ operator keyword flag");
767 (void)CPlusPlusOperatorKeyword;
768
769 // If this identifier is a macro, deserialize the macro
770 // definition.
771 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000772 uint32_t MacroDirectivesOffset =
773 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000774 DataLen -= 4;
775 SmallVector<uint32_t, 8> LocalMacroIDs;
776 if (hasSubmoduleMacros) {
Richard Smithdaa69e02014-07-25 04:40:03 +0000777 while (true) {
778 uint32_t LocalMacroID =
779 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000780 DataLen -= 4;
Richard Smithdaa69e02014-07-25 04:40:03 +0000781 if (LocalMacroID == 0xdeadbeef) break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000782 LocalMacroIDs.push_back(LocalMacroID);
783 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000784 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000785
786 if (F.Kind == MK_Module) {
Richard Smith49f906a2014-03-01 00:08:04 +0000787 // Macro definitions are stored from newest to oldest, so reverse them
788 // before registering them.
789 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000790 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000791 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
792 unsigned Size = 1;
793
794 static const uint32_t HasOverridesFlag = 0x80000000U;
795 if (I + 1 != E && (I[1] & HasOverridesFlag))
796 Size += 1 + (I[1] & ~HasOverridesFlag);
797
798 MacroSizes.push_back(Size);
799 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000800 }
Richard Smith49f906a2014-03-01 00:08:04 +0000801
802 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
803 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
804 SE = MacroSizes.rend();
805 SI != SE; ++SI) {
806 I -= *SI;
807
808 uint32_t LocalMacroID = *I;
Craig Topper00bbdcf2014-06-28 23:22:23 +0000809 ArrayRef<uint32_t> Overrides;
Richard Smith49f906a2014-03-01 00:08:04 +0000810 if (*SI != 1)
811 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
812 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
813 }
814 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000815 } else {
816 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
817 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000818 }
819
820 Reader.SetIdentifierInfo(ID, II);
821
822 // Read all of the declarations visible at global scope with this
823 // name.
824 if (DataLen > 0) {
825 SmallVector<uint32_t, 4> DeclIDs;
826 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000827 DeclIDs.push_back(Reader.getGlobalDeclID(
828 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000829 Reader.SetGloballyVisibleDecls(II, DeclIDs);
830 }
831
832 return II;
833}
834
835unsigned
836ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
837 llvm::FoldingSetNodeID ID;
838 ID.AddInteger(Key.Kind);
839
840 switch (Key.Kind) {
841 case DeclarationName::Identifier:
842 case DeclarationName::CXXLiteralOperatorName:
843 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
844 break;
845 case DeclarationName::ObjCZeroArgSelector:
846 case DeclarationName::ObjCOneArgSelector:
847 case DeclarationName::ObjCMultiArgSelector:
848 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
849 break;
850 case DeclarationName::CXXOperatorName:
851 ID.AddInteger((OverloadedOperatorKind)Key.Data);
852 break;
853 case DeclarationName::CXXConstructorName:
854 case DeclarationName::CXXDestructorName:
855 case DeclarationName::CXXConversionFunctionName:
856 case DeclarationName::CXXUsingDirective:
857 break;
858 }
859
860 return ID.ComputeHash();
861}
862
863ASTDeclContextNameLookupTrait::internal_key_type
864ASTDeclContextNameLookupTrait::GetInternalKey(
865 const external_key_type& Name) const {
866 DeclNameKey Key;
867 Key.Kind = Name.getNameKind();
868 switch (Name.getNameKind()) {
869 case DeclarationName::Identifier:
870 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
871 break;
872 case DeclarationName::ObjCZeroArgSelector:
873 case DeclarationName::ObjCOneArgSelector:
874 case DeclarationName::ObjCMultiArgSelector:
875 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
876 break;
877 case DeclarationName::CXXOperatorName:
878 Key.Data = Name.getCXXOverloadedOperator();
879 break;
880 case DeclarationName::CXXLiteralOperatorName:
881 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
882 break;
883 case DeclarationName::CXXConstructorName:
884 case DeclarationName::CXXDestructorName:
885 case DeclarationName::CXXConversionFunctionName:
886 case DeclarationName::CXXUsingDirective:
887 Key.Data = 0;
888 break;
889 }
890
891 return Key;
892}
893
894std::pair<unsigned, unsigned>
895ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000896 using namespace llvm::support;
897 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
898 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000899 return std::make_pair(KeyLen, DataLen);
900}
901
902ASTDeclContextNameLookupTrait::internal_key_type
903ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000904 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000905
906 DeclNameKey Key;
907 Key.Kind = (DeclarationName::NameKind)*d++;
908 switch (Key.Kind) {
909 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000910 Key.Data = (uint64_t)Reader.getLocalIdentifier(
911 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000912 break;
913 case DeclarationName::ObjCZeroArgSelector:
914 case DeclarationName::ObjCOneArgSelector:
915 case DeclarationName::ObjCMultiArgSelector:
916 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000917 (uint64_t)Reader.getLocalSelector(
918 F, endian::readNext<uint32_t, little, unaligned>(
919 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000920 break;
921 case DeclarationName::CXXOperatorName:
922 Key.Data = *d++; // OverloadedOperatorKind
923 break;
924 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000925 Key.Data = (uint64_t)Reader.getLocalIdentifier(
926 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000927 break;
928 case DeclarationName::CXXConstructorName:
929 case DeclarationName::CXXDestructorName:
930 case DeclarationName::CXXConversionFunctionName:
931 case DeclarationName::CXXUsingDirective:
932 Key.Data = 0;
933 break;
934 }
935
936 return Key;
937}
938
939ASTDeclContextNameLookupTrait::data_type
940ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
941 const unsigned char* d,
942 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000943 using namespace llvm::support;
944 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000945 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
946 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000947 return std::make_pair(Start, Start + NumDecls);
948}
949
950bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000951 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000952 const std::pair<uint64_t, uint64_t> &Offsets,
953 DeclContextInfo &Info) {
954 SavedStreamPosition SavedPosition(Cursor);
955 // First the lexical decls.
956 if (Offsets.first != 0) {
957 Cursor.JumpToBit(Offsets.first);
958
959 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000960 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000961 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000962 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000963 if (RecCode != DECL_CONTEXT_LEXICAL) {
964 Error("Expected lexical block");
965 return true;
966 }
967
Chris Lattner0e6c9402013-01-20 02:38:54 +0000968 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
969 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000970 }
971
972 // Now the lookup table.
973 if (Offsets.second != 0) {
974 Cursor.JumpToBit(Offsets.second);
975
976 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000977 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000978 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000979 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000980 if (RecCode != DECL_CONTEXT_VISIBLE) {
981 Error("Expected visible lookup table block");
982 return true;
983 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000984 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
985 (const unsigned char *)Blob.data() + Record[0],
986 (const unsigned char *)Blob.data() + sizeof(uint32_t),
987 (const unsigned char *)Blob.data(),
988 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +0000989 }
990
991 return false;
992}
993
994void ASTReader::Error(StringRef Msg) {
995 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +0000996 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
997 Diag(diag::note_module_cache_path)
998 << PP.getHeaderSearchInfo().getModuleCachePath();
999 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001000}
1001
1002void ASTReader::Error(unsigned DiagID,
1003 StringRef Arg1, StringRef Arg2) {
1004 if (Diags.isDiagnosticInFlight())
1005 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1006 else
1007 Diag(DiagID) << Arg1 << Arg2;
1008}
1009
1010//===----------------------------------------------------------------------===//
1011// Source Manager Deserialization
1012//===----------------------------------------------------------------------===//
1013
1014/// \brief Read the line table in the source manager block.
1015/// \returns true if there was an error.
1016bool ASTReader::ParseLineTable(ModuleFile &F,
1017 SmallVectorImpl<uint64_t> &Record) {
1018 unsigned Idx = 0;
1019 LineTableInfo &LineTable = SourceMgr.getLineTable();
1020
1021 // Parse the file names
1022 std::map<int, int> FileIDs;
1023 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1024 // Extract the file name
1025 unsigned FilenameLen = Record[Idx++];
1026 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
1027 Idx += FilenameLen;
1028 MaybeAddSystemRootToFilename(F, Filename);
1029 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1030 }
1031
1032 // Parse the line entries
1033 std::vector<LineEntry> Entries;
1034 while (Idx < Record.size()) {
1035 int FID = Record[Idx++];
1036 assert(FID >= 0 && "Serialized line entries for non-local file.");
1037 // Remap FileID from 1-based old view.
1038 FID += F.SLocEntryBaseID - 1;
1039
1040 // Extract the line entries
1041 unsigned NumEntries = Record[Idx++];
1042 assert(NumEntries && "Numentries is 00000");
1043 Entries.clear();
1044 Entries.reserve(NumEntries);
1045 for (unsigned I = 0; I != NumEntries; ++I) {
1046 unsigned FileOffset = Record[Idx++];
1047 unsigned LineNo = Record[Idx++];
1048 int FilenameID = FileIDs[Record[Idx++]];
1049 SrcMgr::CharacteristicKind FileKind
1050 = (SrcMgr::CharacteristicKind)Record[Idx++];
1051 unsigned IncludeOffset = Record[Idx++];
1052 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1053 FileKind, IncludeOffset));
1054 }
1055 LineTable.AddEntry(FileID::get(FID), Entries);
1056 }
1057
1058 return false;
1059}
1060
1061/// \brief Read a source manager block
1062bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1063 using namespace SrcMgr;
1064
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001065 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001066
1067 // Set the source-location entry cursor to the current position in
1068 // the stream. This cursor will be used to read the contents of the
1069 // source manager block initially, and then lazily read
1070 // source-location entries as needed.
1071 SLocEntryCursor = F.Stream;
1072
1073 // The stream itself is going to skip over the source manager block.
1074 if (F.Stream.SkipBlock()) {
1075 Error("malformed block record in AST file");
1076 return true;
1077 }
1078
1079 // Enter the source manager block.
1080 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1081 Error("malformed source manager block record in AST file");
1082 return true;
1083 }
1084
1085 RecordData Record;
1086 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001087 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1088
1089 switch (E.Kind) {
1090 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1091 case llvm::BitstreamEntry::Error:
1092 Error("malformed block record in AST file");
1093 return true;
1094 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001095 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001096 case llvm::BitstreamEntry::Record:
1097 // The interesting case.
1098 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001099 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001100
Guy Benyei11169dd2012-12-18 14:30:41 +00001101 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001102 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001103 StringRef Blob;
1104 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001105 default: // Default behavior: ignore.
1106 break;
1107
1108 case SM_SLOC_FILE_ENTRY:
1109 case SM_SLOC_BUFFER_ENTRY:
1110 case SM_SLOC_EXPANSION_ENTRY:
1111 // Once we hit one of the source location entries, we're done.
1112 return false;
1113 }
1114 }
1115}
1116
1117/// \brief If a header file is not found at the path that we expect it to be
1118/// and the PCH file was moved from its original location, try to resolve the
1119/// file by assuming that header+PCH were moved together and the header is in
1120/// the same place relative to the PCH.
1121static std::string
1122resolveFileRelativeToOriginalDir(const std::string &Filename,
1123 const std::string &OriginalDir,
1124 const std::string &CurrDir) {
1125 assert(OriginalDir != CurrDir &&
1126 "No point trying to resolve the file if the PCH dir didn't change");
1127 using namespace llvm::sys;
1128 SmallString<128> filePath(Filename);
1129 fs::make_absolute(filePath);
1130 assert(path::is_absolute(OriginalDir));
1131 SmallString<128> currPCHPath(CurrDir);
1132
1133 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1134 fileDirE = path::end(path::parent_path(filePath));
1135 path::const_iterator origDirI = path::begin(OriginalDir),
1136 origDirE = path::end(OriginalDir);
1137 // Skip the common path components from filePath and OriginalDir.
1138 while (fileDirI != fileDirE && origDirI != origDirE &&
1139 *fileDirI == *origDirI) {
1140 ++fileDirI;
1141 ++origDirI;
1142 }
1143 for (; origDirI != origDirE; ++origDirI)
1144 path::append(currPCHPath, "..");
1145 path::append(currPCHPath, fileDirI, fileDirE);
1146 path::append(currPCHPath, path::filename(Filename));
1147 return currPCHPath.str();
1148}
1149
1150bool ASTReader::ReadSLocEntry(int ID) {
1151 if (ID == 0)
1152 return false;
1153
1154 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1155 Error("source location entry ID out-of-range for AST file");
1156 return true;
1157 }
1158
1159 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1160 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001161 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001162 unsigned BaseOffset = F->SLocEntryBaseOffset;
1163
1164 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001165 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1166 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001167 Error("incorrectly-formatted source location entry in AST file");
1168 return true;
1169 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001170
Guy Benyei11169dd2012-12-18 14:30:41 +00001171 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001172 StringRef Blob;
1173 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001174 default:
1175 Error("incorrectly-formatted source location entry in AST file");
1176 return true;
1177
1178 case SM_SLOC_FILE_ENTRY: {
1179 // We will detect whether a file changed and return 'Failure' for it, but
1180 // we will also try to fail gracefully by setting up the SLocEntry.
1181 unsigned InputID = Record[4];
1182 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001183 const FileEntry *File = IF.getFile();
1184 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001185
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001186 // Note that we only check if a File was returned. If it was out-of-date
1187 // we have complained but we will continue creating a FileID to recover
1188 // gracefully.
1189 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001190 return true;
1191
1192 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1193 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1194 // This is the module's main file.
1195 IncludeLoc = getImportLocation(F);
1196 }
1197 SrcMgr::CharacteristicKind
1198 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1199 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1200 ID, BaseOffset + Record[0]);
1201 SrcMgr::FileInfo &FileInfo =
1202 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1203 FileInfo.NumCreatedFIDs = Record[5];
1204 if (Record[3])
1205 FileInfo.setHasLineDirectives();
1206
1207 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1208 unsigned NumFileDecls = Record[7];
1209 if (NumFileDecls) {
1210 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1211 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1212 NumFileDecls));
1213 }
1214
1215 const SrcMgr::ContentCache *ContentCache
1216 = SourceMgr.getOrCreateContentCache(File,
1217 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1218 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1219 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1220 unsigned Code = SLocEntryCursor.ReadCode();
1221 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001222 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001223
1224 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1225 Error("AST record has invalid code");
1226 return true;
1227 }
1228
1229 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001230 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +00001231 SourceMgr.overrideFileContents(File, Buffer);
1232 }
1233
1234 break;
1235 }
1236
1237 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001238 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001239 unsigned Offset = Record[0];
1240 SrcMgr::CharacteristicKind
1241 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1242 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1243 if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
1244 IncludeLoc = getImportLocation(F);
1245 }
1246 unsigned Code = SLocEntryCursor.ReadCode();
1247 Record.clear();
1248 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001249 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001250
1251 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1252 Error("AST record has invalid code");
1253 return true;
1254 }
1255
1256 llvm::MemoryBuffer *Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001257 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
Alp Toker6ac2cd02014-05-16 17:23:01 +00001258 SourceMgr.createFileID(Buffer, FileCharacter, ID, BaseOffset + Offset,
1259 IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001260 break;
1261 }
1262
1263 case SM_SLOC_EXPANSION_ENTRY: {
1264 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1265 SourceMgr.createExpansionLoc(SpellingLoc,
1266 ReadSourceLocation(*F, Record[2]),
1267 ReadSourceLocation(*F, Record[3]),
1268 Record[4],
1269 ID,
1270 BaseOffset + Record[0]);
1271 break;
1272 }
1273 }
1274
1275 return false;
1276}
1277
1278std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1279 if (ID == 0)
1280 return std::make_pair(SourceLocation(), "");
1281
1282 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1283 Error("source location entry ID out-of-range for AST file");
1284 return std::make_pair(SourceLocation(), "");
1285 }
1286
1287 // Find which module file this entry lands in.
1288 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1289 if (M->Kind != MK_Module)
1290 return std::make_pair(SourceLocation(), "");
1291
1292 // FIXME: Can we map this down to a particular submodule? That would be
1293 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001294 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001295}
1296
1297/// \brief Find the location where the module F is imported.
1298SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1299 if (F->ImportLoc.isValid())
1300 return F->ImportLoc;
1301
1302 // Otherwise we have a PCH. It's considered to be "imported" at the first
1303 // location of its includer.
1304 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001305 // Main file is the importer.
1306 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1307 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001308 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001309 return F->ImportedBy[0]->FirstLoc;
1310}
1311
1312/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1313/// specified cursor. Read the abbreviations that are at the top of the block
1314/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001315bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001316 if (Cursor.EnterSubBlock(BlockID)) {
1317 Error("malformed block record in AST file");
1318 return Failure;
1319 }
1320
1321 while (true) {
1322 uint64_t Offset = Cursor.GetCurrentBitNo();
1323 unsigned Code = Cursor.ReadCode();
1324
1325 // We expect all abbrevs to be at the start of the block.
1326 if (Code != llvm::bitc::DEFINE_ABBREV) {
1327 Cursor.JumpToBit(Offset);
1328 return false;
1329 }
1330 Cursor.ReadAbbrevRecord();
1331 }
1332}
1333
Richard Smithe40f2ba2013-08-07 21:41:30 +00001334Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001335 unsigned &Idx) {
1336 Token Tok;
1337 Tok.startToken();
1338 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1339 Tok.setLength(Record[Idx++]);
1340 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1341 Tok.setIdentifierInfo(II);
1342 Tok.setKind((tok::TokenKind)Record[Idx++]);
1343 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1344 return Tok;
1345}
1346
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001347MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001348 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001349
1350 // Keep track of where we are in the stream, then jump back there
1351 // after reading this macro.
1352 SavedStreamPosition SavedPosition(Stream);
1353
1354 Stream.JumpToBit(Offset);
1355 RecordData Record;
1356 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001357 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001358
Guy Benyei11169dd2012-12-18 14:30:41 +00001359 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001360 // Advance to the next record, but if we get to the end of the block, don't
1361 // pop it (removing all the abbreviations from the cursor) since we want to
1362 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001363 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001364 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1365
1366 switch (Entry.Kind) {
1367 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1368 case llvm::BitstreamEntry::Error:
1369 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001370 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001371 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001372 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001373 case llvm::BitstreamEntry::Record:
1374 // The interesting case.
1375 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001376 }
1377
1378 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001379 Record.clear();
1380 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001381 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001382 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001383 case PP_MACRO_DIRECTIVE_HISTORY:
1384 return Macro;
1385
Guy Benyei11169dd2012-12-18 14:30:41 +00001386 case PP_MACRO_OBJECT_LIKE:
1387 case PP_MACRO_FUNCTION_LIKE: {
1388 // If we already have a macro, that means that we've hit the end
1389 // of the definition of the macro we were looking for. We're
1390 // done.
1391 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001392 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001393
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001394 unsigned NextIndex = 1; // Skip identifier ID.
1395 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001396 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001397 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001398 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001399 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001400 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001401
Guy Benyei11169dd2012-12-18 14:30:41 +00001402 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1403 // Decode function-like macro info.
1404 bool isC99VarArgs = Record[NextIndex++];
1405 bool isGNUVarArgs = Record[NextIndex++];
1406 bool hasCommaPasting = Record[NextIndex++];
1407 MacroArgs.clear();
1408 unsigned NumArgs = Record[NextIndex++];
1409 for (unsigned i = 0; i != NumArgs; ++i)
1410 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1411
1412 // Install function-like macro info.
1413 MI->setIsFunctionLike();
1414 if (isC99VarArgs) MI->setIsC99Varargs();
1415 if (isGNUVarArgs) MI->setIsGNUVarargs();
1416 if (hasCommaPasting) MI->setHasCommaPasting();
1417 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1418 PP.getPreprocessorAllocator());
1419 }
1420
Guy Benyei11169dd2012-12-18 14:30:41 +00001421 // Remember that we saw this macro last so that we add the tokens that
1422 // form its body to it.
1423 Macro = MI;
1424
1425 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1426 Record[NextIndex]) {
1427 // We have a macro definition. Register the association
1428 PreprocessedEntityID
1429 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1430 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001431 PreprocessingRecord::PPEntityID
1432 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1433 MacroDefinition *PPDef =
1434 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1435 if (PPDef)
1436 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001437 }
1438
1439 ++NumMacrosRead;
1440 break;
1441 }
1442
1443 case PP_TOKEN: {
1444 // If we see a TOKEN before a PP_MACRO_*, then the file is
1445 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001446 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001447
John McCallf413f5e2013-05-03 00:10:13 +00001448 unsigned Idx = 0;
1449 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001450 Macro->AddTokenToBody(Tok);
1451 break;
1452 }
1453 }
1454 }
1455}
1456
1457PreprocessedEntityID
1458ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1459 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1460 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1461 assert(I != M.PreprocessedEntityRemap.end()
1462 && "Invalid index into preprocessed entity index remap");
1463
1464 return LocalID + I->second;
1465}
1466
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001467unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1468 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001469}
1470
1471HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001472HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1473 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1474 FE->getName() };
1475 return ikey;
1476}
Guy Benyei11169dd2012-12-18 14:30:41 +00001477
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001478bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1479 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001480 return false;
1481
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001482 if (strcmp(a.Filename, b.Filename) == 0)
1483 return true;
1484
Guy Benyei11169dd2012-12-18 14:30:41 +00001485 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001486 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001487 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1488 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001489 return (FEA && FEA == FEB);
Guy Benyei11169dd2012-12-18 14:30:41 +00001490}
1491
1492std::pair<unsigned, unsigned>
1493HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001494 using namespace llvm::support;
1495 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001496 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001497 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001498}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001499
1500HeaderFileInfoTrait::internal_key_type
1501HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001502 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001503 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001504 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1505 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001506 ikey.Filename = (const char *)d;
1507 return ikey;
1508}
1509
Guy Benyei11169dd2012-12-18 14:30:41 +00001510HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001511HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001512 unsigned DataLen) {
1513 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001514 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001515 HeaderFileInfo HFI;
1516 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001517 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1518 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001519 HFI.isImport = (Flags >> 5) & 0x01;
1520 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1521 HFI.DirInfo = (Flags >> 2) & 0x03;
1522 HFI.Resolved = (Flags >> 1) & 0x01;
1523 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001524 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1525 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1526 M, endian::readNext<uint32_t, little, unaligned>(d));
1527 if (unsigned FrameworkOffset =
1528 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001529 // The framework offset is 1 greater than the actual offset,
1530 // since 0 is used as an indicator for "no framework name".
1531 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1532 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1533 }
1534
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001535 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001536 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001537 if (LocalSMID) {
1538 // This header is part of a module. Associate it with the module to enable
1539 // implicit module import.
1540 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1541 Module *Mod = Reader.getSubmodule(GlobalSMID);
1542 HFI.isModuleHeader = true;
1543 FileManager &FileMgr = Reader.getFileManager();
1544 ModuleMap &ModMap =
1545 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001546 ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001547 }
1548 }
1549
Guy Benyei11169dd2012-12-18 14:30:41 +00001550 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1551 (void)End;
1552
1553 // This HeaderFileInfo was externally loaded.
1554 HFI.External = true;
1555 return HFI;
1556}
1557
Richard Smith49f906a2014-03-01 00:08:04 +00001558void
1559ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1560 GlobalMacroID GMacID,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001561 ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001562 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Craig Toppera13603a2014-05-22 05:54:18 +00001563 SubmoduleID *OverrideData = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001564 if (!Overrides.empty()) {
1565 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1566 OverrideData[0] = Overrides.size();
1567 for (unsigned I = 0; I != Overrides.size(); ++I)
1568 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1569 }
1570 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001571}
1572
1573void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1574 ModuleFile *M,
1575 uint64_t MacroDirectivesOffset) {
1576 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1577 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001578}
1579
1580void ASTReader::ReadDefinedMacros() {
1581 // Note that we are loading defined macros.
1582 Deserializing Macros(this);
1583
1584 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1585 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001586 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001587
1588 // If there was no preprocessor block, skip this file.
1589 if (!MacroCursor.getBitStreamReader())
1590 continue;
1591
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001592 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001593 Cursor.JumpToBit((*I)->MacroStartOffset);
1594
1595 RecordData Record;
1596 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001597 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1598
1599 switch (E.Kind) {
1600 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1601 case llvm::BitstreamEntry::Error:
1602 Error("malformed block record in AST file");
1603 return;
1604 case llvm::BitstreamEntry::EndBlock:
1605 goto NextCursor;
1606
1607 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001608 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001609 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001610 default: // Default behavior: ignore.
1611 break;
1612
1613 case PP_MACRO_OBJECT_LIKE:
1614 case PP_MACRO_FUNCTION_LIKE:
1615 getLocalIdentifier(**I, Record[0]);
1616 break;
1617
1618 case PP_TOKEN:
1619 // Ignore tokens.
1620 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001621 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001622 break;
1623 }
1624 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001625 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001626 }
1627}
1628
1629namespace {
1630 /// \brief Visitor class used to look up identifirs in an AST file.
1631 class IdentifierLookupVisitor {
1632 StringRef Name;
1633 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001634 unsigned &NumIdentifierLookups;
1635 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001636 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001637
Guy Benyei11169dd2012-12-18 14:30:41 +00001638 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001639 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1640 unsigned &NumIdentifierLookups,
1641 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001642 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001643 NumIdentifierLookups(NumIdentifierLookups),
1644 NumIdentifierLookupHits(NumIdentifierLookupHits),
1645 Found()
1646 {
1647 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001648
1649 static bool visit(ModuleFile &M, void *UserData) {
1650 IdentifierLookupVisitor *This
1651 = static_cast<IdentifierLookupVisitor *>(UserData);
1652
1653 // If we've already searched this module file, skip it now.
1654 if (M.Generation <= This->PriorGeneration)
1655 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001656
Guy Benyei11169dd2012-12-18 14:30:41 +00001657 ASTIdentifierLookupTable *IdTable
1658 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1659 if (!IdTable)
1660 return false;
1661
1662 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1663 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001664 ++This->NumIdentifierLookups;
1665 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001666 if (Pos == IdTable->end())
1667 return false;
1668
1669 // Dereferencing the iterator has the effect of building the
1670 // IdentifierInfo node and populating it with the various
1671 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001672 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001673 This->Found = *Pos;
1674 return true;
1675 }
1676
1677 // \brief Retrieve the identifier info found within the module
1678 // files.
1679 IdentifierInfo *getIdentifierInfo() const { return Found; }
1680 };
1681}
1682
1683void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1684 // Note that we are loading an identifier.
1685 Deserializing AnIdentifier(this);
1686
1687 unsigned PriorGeneration = 0;
1688 if (getContext().getLangOpts().Modules)
1689 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001690
1691 // If there is a global index, look there first to determine which modules
1692 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001693 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001694 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001695 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001696 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1697 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001698 }
1699 }
1700
Douglas Gregor7211ac12013-01-25 23:32:03 +00001701 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001702 NumIdentifierLookups,
1703 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001704 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001705 markIdentifierUpToDate(&II);
1706}
1707
1708void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1709 if (!II)
1710 return;
1711
1712 II->setOutOfDate(false);
1713
1714 // Update the generation for this identifier.
1715 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001716 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001717}
1718
Richard Smith49f906a2014-03-01 00:08:04 +00001719struct ASTReader::ModuleMacroInfo {
1720 SubmoduleID SubModID;
1721 MacroInfo *MI;
1722 SubmoduleID *Overrides;
1723 // FIXME: Remove this.
1724 ModuleFile *F;
1725
1726 bool isDefine() const { return MI; }
1727
1728 SubmoduleID getSubmoduleID() const { return SubModID; }
1729
Craig Topper00bbdcf2014-06-28 23:22:23 +00001730 ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
Richard Smith49f906a2014-03-01 00:08:04 +00001731 if (!Overrides)
Craig Topper00bbdcf2014-06-28 23:22:23 +00001732 return None;
Richard Smith49f906a2014-03-01 00:08:04 +00001733 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1734 }
1735
Richard Smithdaa69e02014-07-25 04:40:03 +00001736 MacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
Richard Smith49f906a2014-03-01 00:08:04 +00001737 if (!MI)
Richard Smithdaa69e02014-07-25 04:40:03 +00001738 return PP.AllocateUndefMacroDirective(ImportLoc, SubModID,
1739 getOverriddenSubmodules());
1740 return PP.AllocateDefMacroDirective(MI, ImportLoc, SubModID,
1741 getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00001742 }
1743};
1744
1745ASTReader::ModuleMacroInfo *
1746ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1747 ModuleMacroInfo Info;
1748
1749 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1750 if (ID & 1) {
1751 // Macro undefinition.
1752 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
Craig Toppera13603a2014-05-22 05:54:18 +00001753 Info.MI = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001754 } else {
1755 // Macro definition.
1756 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1757 assert(GMacID);
1758
1759 // If this macro has already been loaded, don't do so again.
1760 // FIXME: This is highly dubious. Multiple macro definitions can have the
1761 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1762 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
Craig Toppera13603a2014-05-22 05:54:18 +00001763 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001764
1765 Info.MI = getMacro(GMacID);
1766 Info.SubModID = Info.MI->getOwningModuleID();
1767 }
1768 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1769 Info.F = PMInfo.M;
1770
1771 return new (Context) ModuleMacroInfo(Info);
1772}
1773
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001774void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1775 const PendingMacroInfo &PMInfo) {
1776 assert(II);
1777
1778 if (PMInfo.M->Kind != MK_Module) {
1779 installPCHMacroDirectives(II, *PMInfo.M,
1780 PMInfo.PCHMacroData.MacroDirectivesOffset);
1781 return;
1782 }
Richard Smith49f906a2014-03-01 00:08:04 +00001783
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001784 // Module Macro.
1785
Richard Smith49f906a2014-03-01 00:08:04 +00001786 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1787 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001788 return;
1789
Richard Smith49f906a2014-03-01 00:08:04 +00001790 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1791 if (Owner && Owner->NameVisibility == Module::Hidden) {
1792 // Macros in the owning module are hidden. Just remember this macro to
1793 // install if we make this module visible.
1794 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1795 } else {
Richard Smithdaa69e02014-07-25 04:40:03 +00001796 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001797 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001798}
1799
1800void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1801 ModuleFile &M, uint64_t Offset) {
1802 assert(M.Kind != MK_Module);
1803
1804 BitstreamCursor &Cursor = M.MacroCursor;
1805 SavedStreamPosition SavedPosition(Cursor);
1806 Cursor.JumpToBit(Offset);
1807
1808 llvm::BitstreamEntry Entry =
1809 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1810 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1811 Error("malformed block record in AST file");
1812 return;
1813 }
1814
1815 RecordData Record;
1816 PreprocessorRecordTypes RecType =
1817 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1818 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1819 Error("malformed block record in AST file");
1820 return;
1821 }
1822
1823 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001824 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001825 unsigned Idx = 0, N = Record.size();
1826 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001827 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001828 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001829 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1830 switch (K) {
1831 case MacroDirective::MD_Define: {
1832 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1833 MacroInfo *MI = getMacro(GMacID);
Richard Smithdaa69e02014-07-25 04:40:03 +00001834 SubmoduleID ImportedFrom = Record[Idx++];
1835 bool IsAmbiguous = Record[Idx++];
1836 llvm::SmallVector<unsigned, 4> Overrides;
1837 if (ImportedFrom) {
1838 Overrides.insert(Overrides.end(),
1839 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1840 Idx += Overrides.size() + 1;
1841 }
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001842 DefMacroDirective *DefMD =
Richard Smithdaa69e02014-07-25 04:40:03 +00001843 PP.AllocateDefMacroDirective(MI, Loc, ImportedFrom, Overrides);
1844 DefMD->setAmbiguous(IsAmbiguous);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001845 MD = DefMD;
1846 break;
1847 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001848 case MacroDirective::MD_Undefine: {
1849 SubmoduleID ImportedFrom = Record[Idx++];
1850 llvm::SmallVector<unsigned, 4> Overrides;
1851 if (ImportedFrom) {
1852 Overrides.insert(Overrides.end(),
1853 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1854 Idx += Overrides.size() + 1;
1855 }
1856 MD = PP.AllocateUndefMacroDirective(Loc, ImportedFrom, Overrides);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001857 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001858 }
1859 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001860 bool isPublic = Record[Idx++];
1861 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1862 break;
1863 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001864
1865 if (!Latest)
1866 Latest = MD;
1867 if (Earliest)
1868 Earliest->setPrevious(MD);
1869 Earliest = MD;
1870 }
1871
1872 PP.setLoadedMacroDirective(II, Latest);
1873}
1874
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001875/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001876/// modules.
1877static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001878 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001879 assert(PrevMI && NewMI);
Craig Toppera13603a2014-05-22 05:54:18 +00001880 Module *PrevOwner = nullptr;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001881 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1882 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001883 SourceManager &SrcMgr = Reader.getSourceManager();
1884 bool PrevInSystem
1885 = PrevOwner? PrevOwner->IsSystem
1886 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1887 bool NewInSystem
1888 = NewOwner? NewOwner->IsSystem
1889 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1890 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001891 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001892 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001893}
1894
Richard Smith49f906a2014-03-01 00:08:04 +00001895void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001896 SourceLocation ImportLoc,
Richard Smith49f906a2014-03-01 00:08:04 +00001897 AmbiguousMacros &Ambig,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001898 ArrayRef<SubmoduleID> Overrides) {
Richard Smith49f906a2014-03-01 00:08:04 +00001899 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1900 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001901
Richard Smith49f906a2014-03-01 00:08:04 +00001902 // If this macro is not yet visible, remove it from the hidden names list.
1903 Module *Owner = getSubmodule(OwnerID);
1904 HiddenNames &Hidden = HiddenNamesMap[Owner];
1905 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1906 if (HI != Hidden.HiddenMacros.end()) {
Richard Smithdaa69e02014-07-25 04:40:03 +00001907 // Register the macro now so we don't lose it when we re-export.
1908 PP.appendMacroDirective(II, HI->second->import(PP, ImportLoc));
1909
Richard Smith9d100862014-03-06 03:16:27 +00001910 auto SubOverrides = HI->second->getOverriddenSubmodules();
Richard Smith49f906a2014-03-01 00:08:04 +00001911 Hidden.HiddenMacros.erase(HI);
Richard Smithdaa69e02014-07-25 04:40:03 +00001912 removeOverriddenMacros(II, ImportLoc, Ambig, SubOverrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001913 }
1914
1915 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001916 Ambig.erase(
1917 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1918 return MD->getInfo()->getOwningModuleID() == OwnerID;
1919 }),
1920 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001921 }
1922}
1923
1924ASTReader::AmbiguousMacros *
1925ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001926 SourceLocation ImportLoc,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001927 ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001928 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001929 if (!Prev && Overrides.empty())
Craig Toppera13603a2014-05-22 05:54:18 +00001930 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001931
Craig Toppera13603a2014-05-22 05:54:18 +00001932 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective()
1933 : nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001934 if (PrevDef && PrevDef->isAmbiguous()) {
1935 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1936 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1937 Ambig.push_back(PrevDef);
1938
Richard Smithdaa69e02014-07-25 04:40:03 +00001939 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001940
1941 if (!Ambig.empty())
1942 return &Ambig;
1943
1944 AmbiguousMacroDefs.erase(II);
1945 } else {
1946 // There's no ambiguity yet. Maybe we're introducing one.
Benjamin Kramer834652a2014-05-03 18:44:26 +00001947 AmbiguousMacros Ambig;
Richard Smith49f906a2014-03-01 00:08:04 +00001948 if (PrevDef)
1949 Ambig.push_back(PrevDef);
1950
Richard Smithdaa69e02014-07-25 04:40:03 +00001951 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001952
1953 if (!Ambig.empty()) {
1954 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
Benjamin Kramer834652a2014-05-03 18:44:26 +00001955 std::swap(Result, Ambig);
Richard Smith49f906a2014-03-01 00:08:04 +00001956 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001957 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001958 }
Richard Smith49f906a2014-03-01 00:08:04 +00001959
1960 // We ended up with no ambiguity.
Craig Toppera13603a2014-05-22 05:54:18 +00001961 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001962}
1963
1964void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
Richard Smithdaa69e02014-07-25 04:40:03 +00001965 Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00001966 assert(II && Owner);
1967
1968 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
Richard Smithdaa69e02014-07-25 04:40:03 +00001969 if (ImportLoc.isInvalid()) {
Richard Smith49f906a2014-03-01 00:08:04 +00001970 // FIXME: If we made macros from this module visible but didn't provide a
1971 // source location for the import, we don't have a location for the macro.
1972 // Use the location at which the containing module file was first imported
1973 // for now.
1974 ImportLoc = MMI->F->DirectImportLoc;
Richard Smith56be7542014-03-21 00:33:59 +00001975 assert(ImportLoc.isValid() && "no import location for a visible macro?");
Richard Smith49f906a2014-03-01 00:08:04 +00001976 }
1977
Benjamin Kramer834652a2014-05-03 18:44:26 +00001978 AmbiguousMacros *Prev =
Richard Smithdaa69e02014-07-25 04:40:03 +00001979 removeOverriddenMacros(II, ImportLoc, MMI->getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00001980
Richard Smith49f906a2014-03-01 00:08:04 +00001981 // Create a synthetic macro definition corresponding to the import (or null
1982 // if this was an undefinition of the macro).
Richard Smithdaa69e02014-07-25 04:40:03 +00001983 MacroDirective *Imported = MMI->import(PP, ImportLoc);
1984 DefMacroDirective *MD = dyn_cast<DefMacroDirective>(Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00001985
1986 // If there's no ambiguity, just install the macro.
1987 if (!Prev) {
Richard Smithdaa69e02014-07-25 04:40:03 +00001988 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00001989 return;
1990 }
1991 assert(!Prev->empty());
1992
1993 if (!MD) {
1994 // We imported a #undef that didn't remove all prior definitions. The most
1995 // recent prior definition remains, and we install it in the place of the
Richard Smithdaa69e02014-07-25 04:40:03 +00001996 // imported directive, as if by a local #pragma pop_macro.
Richard Smith49f906a2014-03-01 00:08:04 +00001997 MacroInfo *NewMI = Prev->back()->getInfo();
1998 Prev->pop_back();
Richard Smithdaa69e02014-07-25 04:40:03 +00001999 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc);
2000
2001 // Install our #undef first so that we don't lose track of it. We'll replace
2002 // this with whichever macro definition ends up winning.
2003 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002004 }
2005
2006 // We're introducing a macro definition that creates or adds to an ambiguity.
2007 // We can resolve that ambiguity if this macro is token-for-token identical to
2008 // all of the existing definitions.
2009 MacroInfo *NewMI = MD->getInfo();
2010 assert(NewMI && "macro definition with no MacroInfo?");
2011 while (!Prev->empty()) {
2012 MacroInfo *PrevMI = Prev->back()->getInfo();
2013 assert(PrevMI && "macro definition with no MacroInfo?");
2014
2015 // Before marking the macros as ambiguous, check if this is a case where
2016 // both macros are in system headers. If so, we trust that the system
2017 // did not get it wrong. This also handles cases where Clang's own
2018 // headers have a different spelling of certain system macros:
2019 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
2020 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
2021 //
2022 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
2023 // overrides the system limits.h's macros, so there's no conflict here.
2024 if (NewMI != PrevMI &&
2025 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
2026 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
2027 break;
2028
2029 // The previous definition is the same as this one (or both are defined in
2030 // system modules so we can assume they're equivalent); we don't need to
2031 // track it any more.
2032 Prev->pop_back();
2033 }
2034
2035 if (!Prev->empty())
2036 MD->setAmbiguous(true);
2037
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002038 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002039}
2040
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002041ASTReader::InputFileInfo
2042ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002043 // Go find this input file.
2044 BitstreamCursor &Cursor = F.InputFilesCursor;
2045 SavedStreamPosition SavedPosition(Cursor);
2046 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2047
2048 unsigned Code = Cursor.ReadCode();
2049 RecordData Record;
2050 StringRef Blob;
2051
2052 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2053 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2054 "invalid record type for input file");
2055 (void)Result;
2056
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002057 std::string Filename;
2058 off_t StoredSize;
2059 time_t StoredTime;
2060 bool Overridden;
2061
Ben Langmuir198c1682014-03-07 07:27:49 +00002062 assert(Record[0] == ID && "Bogus stored ID or offset");
2063 StoredSize = static_cast<off_t>(Record[1]);
2064 StoredTime = static_cast<time_t>(Record[2]);
2065 Overridden = static_cast<bool>(Record[3]);
2066 Filename = Blob;
2067 MaybeAddSystemRootToFilename(F, Filename);
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002068
Hans Wennborg73945142014-03-14 17:45:06 +00002069 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
2070 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002071}
2072
2073std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002074 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00002075}
2076
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002077InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002078 // If this ID is bogus, just return an empty input file.
2079 if (ID == 0 || ID > F.InputFilesLoaded.size())
2080 return InputFile();
2081
2082 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002083 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002084 return F.InputFilesLoaded[ID-1];
2085
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002086 if (F.InputFilesLoaded[ID-1].isNotFound())
2087 return InputFile();
2088
Guy Benyei11169dd2012-12-18 14:30:41 +00002089 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002090 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002091 SavedStreamPosition SavedPosition(Cursor);
2092 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2093
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002094 InputFileInfo FI = readInputFileInfo(F, ID);
2095 off_t StoredSize = FI.StoredSize;
2096 time_t StoredTime = FI.StoredTime;
2097 bool Overridden = FI.Overridden;
2098 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002099
Ben Langmuir198c1682014-03-07 07:27:49 +00002100 const FileEntry *File
2101 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
2102 : FileMgr.getFile(Filename, /*OpenFile=*/false);
2103
2104 // If we didn't find the file, resolve it relative to the
2105 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002106 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002107 F.OriginalDir != CurrentDir) {
2108 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2109 F.OriginalDir,
2110 CurrentDir);
2111 if (!Resolved.empty())
2112 File = FileMgr.getFile(Resolved);
2113 }
2114
2115 // For an overridden file, create a virtual file with the stored
2116 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00002117 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002118 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2119 }
2120
Craig Toppera13603a2014-05-22 05:54:18 +00002121 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002122 if (Complain) {
2123 std::string ErrorStr = "could not find file '";
2124 ErrorStr += Filename;
2125 ErrorStr += "' referenced by AST file";
2126 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00002127 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002128 // Record that we didn't find the file.
2129 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2130 return InputFile();
2131 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002132
Ben Langmuir198c1682014-03-07 07:27:49 +00002133 // Check if there was a request to override the contents of the file
2134 // that was part of the precompiled header. Overridding such a file
2135 // can lead to problems when lexing using the source locations from the
2136 // PCH.
2137 SourceManager &SM = getSourceManager();
2138 if (!Overridden && SM.isFileOverridden(File)) {
2139 if (Complain)
2140 Error(diag::err_fe_pch_file_overridden, Filename);
2141 // After emitting the diagnostic, recover by disabling the override so
2142 // that the original file will be used.
2143 SM.disableFileContentsOverride(File);
2144 // The FileEntry is a virtual file entry with the size of the contents
2145 // that would override the original contents. Set it to the original's
2146 // size/time.
2147 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2148 StoredSize, StoredTime);
2149 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002150
Ben Langmuir198c1682014-03-07 07:27:49 +00002151 bool IsOutOfDate = false;
2152
2153 // For an overridden file, there is nothing to validate.
2154 if (!Overridden && (StoredSize != File->getSize()
Guy Benyei11169dd2012-12-18 14:30:41 +00002155#if !defined(LLVM_ON_WIN32)
Ben Langmuir198c1682014-03-07 07:27:49 +00002156 // In our regression testing, the Windows file system seems to
2157 // have inconsistent modification times that sometimes
2158 // erroneously trigger this error-handling path.
2159 || StoredTime != File->getModificationTime()
Guy Benyei11169dd2012-12-18 14:30:41 +00002160#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002161 )) {
2162 if (Complain) {
2163 // Build a list of the PCH imports that got us here (in reverse).
2164 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2165 while (ImportStack.back()->ImportedBy.size() > 0)
2166 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002167
Ben Langmuir198c1682014-03-07 07:27:49 +00002168 // The top-level PCH is stale.
2169 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2170 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002171
Ben Langmuir198c1682014-03-07 07:27:49 +00002172 // Print the import stack.
2173 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2174 Diag(diag::note_pch_required_by)
2175 << Filename << ImportStack[0]->FileName;
2176 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002177 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002178 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002179 }
2180
Ben Langmuir198c1682014-03-07 07:27:49 +00002181 if (!Diags.isDiagnosticInFlight())
2182 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002183 }
2184
Ben Langmuir198c1682014-03-07 07:27:49 +00002185 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002186 }
2187
Ben Langmuir198c1682014-03-07 07:27:49 +00002188 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2189
2190 // Note that we've loaded this input file.
2191 F.InputFilesLoaded[ID-1] = IF;
2192 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002193}
2194
2195const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
2196 ModuleFile &M = ModuleMgr.getPrimaryModule();
2197 std::string Filename = filenameStrRef;
2198 MaybeAddSystemRootToFilename(M, Filename);
2199 const FileEntry *File = FileMgr.getFile(Filename);
Craig Toppera13603a2014-05-22 05:54:18 +00002200 if (File == nullptr && !M.OriginalDir.empty() && !CurrentDir.empty() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002201 M.OriginalDir != CurrentDir) {
2202 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
2203 M.OriginalDir,
2204 CurrentDir);
2205 if (!resolved.empty())
2206 File = FileMgr.getFile(resolved);
2207 }
2208
2209 return File;
2210}
2211
2212/// \brief If we are loading a relocatable PCH file, and the filename is
2213/// not an absolute path, add the system root to the beginning of the file
2214/// name.
2215void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
2216 std::string &Filename) {
2217 // If this is not a relocatable PCH file, there's nothing to do.
2218 if (!M.RelocatablePCH)
2219 return;
2220
2221 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2222 return;
2223
2224 if (isysroot.empty()) {
2225 // If no system root was given, default to '/'
2226 Filename.insert(Filename.begin(), '/');
2227 return;
2228 }
2229
2230 unsigned Length = isysroot.size();
2231 if (isysroot[Length - 1] != '/')
2232 Filename.insert(Filename.begin(), '/');
2233
2234 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
2235}
2236
2237ASTReader::ASTReadResult
2238ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002239 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002240 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002241 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002242 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002243
2244 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2245 Error("malformed block record in AST file");
2246 return Failure;
2247 }
2248
2249 // Read all of the records and blocks in the control block.
2250 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002251 while (1) {
2252 llvm::BitstreamEntry Entry = Stream.advance();
2253
2254 switch (Entry.Kind) {
2255 case llvm::BitstreamEntry::Error:
2256 Error("malformed block record in AST file");
2257 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002258 case llvm::BitstreamEntry::EndBlock: {
2259 // Validate input files.
2260 const HeaderSearchOptions &HSOpts =
2261 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002262
2263 // All user input files reside at the index range [0, Record[1]), and
2264 // system input files reside at [Record[1], Record[0]).
2265 // Record is the one from INPUT_FILE_OFFSETS.
2266 unsigned NumInputs = Record[0];
2267 unsigned NumUserInputs = Record[1];
2268
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002269 if (!DisableValidation &&
Ben Langmuir1e258222014-04-08 15:36:28 +00002270 (ValidateSystemInputs || !HSOpts.ModulesValidateOncePerBuildSession ||
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002271 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002272 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002273
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002274 // If we are reading a module, we will create a verification timestamp,
2275 // so we verify all input files. Otherwise, verify only user input
2276 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002277
2278 unsigned N = NumUserInputs;
2279 if (ValidateSystemInputs ||
Ben Langmuircb69b572014-03-07 06:40:32 +00002280 (HSOpts.ModulesValidateOncePerBuildSession && F.Kind == MK_Module))
2281 N = NumInputs;
2282
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002283 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002284 InputFile IF = getInputFile(F, I+1, Complain);
2285 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002286 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002287 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002288 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002289
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002290 if (Listener)
2291 Listener->visitModuleFile(F.FileName);
2292
Ben Langmuircb69b572014-03-07 06:40:32 +00002293 if (Listener && Listener->needsInputFileVisitation()) {
2294 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2295 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002296 for (unsigned I = 0; I < N; ++I) {
2297 bool IsSystem = I >= NumUserInputs;
2298 InputFileInfo FI = readInputFileInfo(F, I+1);
2299 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2300 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002301 }
2302
Guy Benyei11169dd2012-12-18 14:30:41 +00002303 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002304 }
2305
Chris Lattnere7b154b2013-01-19 21:39:22 +00002306 case llvm::BitstreamEntry::SubBlock:
2307 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002308 case INPUT_FILES_BLOCK_ID:
2309 F.InputFilesCursor = Stream;
2310 if (Stream.SkipBlock() || // Skip with the main cursor
2311 // Read the abbreviations
2312 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2313 Error("malformed block record in AST file");
2314 return Failure;
2315 }
2316 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002317
Guy Benyei11169dd2012-12-18 14:30:41 +00002318 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002319 if (Stream.SkipBlock()) {
2320 Error("malformed block record in AST file");
2321 return Failure;
2322 }
2323 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002324 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002325
2326 case llvm::BitstreamEntry::Record:
2327 // The interesting case.
2328 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002329 }
2330
2331 // Read and process a record.
2332 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002333 StringRef Blob;
2334 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002335 case METADATA: {
2336 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2337 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002338 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2339 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002340 return VersionMismatch;
2341 }
2342
2343 bool hasErrors = Record[5];
2344 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2345 Diag(diag::err_pch_with_compiler_errors);
2346 return HadErrors;
2347 }
2348
2349 F.RelocatablePCH = Record[4];
2350
2351 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002352 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002353 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2354 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002355 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002356 return VersionMismatch;
2357 }
2358 break;
2359 }
2360
2361 case IMPORTS: {
2362 // Load each of the imported PCH files.
2363 unsigned Idx = 0, N = Record.size();
2364 while (Idx < N) {
2365 // Read information about the AST file.
2366 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2367 // The import location will be the local one for now; we will adjust
2368 // all import locations of module imports after the global source
2369 // location info are setup.
2370 SourceLocation ImportLoc =
2371 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002372 off_t StoredSize = (off_t)Record[Idx++];
2373 time_t StoredModTime = (time_t)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002374 unsigned Length = Record[Idx++];
2375 SmallString<128> ImportedFile(Record.begin() + Idx,
2376 Record.begin() + Idx + Length);
2377 Idx += Length;
2378
2379 // Load the AST file.
2380 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00002381 StoredSize, StoredModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00002382 ClientLoadCapabilities)) {
2383 case Failure: return Failure;
2384 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002385 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002386 case OutOfDate: return OutOfDate;
2387 case VersionMismatch: return VersionMismatch;
2388 case ConfigurationMismatch: return ConfigurationMismatch;
2389 case HadErrors: return HadErrors;
2390 case Success: break;
2391 }
2392 }
2393 break;
2394 }
2395
2396 case LANGUAGE_OPTIONS: {
2397 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2398 if (Listener && &F == *ModuleMgr.begin() &&
2399 ParseLanguageOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002400 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002401 return ConfigurationMismatch;
2402 break;
2403 }
2404
2405 case TARGET_OPTIONS: {
2406 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2407 if (Listener && &F == *ModuleMgr.begin() &&
2408 ParseTargetOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002409 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002410 return ConfigurationMismatch;
2411 break;
2412 }
2413
2414 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002415 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002416 if (Listener && &F == *ModuleMgr.begin() &&
2417 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002418 !DisableValidation)
2419 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002420 break;
2421 }
2422
2423 case FILE_SYSTEM_OPTIONS: {
2424 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2425 if (Listener && &F == *ModuleMgr.begin() &&
2426 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002427 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002428 return ConfigurationMismatch;
2429 break;
2430 }
2431
2432 case HEADER_SEARCH_OPTIONS: {
2433 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2434 if (Listener && &F == *ModuleMgr.begin() &&
2435 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002436 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002437 return ConfigurationMismatch;
2438 break;
2439 }
2440
2441 case PREPROCESSOR_OPTIONS: {
2442 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2443 if (Listener && &F == *ModuleMgr.begin() &&
2444 ParsePreprocessorOptions(Record, Complain, *Listener,
2445 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002446 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002447 return ConfigurationMismatch;
2448 break;
2449 }
2450
2451 case ORIGINAL_FILE:
2452 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002453 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002454 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2455 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
2456 break;
2457
2458 case ORIGINAL_FILE_ID:
2459 F.OriginalSourceFileID = FileID::get(Record[0]);
2460 break;
2461
2462 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002463 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002464 break;
2465
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002466 case MODULE_NAME:
2467 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002468 if (Listener)
2469 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002470 break;
2471
2472 case MODULE_MAP_FILE:
2473 F.ModuleMapPath = Blob;
2474
2475 // Try to resolve ModuleName in the current header search context and
2476 // verify that it is found in the same module map file as we saved. If the
2477 // top-level AST file is a main file, skip this check because there is no
2478 // usable header search context.
2479 assert(!F.ModuleName.empty() &&
2480 "MODULE_NAME should come before MOUDLE_MAP_FILE");
2481 if (F.Kind == MK_Module &&
2482 (*ModuleMgr.begin())->Kind != MK_MainFile) {
2483 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2484 if (!M) {
2485 assert(ImportedBy && "top-level import should be verified");
2486 if ((ClientLoadCapabilities & ARR_Missing) == 0)
2487 Diag(diag::err_imported_module_not_found)
2488 << F.ModuleName << ImportedBy->FileName;
2489 return Missing;
2490 }
2491
Ben Langmuir9d6448b2014-08-09 00:57:23 +00002492 HeaderSearch &HS = PP.getHeaderSearchInfo();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002493 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir9d6448b2014-08-09 00:57:23 +00002494 const FileEntry *ModMap =
2495 HS.getModuleMap().getModuleMapFileForUniquing(M);
2496 if (StoredModMap == nullptr || StoredModMap != ModMap) {
2497 assert(ModMap && "found module is missing module map file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002498 assert(M->Name == F.ModuleName && "found module with different name");
2499 assert(ImportedBy && "top-level import should be verified");
2500 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2501 Diag(diag::err_imported_module_modmap_changed)
2502 << F.ModuleName << ImportedBy->FileName
Ben Langmuir9d6448b2014-08-09 00:57:23 +00002503 << ModMap->getName() << F.ModuleMapPath;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002504 return OutOfDate;
2505 }
2506 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002507
2508 if (Listener)
2509 Listener->ReadModuleMapFile(F.ModuleMapPath);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002510 break;
2511
Guy Benyei11169dd2012-12-18 14:30:41 +00002512 case INPUT_FILE_OFFSETS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002513 F.InputFileOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002514 F.InputFilesLoaded.resize(Record[0]);
2515 break;
2516 }
2517 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002518}
2519
Ben Langmuir2c9af442014-04-10 17:57:43 +00002520ASTReader::ASTReadResult
2521ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002522 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002523
2524 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2525 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002526 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002527 }
2528
2529 // Read all of the records and blocks for the AST file.
2530 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002531 while (1) {
2532 llvm::BitstreamEntry Entry = Stream.advance();
2533
2534 switch (Entry.Kind) {
2535 case llvm::BitstreamEntry::Error:
2536 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002537 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002538 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002539 // Outside of C++, we do not store a lookup map for the translation unit.
2540 // Instead, mark it as needing a lookup map to be built if this module
2541 // contains any declarations lexically within it (which it always does!).
2542 // This usually has no cost, since we very rarely need the lookup map for
2543 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002544 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002545 if (DC->hasExternalLexicalStorage() &&
2546 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002547 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002548
Ben Langmuir2c9af442014-04-10 17:57:43 +00002549 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002550 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002551 case llvm::BitstreamEntry::SubBlock:
2552 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002553 case DECLTYPES_BLOCK_ID:
2554 // We lazily load the decls block, but we want to set up the
2555 // DeclsCursor cursor to point into it. Clone our current bitcode
2556 // cursor to it, enter the block and read the abbrevs in that block.
2557 // With the main cursor, we just skip over it.
2558 F.DeclsCursor = Stream;
2559 if (Stream.SkipBlock() || // Skip with the main cursor.
2560 // Read the abbrevs.
2561 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2562 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002563 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002564 }
2565 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002566
Guy Benyei11169dd2012-12-18 14:30:41 +00002567 case PREPROCESSOR_BLOCK_ID:
2568 F.MacroCursor = Stream;
2569 if (!PP.getExternalSource())
2570 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002571
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 if (Stream.SkipBlock() ||
2573 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2574 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002575 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002576 }
2577 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2578 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002579
Guy Benyei11169dd2012-12-18 14:30:41 +00002580 case PREPROCESSOR_DETAIL_BLOCK_ID:
2581 F.PreprocessorDetailCursor = Stream;
2582 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002583 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002584 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002585 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002586 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002587 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002588 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002589 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2590
Guy Benyei11169dd2012-12-18 14:30:41 +00002591 if (!PP.getPreprocessingRecord())
2592 PP.createPreprocessingRecord();
2593 if (!PP.getPreprocessingRecord()->getExternalSource())
2594 PP.getPreprocessingRecord()->SetExternalSource(*this);
2595 break;
2596
2597 case SOURCE_MANAGER_BLOCK_ID:
2598 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002599 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002601
Guy Benyei11169dd2012-12-18 14:30:41 +00002602 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002603 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2604 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002605 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002606
Guy Benyei11169dd2012-12-18 14:30:41 +00002607 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002608 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002609 if (Stream.SkipBlock() ||
2610 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2611 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002612 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002613 }
2614 CommentsCursors.push_back(std::make_pair(C, &F));
2615 break;
2616 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002617
Guy Benyei11169dd2012-12-18 14:30:41 +00002618 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002619 if (Stream.SkipBlock()) {
2620 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002621 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002622 }
2623 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002624 }
2625 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002626
2627 case llvm::BitstreamEntry::Record:
2628 // The interesting case.
2629 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002630 }
2631
2632 // Read and process a record.
2633 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002634 StringRef Blob;
2635 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002636 default: // Default behavior: ignore.
2637 break;
2638
2639 case TYPE_OFFSET: {
2640 if (F.LocalNumTypes != 0) {
2641 Error("duplicate TYPE_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.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002645 F.LocalNumTypes = Record[0];
2646 unsigned LocalBaseTypeIndex = Record[1];
2647 F.BaseTypeIndex = getTotalNumTypes();
2648
2649 if (F.LocalNumTypes > 0) {
2650 // Introduce the global -> local mapping for types within this module.
2651 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2652
2653 // Introduce the local -> global mapping for types within this module.
2654 F.TypeRemap.insertOrReplace(
2655 std::make_pair(LocalBaseTypeIndex,
2656 F.BaseTypeIndex - LocalBaseTypeIndex));
2657
2658 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2659 }
2660 break;
2661 }
2662
2663 case DECL_OFFSET: {
2664 if (F.LocalNumDecls != 0) {
2665 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002666 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002667 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002668 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002669 F.LocalNumDecls = Record[0];
2670 unsigned LocalBaseDeclID = Record[1];
2671 F.BaseDeclID = getTotalNumDecls();
2672
2673 if (F.LocalNumDecls > 0) {
2674 // Introduce the global -> local mapping for declarations within this
2675 // module.
2676 GlobalDeclMap.insert(
2677 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2678
2679 // Introduce the local -> global mapping for declarations within this
2680 // module.
2681 F.DeclRemap.insertOrReplace(
2682 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2683
2684 // Introduce the global -> local mapping for declarations within this
2685 // module.
2686 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2687
2688 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2689 }
2690 break;
2691 }
2692
2693 case TU_UPDATE_LEXICAL: {
2694 DeclContext *TU = Context.getTranslationUnitDecl();
2695 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002696 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002697 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002698 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002699 TU->setHasExternalLexicalStorage(true);
2700 break;
2701 }
2702
2703 case UPDATE_VISIBLE: {
2704 unsigned Idx = 0;
2705 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2706 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002707 ASTDeclContextNameLookupTable::Create(
2708 (const unsigned char *)Blob.data() + Record[Idx++],
2709 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2710 (const unsigned char *)Blob.data(),
2711 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002712 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002713 auto *DC = cast<DeclContext>(D);
2714 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002715 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
Richard Smithcd45dbc2014-04-19 03:48:30 +00002716 // FIXME: There should never be an existing lookup table.
Richard Smith52e3fba2014-03-11 07:17:35 +00002717 delete LookupTable;
2718 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002719 } else
2720 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2721 break;
2722 }
2723
2724 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002725 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002726 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002727 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2728 (const unsigned char *)F.IdentifierTableData + Record[0],
2729 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2730 (const unsigned char *)F.IdentifierTableData,
2731 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002732
2733 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2734 }
2735 break;
2736
2737 case IDENTIFIER_OFFSET: {
2738 if (F.LocalNumIdentifiers != 0) {
2739 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002740 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002741 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002742 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002743 F.LocalNumIdentifiers = Record[0];
2744 unsigned LocalBaseIdentifierID = Record[1];
2745 F.BaseIdentifierID = getTotalNumIdentifiers();
2746
2747 if (F.LocalNumIdentifiers > 0) {
2748 // Introduce the global -> local mapping for identifiers within this
2749 // module.
2750 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2751 &F));
2752
2753 // Introduce the local -> global mapping for identifiers within this
2754 // module.
2755 F.IdentifierRemap.insertOrReplace(
2756 std::make_pair(LocalBaseIdentifierID,
2757 F.BaseIdentifierID - LocalBaseIdentifierID));
2758
2759 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2760 + F.LocalNumIdentifiers);
2761 }
2762 break;
2763 }
2764
Ben Langmuir332aafe2014-01-31 01:06:56 +00002765 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002766 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002767 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002768 break;
2769
2770 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002771 if (SpecialTypes.empty()) {
2772 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2773 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2774 break;
2775 }
2776
2777 if (SpecialTypes.size() != Record.size()) {
2778 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002779 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002780 }
2781
2782 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2783 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2784 if (!SpecialTypes[I])
2785 SpecialTypes[I] = ID;
2786 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2787 // merge step?
2788 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002789 break;
2790
2791 case STATISTICS:
2792 TotalNumStatements += Record[0];
2793 TotalNumMacros += Record[1];
2794 TotalLexicalDeclContexts += Record[2];
2795 TotalVisibleDeclContexts += Record[3];
2796 break;
2797
2798 case UNUSED_FILESCOPED_DECLS:
2799 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2800 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2801 break;
2802
2803 case DELEGATING_CTORS:
2804 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2805 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2806 break;
2807
2808 case WEAK_UNDECLARED_IDENTIFIERS:
2809 if (Record.size() % 4 != 0) {
2810 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002811 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002812 }
2813
2814 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2815 // files. This isn't the way to do it :)
2816 WeakUndeclaredIdentifiers.clear();
2817
2818 // Translate the weak, undeclared identifiers into global IDs.
2819 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2820 WeakUndeclaredIdentifiers.push_back(
2821 getGlobalIdentifierID(F, Record[I++]));
2822 WeakUndeclaredIdentifiers.push_back(
2823 getGlobalIdentifierID(F, Record[I++]));
2824 WeakUndeclaredIdentifiers.push_back(
2825 ReadSourceLocation(F, Record, I).getRawEncoding());
2826 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2827 }
2828 break;
2829
Richard Smith78165b52013-01-10 23:43:47 +00002830 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002831 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith78165b52013-01-10 23:43:47 +00002832 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002833 break;
2834
2835 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002836 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002837 F.LocalNumSelectors = Record[0];
2838 unsigned LocalBaseSelectorID = Record[1];
2839 F.BaseSelectorID = getTotalNumSelectors();
2840
2841 if (F.LocalNumSelectors > 0) {
2842 // Introduce the global -> local mapping for selectors within this
2843 // module.
2844 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2845
2846 // Introduce the local -> global mapping for selectors within this
2847 // module.
2848 F.SelectorRemap.insertOrReplace(
2849 std::make_pair(LocalBaseSelectorID,
2850 F.BaseSelectorID - LocalBaseSelectorID));
2851
2852 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2853 }
2854 break;
2855 }
2856
2857 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002858 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002859 if (Record[0])
2860 F.SelectorLookupTable
2861 = ASTSelectorLookupTable::Create(
2862 F.SelectorLookupTableData + Record[0],
2863 F.SelectorLookupTableData,
2864 ASTSelectorLookupTrait(*this, F));
2865 TotalNumMethodPoolEntries += Record[1];
2866 break;
2867
2868 case REFERENCED_SELECTOR_POOL:
2869 if (!Record.empty()) {
2870 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2871 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2872 Record[Idx++]));
2873 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2874 getRawEncoding());
2875 }
2876 }
2877 break;
2878
2879 case PP_COUNTER_VALUE:
2880 if (!Record.empty() && Listener)
2881 Listener->ReadCounter(F, Record[0]);
2882 break;
2883
2884 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002885 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002886 F.NumFileSortedDecls = Record[0];
2887 break;
2888
2889 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002890 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002891 F.LocalNumSLocEntries = Record[0];
2892 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002893 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Guy Benyei11169dd2012-12-18 14:30:41 +00002894 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2895 SLocSpaceSize);
2896 // Make our entry in the range map. BaseID is negative and growing, so
2897 // we invert it. Because we invert it, though, we need the other end of
2898 // the range.
2899 unsigned RangeStart =
2900 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2901 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2902 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2903
2904 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2905 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2906 GlobalSLocOffsetMap.insert(
2907 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2908 - SLocSpaceSize,&F));
2909
2910 // Initialize the remapping table.
2911 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002912 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002913 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002914 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002915 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2916
2917 TotalNumSLocEntries += F.LocalNumSLocEntries;
2918 break;
2919 }
2920
2921 case MODULE_OFFSET_MAP: {
2922 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002923 const unsigned char *Data = (const unsigned char*)Blob.data();
2924 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002925
2926 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2927 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2928 F.SLocRemap.insert(std::make_pair(0U, 0));
2929 F.SLocRemap.insert(std::make_pair(2U, 1));
2930 }
2931
Guy Benyei11169dd2012-12-18 14:30:41 +00002932 // Continuous range maps we may be updating in our module.
2933 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2934 ContinuousRangeMap<uint32_t, int, 2>::Builder
2935 IdentifierRemap(F.IdentifierRemap);
2936 ContinuousRangeMap<uint32_t, int, 2>::Builder
2937 MacroRemap(F.MacroRemap);
2938 ContinuousRangeMap<uint32_t, int, 2>::Builder
2939 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2940 ContinuousRangeMap<uint32_t, int, 2>::Builder
2941 SubmoduleRemap(F.SubmoduleRemap);
2942 ContinuousRangeMap<uint32_t, int, 2>::Builder
2943 SelectorRemap(F.SelectorRemap);
2944 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2945 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2946
2947 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002948 using namespace llvm::support;
2949 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002950 StringRef Name = StringRef((const char*)Data, Len);
2951 Data += Len;
2952 ModuleFile *OM = ModuleMgr.lookup(Name);
2953 if (!OM) {
2954 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002955 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002956 }
2957
Justin Bogner57ba0b22014-03-28 22:03:24 +00002958 uint32_t SLocOffset =
2959 endian::readNext<uint32_t, little, unaligned>(Data);
2960 uint32_t IdentifierIDOffset =
2961 endian::readNext<uint32_t, little, unaligned>(Data);
2962 uint32_t MacroIDOffset =
2963 endian::readNext<uint32_t, little, unaligned>(Data);
2964 uint32_t PreprocessedEntityIDOffset =
2965 endian::readNext<uint32_t, little, unaligned>(Data);
2966 uint32_t SubmoduleIDOffset =
2967 endian::readNext<uint32_t, little, unaligned>(Data);
2968 uint32_t SelectorIDOffset =
2969 endian::readNext<uint32_t, little, unaligned>(Data);
2970 uint32_t DeclIDOffset =
2971 endian::readNext<uint32_t, little, unaligned>(Data);
2972 uint32_t TypeIndexOffset =
2973 endian::readNext<uint32_t, little, unaligned>(Data);
2974
Guy Benyei11169dd2012-12-18 14:30:41 +00002975 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2976 SLocRemap.insert(std::make_pair(SLocOffset,
2977 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2978 IdentifierRemap.insert(
2979 std::make_pair(IdentifierIDOffset,
2980 OM->BaseIdentifierID - IdentifierIDOffset));
2981 MacroRemap.insert(std::make_pair(MacroIDOffset,
2982 OM->BaseMacroID - MacroIDOffset));
2983 PreprocessedEntityRemap.insert(
2984 std::make_pair(PreprocessedEntityIDOffset,
2985 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2986 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2987 OM->BaseSubmoduleID - SubmoduleIDOffset));
2988 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2989 OM->BaseSelectorID - SelectorIDOffset));
2990 DeclRemap.insert(std::make_pair(DeclIDOffset,
2991 OM->BaseDeclID - DeclIDOffset));
2992
2993 TypeRemap.insert(std::make_pair(TypeIndexOffset,
2994 OM->BaseTypeIndex - TypeIndexOffset));
2995
2996 // Global -> local mappings.
2997 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2998 }
2999 break;
3000 }
3001
3002 case SOURCE_MANAGER_LINE_TABLE:
3003 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003004 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003005 break;
3006
3007 case SOURCE_LOCATION_PRELOADS: {
3008 // Need to transform from the local view (1-based IDs) to the global view,
3009 // which is based off F.SLocEntryBaseID.
3010 if (!F.PreloadSLocEntries.empty()) {
3011 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003012 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003013 }
3014
3015 F.PreloadSLocEntries.swap(Record);
3016 break;
3017 }
3018
3019 case EXT_VECTOR_DECLS:
3020 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3021 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3022 break;
3023
3024 case VTABLE_USES:
3025 if (Record.size() % 3 != 0) {
3026 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003027 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003028 }
3029
3030 // Later tables overwrite earlier ones.
3031 // FIXME: Modules will have some trouble with this. This is clearly not
3032 // the right way to do this.
3033 VTableUses.clear();
3034
3035 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3036 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3037 VTableUses.push_back(
3038 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3039 VTableUses.push_back(Record[Idx++]);
3040 }
3041 break;
3042
3043 case DYNAMIC_CLASSES:
3044 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3045 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
3046 break;
3047
3048 case PENDING_IMPLICIT_INSTANTIATIONS:
3049 if (PendingInstantiations.size() % 2 != 0) {
3050 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003051 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003052 }
3053
3054 if (Record.size() % 2 != 0) {
3055 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003056 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003057 }
3058
3059 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3060 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3061 PendingInstantiations.push_back(
3062 ReadSourceLocation(F, Record, I).getRawEncoding());
3063 }
3064 break;
3065
3066 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00003067 if (Record.size() != 2) {
3068 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003069 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003070 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003071 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3072 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3073 break;
3074
3075 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003076 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3077 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3078 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003079
3080 unsigned LocalBasePreprocessedEntityID = Record[0];
3081
3082 unsigned StartingID;
3083 if (!PP.getPreprocessingRecord())
3084 PP.createPreprocessingRecord();
3085 if (!PP.getPreprocessingRecord()->getExternalSource())
3086 PP.getPreprocessingRecord()->SetExternalSource(*this);
3087 StartingID
3088 = PP.getPreprocessingRecord()
3089 ->allocateLoadedEntities(F.NumPreprocessedEntities);
3090 F.BasePreprocessedEntityID = StartingID;
3091
3092 if (F.NumPreprocessedEntities > 0) {
3093 // Introduce the global -> local mapping for preprocessed entities in
3094 // this module.
3095 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3096
3097 // Introduce the local -> global mapping for preprocessed entities in
3098 // this module.
3099 F.PreprocessedEntityRemap.insertOrReplace(
3100 std::make_pair(LocalBasePreprocessedEntityID,
3101 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3102 }
3103
3104 break;
3105 }
3106
3107 case DECL_UPDATE_OFFSETS: {
3108 if (Record.size() % 2 != 0) {
3109 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003110 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003111 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003112 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3113 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3114 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3115
3116 // If we've already loaded the decl, perform the updates when we finish
3117 // loading this block.
3118 if (Decl *D = GetExistingDecl(ID))
3119 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3120 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003121 break;
3122 }
3123
3124 case DECL_REPLACEMENTS: {
3125 if (Record.size() % 3 != 0) {
3126 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003127 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003128 }
3129 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3130 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3131 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3132 break;
3133 }
3134
3135 case OBJC_CATEGORIES_MAP: {
3136 if (F.LocalNumObjCCategoriesInMap != 0) {
3137 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003138 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003139 }
3140
3141 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003142 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003143 break;
3144 }
3145
3146 case OBJC_CATEGORIES:
3147 F.ObjCCategories.swap(Record);
3148 break;
3149
3150 case CXX_BASE_SPECIFIER_OFFSETS: {
3151 if (F.LocalNumCXXBaseSpecifiers != 0) {
3152 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003153 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003154 }
3155
3156 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003157 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003158 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
3159 break;
3160 }
3161
3162 case DIAG_PRAGMA_MAPPINGS:
3163 if (F.PragmaDiagMappings.empty())
3164 F.PragmaDiagMappings.swap(Record);
3165 else
3166 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3167 Record.begin(), Record.end());
3168 break;
3169
3170 case CUDA_SPECIAL_DECL_REFS:
3171 // Later tables overwrite earlier ones.
3172 // FIXME: Modules will have trouble with this.
3173 CUDASpecialDeclRefs.clear();
3174 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3175 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3176 break;
3177
3178 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003179 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003180 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003181 if (Record[0]) {
3182 F.HeaderFileInfoTable
3183 = HeaderFileInfoLookupTable::Create(
3184 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3185 (const unsigned char *)F.HeaderFileInfoTableData,
3186 HeaderFileInfoTrait(*this, F,
3187 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003188 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003189
3190 PP.getHeaderSearchInfo().SetExternalSource(this);
3191 if (!PP.getHeaderSearchInfo().getExternalLookup())
3192 PP.getHeaderSearchInfo().SetExternalLookup(this);
3193 }
3194 break;
3195 }
3196
3197 case FP_PRAGMA_OPTIONS:
3198 // Later tables overwrite earlier ones.
3199 FPPragmaOptions.swap(Record);
3200 break;
3201
3202 case OPENCL_EXTENSIONS:
3203 // Later tables overwrite earlier ones.
3204 OpenCLExtensions.swap(Record);
3205 break;
3206
3207 case TENTATIVE_DEFINITIONS:
3208 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3209 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3210 break;
3211
3212 case KNOWN_NAMESPACES:
3213 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3214 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3215 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003216
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003217 case UNDEFINED_BUT_USED:
3218 if (UndefinedButUsed.size() % 2 != 0) {
3219 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003220 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003221 }
3222
3223 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003224 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003225 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003226 }
3227 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003228 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3229 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003230 ReadSourceLocation(F, Record, I).getRawEncoding());
3231 }
3232 break;
3233
Guy Benyei11169dd2012-12-18 14:30:41 +00003234 case IMPORTED_MODULES: {
3235 if (F.Kind != MK_Module) {
3236 // If we aren't loading a module (which has its own exports), make
3237 // all of the imported modules visible.
3238 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003239 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3240 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3241 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3242 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003243 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003244 }
3245 }
3246 break;
3247 }
3248
3249 case LOCAL_REDECLARATIONS: {
3250 F.RedeclarationChains.swap(Record);
3251 break;
3252 }
3253
3254 case LOCAL_REDECLARATIONS_MAP: {
3255 if (F.LocalNumRedeclarationsInMap != 0) {
3256 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003257 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003258 }
3259
3260 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003261 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003262 break;
3263 }
3264
3265 case MERGED_DECLARATIONS: {
3266 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3267 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3268 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3269 for (unsigned N = Record[Idx++]; N > 0; --N)
3270 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3271 }
3272 break;
3273 }
3274
3275 case MACRO_OFFSET: {
3276 if (F.LocalNumMacros != 0) {
3277 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003278 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003279 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003280 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003281 F.LocalNumMacros = Record[0];
3282 unsigned LocalBaseMacroID = Record[1];
3283 F.BaseMacroID = getTotalNumMacros();
3284
3285 if (F.LocalNumMacros > 0) {
3286 // Introduce the global -> local mapping for macros within this module.
3287 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3288
3289 // Introduce the local -> global mapping for macros within this module.
3290 F.MacroRemap.insertOrReplace(
3291 std::make_pair(LocalBaseMacroID,
3292 F.BaseMacroID - LocalBaseMacroID));
3293
3294 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3295 }
3296 break;
3297 }
3298
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003299 case MACRO_TABLE: {
3300 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00003301 break;
3302 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00003303
3304 case LATE_PARSED_TEMPLATE: {
3305 LateParsedTemplates.append(Record.begin(), Record.end());
3306 break;
3307 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003308
3309 case OPTIMIZE_PRAGMA_OPTIONS:
3310 if (Record.size() != 1) {
3311 Error("invalid pragma optimize record");
3312 return Failure;
3313 }
3314 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3315 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003316 }
3317 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003318}
3319
Douglas Gregorc1489562013-02-12 23:36:21 +00003320/// \brief Move the given method to the back of the global list of methods.
3321static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3322 // Find the entry for this selector in the method pool.
3323 Sema::GlobalMethodPool::iterator Known
3324 = S.MethodPool.find(Method->getSelector());
3325 if (Known == S.MethodPool.end())
3326 return;
3327
3328 // Retrieve the appropriate method list.
3329 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3330 : Known->second.second;
3331 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003332 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003333 if (!Found) {
3334 if (List->Method == Method) {
3335 Found = true;
3336 } else {
3337 // Keep searching.
3338 continue;
3339 }
3340 }
3341
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003342 if (List->getNext())
3343 List->Method = List->getNext()->Method;
Douglas Gregorc1489562013-02-12 23:36:21 +00003344 else
3345 List->Method = Method;
3346 }
3347}
3348
Richard Smithe657bbd2014-07-18 22:13:40 +00003349void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner,
3350 bool FromFinalization) {
3351 // FIXME: Only do this if Owner->NameVisibility == AllVisible.
Richard Smith57721ac2014-07-21 04:10:40 +00003352 for (Decl *D : Names.HiddenDecls) {
Richard Smith49f906a2014-03-01 00:08:04 +00003353 bool wasHidden = D->Hidden;
3354 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003355
Richard Smith49f906a2014-03-01 00:08:04 +00003356 if (wasHidden && SemaObj) {
3357 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3358 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003359 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003360 }
3361 }
Richard Smith49f906a2014-03-01 00:08:04 +00003362
Richard Smithe657bbd2014-07-18 22:13:40 +00003363 assert((FromFinalization || Owner->NameVisibility >= Module::MacrosVisible) &&
3364 "nothing to make visible?");
Richard Smithdaa69e02014-07-25 04:40:03 +00003365 for (const auto &Macro : Names.HiddenMacros) {
3366 if (FromFinalization)
3367 PP.appendMacroDirective(Macro.first,
3368 Macro.second->import(PP, SourceLocation()));
3369 else
3370 installImportedMacro(Macro.first, Macro.second, Owner);
3371 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003372}
3373
Richard Smith49f906a2014-03-01 00:08:04 +00003374void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003375 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003376 SourceLocation ImportLoc,
3377 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003378 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003379 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003380 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003381 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003382 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003383
3384 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003385 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003386 // there is nothing more to do.
3387 continue;
3388 }
Richard Smith49f906a2014-03-01 00:08:04 +00003389
Guy Benyei11169dd2012-12-18 14:30:41 +00003390 if (!Mod->isAvailable()) {
3391 // Modules that aren't available cannot be made visible.
3392 continue;
3393 }
3394
3395 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003396 if (NameVisibility >= Module::MacrosVisible &&
3397 Mod->NameVisibility < Module::MacrosVisible)
3398 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003399 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003400
Guy Benyei11169dd2012-12-18 14:30:41 +00003401 // If we've already deserialized any names from this module,
3402 // mark them as visible.
3403 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3404 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003405 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003406 HiddenNamesMap.erase(Hidden);
Richard Smith57721ac2014-07-21 04:10:40 +00003407 makeNamesVisible(HiddenNames.second, HiddenNames.first,
3408 /*FromFinalization*/false);
3409 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3410 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003411 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003412
Guy Benyei11169dd2012-12-18 14:30:41 +00003413 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003414 SmallVector<Module *, 16> Exports;
3415 Mod->getExportedModules(Exports);
3416 for (SmallVectorImpl<Module *>::iterator
3417 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3418 Module *Exported = *I;
3419 if (Visited.insert(Exported))
3420 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003421 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003422
3423 // Detect any conflicts.
3424 if (Complain) {
3425 assert(ImportLoc.isValid() && "Missing import location");
3426 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3427 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3428 Diag(ImportLoc, diag::warn_module_conflict)
3429 << Mod->getFullModuleName()
3430 << Mod->Conflicts[I].Other->getFullModuleName()
3431 << Mod->Conflicts[I].Message;
3432 // FIXME: Need note where the other module was imported.
3433 }
3434 }
3435 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003436 }
3437}
3438
Douglas Gregore060e572013-01-25 01:03:03 +00003439bool ASTReader::loadGlobalIndex() {
3440 if (GlobalIndex)
3441 return false;
3442
3443 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3444 !Context.getLangOpts().Modules)
3445 return true;
3446
3447 // Try to load the global index.
3448 TriedLoadingGlobalIndex = true;
3449 StringRef ModuleCachePath
3450 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3451 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003452 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003453 if (!Result.first)
3454 return true;
3455
3456 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003457 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003458 return false;
3459}
3460
3461bool ASTReader::isGlobalIndexUnavailable() const {
3462 return Context.getLangOpts().Modules && UseGlobalIndex &&
3463 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3464}
3465
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003466static void updateModuleTimestamp(ModuleFile &MF) {
3467 // Overwrite the timestamp file contents so that file's mtime changes.
3468 std::string TimestampFilename = MF.getTimestampFilename();
3469 std::string ErrorInfo;
Rafael Espindola04a13be2014-02-24 15:06:52 +00003470 llvm::raw_fd_ostream OS(TimestampFilename.c_str(), ErrorInfo,
Rafael Espindola4fbd3732014-02-24 18:20:21 +00003471 llvm::sys::fs::F_Text);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003472 if (!ErrorInfo.empty())
3473 return;
3474 OS << "Timestamp file\n";
3475}
3476
Guy Benyei11169dd2012-12-18 14:30:41 +00003477ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3478 ModuleKind Type,
3479 SourceLocation ImportLoc,
3480 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003481 llvm::SaveAndRestore<SourceLocation>
3482 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3483
Richard Smithd1c46742014-04-30 02:24:17 +00003484 // Defer any pending actions until we get to the end of reading the AST file.
3485 Deserializing AnASTFile(this);
3486
Guy Benyei11169dd2012-12-18 14:30:41 +00003487 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003488 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003489
3490 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003491 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003492 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003493 /*ImportedBy=*/nullptr, Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003494 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003495 ClientLoadCapabilities)) {
3496 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003497 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003498 case OutOfDate:
3499 case VersionMismatch:
3500 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003501 case HadErrors: {
3502 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3503 for (const ImportedModule &IM : Loaded)
3504 LoadedSet.insert(IM.Mod);
3505
Douglas Gregor7029ce12013-03-19 00:28:20 +00003506 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003507 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003508 Context.getLangOpts().Modules
3509 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003510 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003511
3512 // If we find that any modules are unusable, the global index is going
3513 // to be out-of-date. Just remove it.
3514 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003515 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003516 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003517 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003518 case Success:
3519 break;
3520 }
3521
3522 // Here comes stuff that we only do once the entire chain is loaded.
3523
3524 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003525 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3526 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003527 M != MEnd; ++M) {
3528 ModuleFile &F = *M->Mod;
3529
3530 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003531 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3532 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003533
3534 // Once read, set the ModuleFile bit base offset and update the size in
3535 // bits of all files we've seen.
3536 F.GlobalBitOffset = TotalModulesSizeInBits;
3537 TotalModulesSizeInBits += F.SizeInBits;
3538 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3539
3540 // Preload SLocEntries.
3541 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3542 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3543 // Load it through the SourceManager and don't call ReadSLocEntry()
3544 // directly because the entry may have already been loaded in which case
3545 // calling ReadSLocEntry() directly would trigger an assertion in
3546 // SourceManager.
3547 SourceMgr.getLoadedSLocEntryByID(Index);
3548 }
3549 }
3550
Douglas Gregor603cd862013-03-22 18:50:14 +00003551 // Setup the import locations and notify the module manager that we've
3552 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003553 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3554 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003555 M != MEnd; ++M) {
3556 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003557
3558 ModuleMgr.moduleFileAccepted(&F);
3559
3560 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003561 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003562 if (!M->ImportedBy)
3563 F.ImportLoc = M->ImportLoc;
3564 else
3565 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3566 M->ImportLoc.getRawEncoding());
3567 }
3568
3569 // Mark all of the identifiers in the identifier table as being out of date,
3570 // so that various accessors know to check the loaded modules when the
3571 // identifier is used.
3572 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3573 IdEnd = PP.getIdentifierTable().end();
3574 Id != IdEnd; ++Id)
3575 Id->second->setOutOfDate(true);
3576
3577 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003578 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3579 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003580 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3581 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003582
3583 switch (Unresolved.Kind) {
3584 case UnresolvedModuleRef::Conflict:
3585 if (ResolvedMod) {
3586 Module::Conflict Conflict;
3587 Conflict.Other = ResolvedMod;
3588 Conflict.Message = Unresolved.String.str();
3589 Unresolved.Mod->Conflicts.push_back(Conflict);
3590 }
3591 continue;
3592
3593 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003594 if (ResolvedMod)
3595 Unresolved.Mod->Imports.push_back(ResolvedMod);
3596 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003597
Douglas Gregorfb912652013-03-20 21:10:35 +00003598 case UnresolvedModuleRef::Export:
3599 if (ResolvedMod || Unresolved.IsWildcard)
3600 Unresolved.Mod->Exports.push_back(
3601 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3602 continue;
3603 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003604 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003605 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003606
3607 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3608 // Might be unnecessary as use declarations are only used to build the
3609 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003610
3611 InitializeContext();
3612
Richard Smith3d8e97e2013-10-18 06:54:39 +00003613 if (SemaObj)
3614 UpdateSema();
3615
Guy Benyei11169dd2012-12-18 14:30:41 +00003616 if (DeserializationListener)
3617 DeserializationListener->ReaderInitialized(this);
3618
3619 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3620 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3621 PrimaryModule.OriginalSourceFileID
3622 = FileID::get(PrimaryModule.SLocEntryBaseID
3623 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3624
3625 // If this AST file is a precompiled preamble, then set the
3626 // preamble file ID of the source manager to the file source file
3627 // from which the preamble was built.
3628 if (Type == MK_Preamble) {
3629 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3630 } else if (Type == MK_MainFile) {
3631 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3632 }
3633 }
3634
3635 // For any Objective-C class definitions we have already loaded, make sure
3636 // that we load any additional categories.
3637 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3638 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3639 ObjCClassesLoaded[I],
3640 PreviousGeneration);
3641 }
Douglas Gregore060e572013-01-25 01:03:03 +00003642
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003643 if (PP.getHeaderSearchInfo()
3644 .getHeaderSearchOpts()
3645 .ModulesValidateOncePerBuildSession) {
3646 // Now we are certain that the module and all modules it depends on are
3647 // up to date. Create or update timestamp files for modules that are
3648 // located in the module cache (not for PCH files that could be anywhere
3649 // in the filesystem).
3650 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3651 ImportedModule &M = Loaded[I];
3652 if (M.Mod->Kind == MK_Module) {
3653 updateModuleTimestamp(*M.Mod);
3654 }
3655 }
3656 }
3657
Guy Benyei11169dd2012-12-18 14:30:41 +00003658 return Success;
3659}
3660
3661ASTReader::ASTReadResult
3662ASTReader::ReadASTCore(StringRef FileName,
3663 ModuleKind Type,
3664 SourceLocation ImportLoc,
3665 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003666 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003667 off_t ExpectedSize, time_t ExpectedModTime,
Guy Benyei11169dd2012-12-18 14:30:41 +00003668 unsigned ClientLoadCapabilities) {
3669 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003670 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003671 ModuleManager::AddModuleResult AddResult
3672 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003673 getGeneration(), ExpectedSize, ExpectedModTime,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003674 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003675
Douglas Gregor7029ce12013-03-19 00:28:20 +00003676 switch (AddResult) {
3677 case ModuleManager::AlreadyLoaded:
3678 return Success;
3679
3680 case ModuleManager::NewlyLoaded:
3681 // Load module file below.
3682 break;
3683
3684 case ModuleManager::Missing:
3685 // The module file was missing; if the client handle handle, that, return
3686 // it.
3687 if (ClientLoadCapabilities & ARR_Missing)
3688 return Missing;
3689
3690 // Otherwise, return an error.
3691 {
3692 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3693 + ErrorStr;
3694 Error(Msg);
3695 }
3696 return Failure;
3697
3698 case ModuleManager::OutOfDate:
3699 // We couldn't load the module file because it is out-of-date. If the
3700 // client can handle out-of-date, return it.
3701 if (ClientLoadCapabilities & ARR_OutOfDate)
3702 return OutOfDate;
3703
3704 // Otherwise, return an error.
3705 {
3706 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3707 + ErrorStr;
3708 Error(Msg);
3709 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003710 return Failure;
3711 }
3712
Douglas Gregor7029ce12013-03-19 00:28:20 +00003713 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003714
3715 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3716 // module?
3717 if (FileName != "-") {
3718 CurrentDir = llvm::sys::path::parent_path(FileName);
3719 if (CurrentDir.empty()) CurrentDir = ".";
3720 }
3721
3722 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003723 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003724 Stream.init(F.StreamFile);
3725 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3726
3727 // Sniff for the signature.
3728 if (Stream.Read(8) != 'C' ||
3729 Stream.Read(8) != 'P' ||
3730 Stream.Read(8) != 'C' ||
3731 Stream.Read(8) != 'H') {
3732 Diag(diag::err_not_a_pch_file) << FileName;
3733 return Failure;
3734 }
3735
3736 // This is used for compatibility with older PCH formats.
3737 bool HaveReadControlBlock = false;
3738
Chris Lattnerefa77172013-01-20 00:00:22 +00003739 while (1) {
3740 llvm::BitstreamEntry Entry = Stream.advance();
3741
3742 switch (Entry.Kind) {
3743 case llvm::BitstreamEntry::Error:
3744 case llvm::BitstreamEntry::EndBlock:
3745 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003746 Error("invalid record at top-level of AST file");
3747 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003748
3749 case llvm::BitstreamEntry::SubBlock:
3750 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003751 }
3752
Guy Benyei11169dd2012-12-18 14:30:41 +00003753 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003754 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003755 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3756 if (Stream.ReadBlockInfoBlock()) {
3757 Error("malformed BlockInfoBlock in AST file");
3758 return Failure;
3759 }
3760 break;
3761 case CONTROL_BLOCK_ID:
3762 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003763 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003764 case Success:
3765 break;
3766
3767 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003768 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003769 case OutOfDate: return OutOfDate;
3770 case VersionMismatch: return VersionMismatch;
3771 case ConfigurationMismatch: return ConfigurationMismatch;
3772 case HadErrors: return HadErrors;
3773 }
3774 break;
3775 case AST_BLOCK_ID:
3776 if (!HaveReadControlBlock) {
3777 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003778 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003779 return VersionMismatch;
3780 }
3781
3782 // Record that we've loaded this module.
3783 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3784 return Success;
3785
3786 default:
3787 if (Stream.SkipBlock()) {
3788 Error("malformed block record in AST file");
3789 return Failure;
3790 }
3791 break;
3792 }
3793 }
3794
3795 return Success;
3796}
3797
3798void ASTReader::InitializeContext() {
3799 // If there's a listener, notify them that we "read" the translation unit.
3800 if (DeserializationListener)
3801 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3802 Context.getTranslationUnitDecl());
3803
Guy Benyei11169dd2012-12-18 14:30:41 +00003804 // FIXME: Find a better way to deal with collisions between these
3805 // built-in types. Right now, we just ignore the problem.
3806
3807 // Load the special types.
3808 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3809 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3810 if (!Context.CFConstantStringTypeDecl)
3811 Context.setCFConstantStringType(GetType(String));
3812 }
3813
3814 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3815 QualType FileType = GetType(File);
3816 if (FileType.isNull()) {
3817 Error("FILE type is NULL");
3818 return;
3819 }
3820
3821 if (!Context.FILEDecl) {
3822 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3823 Context.setFILEDecl(Typedef->getDecl());
3824 else {
3825 const TagType *Tag = FileType->getAs<TagType>();
3826 if (!Tag) {
3827 Error("Invalid FILE type in AST file");
3828 return;
3829 }
3830 Context.setFILEDecl(Tag->getDecl());
3831 }
3832 }
3833 }
3834
3835 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3836 QualType Jmp_bufType = GetType(Jmp_buf);
3837 if (Jmp_bufType.isNull()) {
3838 Error("jmp_buf type is NULL");
3839 return;
3840 }
3841
3842 if (!Context.jmp_bufDecl) {
3843 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3844 Context.setjmp_bufDecl(Typedef->getDecl());
3845 else {
3846 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3847 if (!Tag) {
3848 Error("Invalid jmp_buf type in AST file");
3849 return;
3850 }
3851 Context.setjmp_bufDecl(Tag->getDecl());
3852 }
3853 }
3854 }
3855
3856 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3857 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3858 if (Sigjmp_bufType.isNull()) {
3859 Error("sigjmp_buf type is NULL");
3860 return;
3861 }
3862
3863 if (!Context.sigjmp_bufDecl) {
3864 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3865 Context.setsigjmp_bufDecl(Typedef->getDecl());
3866 else {
3867 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3868 assert(Tag && "Invalid sigjmp_buf type in AST file");
3869 Context.setsigjmp_bufDecl(Tag->getDecl());
3870 }
3871 }
3872 }
3873
3874 if (unsigned ObjCIdRedef
3875 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3876 if (Context.ObjCIdRedefinitionType.isNull())
3877 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3878 }
3879
3880 if (unsigned ObjCClassRedef
3881 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3882 if (Context.ObjCClassRedefinitionType.isNull())
3883 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3884 }
3885
3886 if (unsigned ObjCSelRedef
3887 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3888 if (Context.ObjCSelRedefinitionType.isNull())
3889 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3890 }
3891
3892 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3893 QualType Ucontext_tType = GetType(Ucontext_t);
3894 if (Ucontext_tType.isNull()) {
3895 Error("ucontext_t type is NULL");
3896 return;
3897 }
3898
3899 if (!Context.ucontext_tDecl) {
3900 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3901 Context.setucontext_tDecl(Typedef->getDecl());
3902 else {
3903 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3904 assert(Tag && "Invalid ucontext_t type in AST file");
3905 Context.setucontext_tDecl(Tag->getDecl());
3906 }
3907 }
3908 }
3909 }
3910
3911 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3912
3913 // If there were any CUDA special declarations, deserialize them.
3914 if (!CUDASpecialDeclRefs.empty()) {
3915 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3916 Context.setcudaConfigureCallDecl(
3917 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3918 }
Richard Smith56be7542014-03-21 00:33:59 +00003919
Guy Benyei11169dd2012-12-18 14:30:41 +00003920 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00003921 // FIXME: This does not make macro-only imports visible again. It also doesn't
3922 // make #includes mapped to module imports visible.
3923 for (auto &Import : ImportedModules) {
3924 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003925 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00003926 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00003927 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00003928 }
3929 ImportedModules.clear();
3930}
3931
3932void ASTReader::finalizeForWriting() {
Richard Smith57721ac2014-07-21 04:10:40 +00003933 while (!HiddenNamesMap.empty()) {
3934 auto HiddenNames = std::move(*HiddenNamesMap.begin());
3935 HiddenNamesMap.erase(HiddenNamesMap.begin());
3936 makeNamesVisible(HiddenNames.second, HiddenNames.first,
3937 /*FromFinalization*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00003938 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003939}
3940
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003941/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3942/// cursor into the start of the given block ID, returning false on success and
3943/// true on failure.
3944static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003945 while (1) {
3946 llvm::BitstreamEntry Entry = Cursor.advance();
3947 switch (Entry.Kind) {
3948 case llvm::BitstreamEntry::Error:
3949 case llvm::BitstreamEntry::EndBlock:
3950 return true;
3951
3952 case llvm::BitstreamEntry::Record:
3953 // Ignore top-level records.
3954 Cursor.skipRecord(Entry.ID);
3955 break;
3956
3957 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003958 if (Entry.ID == BlockID) {
3959 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003960 return true;
3961 // Found it!
3962 return false;
3963 }
3964
3965 if (Cursor.SkipBlock())
3966 return true;
3967 }
3968 }
3969}
3970
Guy Benyei11169dd2012-12-18 14:30:41 +00003971/// \brief Retrieve the name of the original source file name
3972/// directly from the AST file, without actually loading the AST
3973/// file.
3974std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3975 FileManager &FileMgr,
3976 DiagnosticsEngine &Diags) {
3977 // Open the AST file.
3978 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00003979 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00003980 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3981 if (!Buffer) {
3982 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3983 return std::string();
3984 }
3985
3986 // Initialize the stream
3987 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003988 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00003989 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3990 (const unsigned char *)Buffer->getBufferEnd());
3991 Stream.init(StreamFile);
3992
3993 // Sniff for the signature.
3994 if (Stream.Read(8) != 'C' ||
3995 Stream.Read(8) != 'P' ||
3996 Stream.Read(8) != 'C' ||
3997 Stream.Read(8) != 'H') {
3998 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3999 return std::string();
4000 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004001
Chris Lattnere7b154b2013-01-19 21:39:22 +00004002 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004003 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004004 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4005 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004006 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004007
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004008 // Scan for ORIGINAL_FILE inside the control block.
4009 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004010 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004011 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004012 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4013 return std::string();
4014
4015 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4016 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4017 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004018 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004019
Guy Benyei11169dd2012-12-18 14:30:41 +00004020 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004021 StringRef Blob;
4022 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4023 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004024 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004025}
4026
4027namespace {
4028 class SimplePCHValidator : public ASTReaderListener {
4029 const LangOptions &ExistingLangOpts;
4030 const TargetOptions &ExistingTargetOpts;
4031 const PreprocessorOptions &ExistingPPOpts;
4032 FileManager &FileMgr;
4033
4034 public:
4035 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4036 const TargetOptions &ExistingTargetOpts,
4037 const PreprocessorOptions &ExistingPPOpts,
4038 FileManager &FileMgr)
4039 : ExistingLangOpts(ExistingLangOpts),
4040 ExistingTargetOpts(ExistingTargetOpts),
4041 ExistingPPOpts(ExistingPPOpts),
4042 FileMgr(FileMgr)
4043 {
4044 }
4045
Craig Topper3e89dfe2014-03-13 02:13:41 +00004046 bool ReadLanguageOptions(const LangOptions &LangOpts,
4047 bool Complain) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004048 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004049 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004050 bool ReadTargetOptions(const TargetOptions &TargetOpts,
4051 bool Complain) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004052 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004053 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004054 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4055 bool Complain,
4056 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004057 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004058 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004059 }
4060 };
4061}
4062
4063bool ASTReader::readASTFileControlBlock(StringRef Filename,
4064 FileManager &FileMgr,
4065 ASTReaderListener &Listener) {
4066 // Open the AST file.
4067 std::string ErrStr;
Ahmed Charlesb8984322014-03-07 20:03:18 +00004068 std::unique_ptr<llvm::MemoryBuffer> Buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +00004069 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
4070 if (!Buffer) {
4071 return true;
4072 }
4073
4074 // Initialize the stream
4075 llvm::BitstreamReader StreamFile;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004076 BitstreamCursor Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00004077 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
4078 (const unsigned char *)Buffer->getBufferEnd());
4079 Stream.init(StreamFile);
4080
4081 // Sniff for the signature.
4082 if (Stream.Read(8) != 'C' ||
4083 Stream.Read(8) != 'P' ||
4084 Stream.Read(8) != 'C' ||
4085 Stream.Read(8) != 'H') {
4086 return true;
4087 }
4088
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004089 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004090 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004091 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004092
4093 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004094 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004095 BitstreamCursor InputFilesCursor;
4096 if (NeedsInputFiles) {
4097 InputFilesCursor = Stream;
4098 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4099 return true;
4100
4101 // Read the abbreviations
4102 while (true) {
4103 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4104 unsigned Code = InputFilesCursor.ReadCode();
4105
4106 // We expect all abbrevs to be at the start of the block.
4107 if (Code != llvm::bitc::DEFINE_ABBREV) {
4108 InputFilesCursor.JumpToBit(Offset);
4109 break;
4110 }
4111 InputFilesCursor.ReadAbbrevRecord();
4112 }
4113 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004114
4115 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004116 RecordData Record;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004117 while (1) {
4118 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4119 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4120 return false;
4121
4122 if (Entry.Kind != llvm::BitstreamEntry::Record)
4123 return true;
4124
Guy Benyei11169dd2012-12-18 14:30:41 +00004125 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004126 StringRef Blob;
4127 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004128 switch ((ControlRecordTypes)RecCode) {
4129 case METADATA: {
4130 if (Record[0] != VERSION_MAJOR)
4131 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004132
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004133 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004134 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004135
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004136 break;
4137 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004138 case MODULE_NAME:
4139 Listener.ReadModuleName(Blob);
4140 break;
4141 case MODULE_MAP_FILE:
4142 Listener.ReadModuleMapFile(Blob);
4143 break;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004144 case LANGUAGE_OPTIONS:
4145 if (ParseLanguageOptions(Record, false, Listener))
4146 return true;
4147 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004148
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004149 case TARGET_OPTIONS:
4150 if (ParseTargetOptions(Record, false, Listener))
4151 return true;
4152 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004153
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004154 case DIAGNOSTIC_OPTIONS:
4155 if (ParseDiagnosticOptions(Record, false, Listener))
4156 return true;
4157 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004158
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004159 case FILE_SYSTEM_OPTIONS:
4160 if (ParseFileSystemOptions(Record, false, Listener))
4161 return true;
4162 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004163
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004164 case HEADER_SEARCH_OPTIONS:
4165 if (ParseHeaderSearchOptions(Record, false, Listener))
4166 return true;
4167 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004168
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004169 case PREPROCESSOR_OPTIONS: {
4170 std::string IgnoredSuggestedPredefines;
4171 if (ParsePreprocessorOptions(Record, false, Listener,
4172 IgnoredSuggestedPredefines))
4173 return true;
4174 break;
4175 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004176
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004177 case INPUT_FILE_OFFSETS: {
4178 if (!NeedsInputFiles)
4179 break;
4180
4181 unsigned NumInputFiles = Record[0];
4182 unsigned NumUserFiles = Record[1];
4183 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
4184 for (unsigned I = 0; I != NumInputFiles; ++I) {
4185 // Go find this input file.
4186 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004187
4188 if (isSystemFile && !NeedsSystemInputFiles)
4189 break; // the rest are system input files
4190
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004191 BitstreamCursor &Cursor = InputFilesCursor;
4192 SavedStreamPosition SavedPosition(Cursor);
4193 Cursor.JumpToBit(InputFileOffs[I]);
4194
4195 unsigned Code = Cursor.ReadCode();
4196 RecordData Record;
4197 StringRef Blob;
4198 bool shouldContinue = false;
4199 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4200 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004201 bool Overridden = static_cast<bool>(Record[3]);
4202 shouldContinue = Listener.visitInputFile(Blob, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004203 break;
4204 }
4205 if (!shouldContinue)
4206 break;
4207 }
4208 break;
4209 }
4210
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004211 default:
4212 // No other validation to perform.
4213 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004214 }
4215 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004216}
4217
4218
4219bool ASTReader::isAcceptableASTFile(StringRef Filename,
4220 FileManager &FileMgr,
4221 const LangOptions &LangOpts,
4222 const TargetOptions &TargetOpts,
4223 const PreprocessorOptions &PPOpts) {
4224 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
4225 return !readASTFileControlBlock(Filename, FileMgr, validator);
4226}
4227
Ben Langmuir2c9af442014-04-10 17:57:43 +00004228ASTReader::ASTReadResult
4229ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004230 // Enter the submodule block.
4231 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4232 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004233 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004234 }
4235
4236 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4237 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004238 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004239 RecordData Record;
4240 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004241 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4242
4243 switch (Entry.Kind) {
4244 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4245 case llvm::BitstreamEntry::Error:
4246 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004247 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004248 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004249 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004250 case llvm::BitstreamEntry::Record:
4251 // The interesting case.
4252 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004253 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004254
Guy Benyei11169dd2012-12-18 14:30:41 +00004255 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004256 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004257 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004258 switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004259 default: // Default behavior: ignore.
4260 break;
4261
4262 case SUBMODULE_DEFINITION: {
4263 if (First) {
4264 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004265 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004266 }
4267
Douglas Gregor8d932422013-03-20 03:59:18 +00004268 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004269 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004270 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004271 }
4272
Chris Lattner0e6c9402013-01-20 02:38:54 +00004273 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004274 unsigned Idx = 0;
4275 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4276 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4277 bool IsFramework = Record[Idx++];
4278 bool IsExplicit = Record[Idx++];
4279 bool IsSystem = Record[Idx++];
4280 bool IsExternC = Record[Idx++];
4281 bool InferSubmodules = Record[Idx++];
4282 bool InferExplicitSubmodules = Record[Idx++];
4283 bool InferExportWildcard = Record[Idx++];
4284 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004285
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004286 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004287 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004288 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004289
Guy Benyei11169dd2012-12-18 14:30:41 +00004290 // Retrieve this (sub)module from the module map, creating it if
4291 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004292 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004293 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004294
4295 // FIXME: set the definition loc for CurrentModule, or call
4296 // ModMap.setInferredModuleAllowedBy()
4297
Guy Benyei11169dd2012-12-18 14:30:41 +00004298 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4299 if (GlobalIndex >= SubmodulesLoaded.size() ||
4300 SubmodulesLoaded[GlobalIndex]) {
4301 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004302 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004303 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004304
Douglas Gregor7029ce12013-03-19 00:28:20 +00004305 if (!ParentModule) {
4306 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4307 if (CurFile != F.File) {
4308 if (!Diags.isDiagnosticInFlight()) {
4309 Diag(diag::err_module_file_conflict)
4310 << CurrentModule->getTopLevelModuleName()
4311 << CurFile->getName()
4312 << F.File->getName();
4313 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004314 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004315 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004316 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004317
4318 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004319 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004320
Guy Benyei11169dd2012-12-18 14:30:41 +00004321 CurrentModule->IsFromModuleFile = true;
4322 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004323 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004324 CurrentModule->InferSubmodules = InferSubmodules;
4325 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4326 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004327 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004328 if (DeserializationListener)
4329 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4330
4331 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004332
Douglas Gregorfb912652013-03-20 21:10:35 +00004333 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004334 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004335 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004336 CurrentModule->UnresolvedConflicts.clear();
4337 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004338 break;
4339 }
4340
4341 case SUBMODULE_UMBRELLA_HEADER: {
4342 if (First) {
4343 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004344 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004345 }
4346
4347 if (!CurrentModule)
4348 break;
4349
Chris Lattner0e6c9402013-01-20 02:38:54 +00004350 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004351 if (!CurrentModule->getUmbrellaHeader())
4352 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4353 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004354 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4355 Error("mismatched umbrella headers in submodule");
4356 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004357 }
4358 }
4359 break;
4360 }
4361
4362 case SUBMODULE_HEADER: {
4363 if (First) {
4364 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004365 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004366 }
4367
4368 if (!CurrentModule)
4369 break;
4370
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004371 // We lazily associate headers with their modules via the HeaderInfoTable.
4372 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4373 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004374 break;
4375 }
4376
4377 case SUBMODULE_EXCLUDED_HEADER: {
4378 if (First) {
4379 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004380 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004381 }
4382
4383 if (!CurrentModule)
4384 break;
4385
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004386 // We lazily associate headers with their modules via the HeaderInfoTable.
4387 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4388 // of complete filenames or remove it entirely.
Guy Benyei11169dd2012-12-18 14:30:41 +00004389 break;
4390 }
4391
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004392 case SUBMODULE_PRIVATE_HEADER: {
4393 if (First) {
4394 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004395 return Failure;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004396 }
4397
4398 if (!CurrentModule)
4399 break;
4400
4401 // We lazily associate headers with their modules via the HeaderInfoTable.
4402 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4403 // of complete filenames or remove it entirely.
4404 break;
4405 }
4406
Guy Benyei11169dd2012-12-18 14:30:41 +00004407 case SUBMODULE_TOPHEADER: {
4408 if (First) {
4409 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004410 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004411 }
4412
4413 if (!CurrentModule)
4414 break;
4415
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004416 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004417 break;
4418 }
4419
4420 case SUBMODULE_UMBRELLA_DIR: {
4421 if (First) {
4422 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004423 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004424 }
4425
4426 if (!CurrentModule)
4427 break;
4428
Guy Benyei11169dd2012-12-18 14:30:41 +00004429 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004430 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004431 if (!CurrentModule->getUmbrellaDir())
4432 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4433 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004434 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4435 Error("mismatched umbrella directories in submodule");
4436 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004437 }
4438 }
4439 break;
4440 }
4441
4442 case SUBMODULE_METADATA: {
4443 if (!First) {
4444 Error("submodule metadata record not at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004445 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004446 }
4447 First = false;
4448
4449 F.BaseSubmoduleID = getTotalNumSubmodules();
4450 F.LocalNumSubmodules = Record[0];
4451 unsigned LocalBaseSubmoduleID = Record[1];
4452 if (F.LocalNumSubmodules > 0) {
4453 // Introduce the global -> local mapping for submodules within this
4454 // module.
4455 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4456
4457 // Introduce the local -> global mapping for submodules within this
4458 // module.
4459 F.SubmoduleRemap.insertOrReplace(
4460 std::make_pair(LocalBaseSubmoduleID,
4461 F.BaseSubmoduleID - LocalBaseSubmoduleID));
4462
4463 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4464 }
4465 break;
4466 }
4467
4468 case SUBMODULE_IMPORTS: {
4469 if (First) {
4470 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004471 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004472 }
4473
4474 if (!CurrentModule)
4475 break;
4476
4477 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004478 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004479 Unresolved.File = &F;
4480 Unresolved.Mod = CurrentModule;
4481 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004482 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004483 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004484 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004485 }
4486 break;
4487 }
4488
4489 case SUBMODULE_EXPORTS: {
4490 if (First) {
4491 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004492 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004493 }
4494
4495 if (!CurrentModule)
4496 break;
4497
4498 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004499 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004500 Unresolved.File = &F;
4501 Unresolved.Mod = CurrentModule;
4502 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004503 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004504 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004505 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004506 }
4507
4508 // Once we've loaded the set of exports, there's no reason to keep
4509 // the parsed, unresolved exports around.
4510 CurrentModule->UnresolvedExports.clear();
4511 break;
4512 }
4513 case SUBMODULE_REQUIRES: {
4514 if (First) {
4515 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004516 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004517 }
4518
4519 if (!CurrentModule)
4520 break;
4521
Richard Smitha3feee22013-10-28 22:18:19 +00004522 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004523 Context.getTargetInfo());
4524 break;
4525 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004526
4527 case SUBMODULE_LINK_LIBRARY:
4528 if (First) {
4529 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004530 return Failure;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004531 }
4532
4533 if (!CurrentModule)
4534 break;
4535
4536 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004537 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004538 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004539
4540 case SUBMODULE_CONFIG_MACRO:
4541 if (First) {
4542 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004543 return Failure;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004544 }
4545
4546 if (!CurrentModule)
4547 break;
4548
4549 CurrentModule->ConfigMacros.push_back(Blob.str());
4550 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004551
4552 case SUBMODULE_CONFLICT: {
4553 if (First) {
4554 Error("missing submodule metadata record at beginning of block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004555 return Failure;
Douglas Gregorfb912652013-03-20 21:10:35 +00004556 }
4557
4558 if (!CurrentModule)
4559 break;
4560
4561 UnresolvedModuleRef Unresolved;
4562 Unresolved.File = &F;
4563 Unresolved.Mod = CurrentModule;
4564 Unresolved.ID = Record[0];
4565 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4566 Unresolved.IsWildcard = false;
4567 Unresolved.String = Blob;
4568 UnresolvedModuleRefs.push_back(Unresolved);
4569 break;
4570 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004571 }
4572 }
4573}
4574
4575/// \brief Parse the record that corresponds to a LangOptions data
4576/// structure.
4577///
4578/// This routine parses the language options from the AST file and then gives
4579/// them to the AST listener if one is set.
4580///
4581/// \returns true if the listener deems the file unacceptable, false otherwise.
4582bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4583 bool Complain,
4584 ASTReaderListener &Listener) {
4585 LangOptions LangOpts;
4586 unsigned Idx = 0;
4587#define LANGOPT(Name, Bits, Default, Description) \
4588 LangOpts.Name = Record[Idx++];
4589#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4590 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4591#include "clang/Basic/LangOptions.def"
Will Dietzf54319c2013-01-18 11:30:38 +00004592#define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
4593#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004594
4595 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4596 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4597 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4598
4599 unsigned Length = Record[Idx++];
4600 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4601 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004602
4603 Idx += Length;
4604
4605 // Comment options.
4606 for (unsigned N = Record[Idx++]; N; --N) {
4607 LangOpts.CommentOpts.BlockCommandNames.push_back(
4608 ReadString(Record, Idx));
4609 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004610 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004611
Guy Benyei11169dd2012-12-18 14:30:41 +00004612 return Listener.ReadLanguageOptions(LangOpts, Complain);
4613}
4614
4615bool ASTReader::ParseTargetOptions(const RecordData &Record,
4616 bool Complain,
4617 ASTReaderListener &Listener) {
4618 unsigned Idx = 0;
4619 TargetOptions TargetOpts;
4620 TargetOpts.Triple = ReadString(Record, Idx);
4621 TargetOpts.CPU = ReadString(Record, Idx);
4622 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004623 for (unsigned N = Record[Idx++]; N; --N) {
4624 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4625 }
4626 for (unsigned N = Record[Idx++]; N; --N) {
4627 TargetOpts.Features.push_back(ReadString(Record, Idx));
4628 }
4629
4630 return Listener.ReadTargetOptions(TargetOpts, Complain);
4631}
4632
4633bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4634 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004635 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004636 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004637#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004638#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004639 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004640#include "clang/Basic/DiagnosticOptions.def"
4641
Richard Smith3be1cb22014-08-07 00:24:21 +00004642 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004643 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004644 for (unsigned N = Record[Idx++]; N; --N)
4645 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004646
4647 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4648}
4649
4650bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4651 ASTReaderListener &Listener) {
4652 FileSystemOptions FSOpts;
4653 unsigned Idx = 0;
4654 FSOpts.WorkingDir = ReadString(Record, Idx);
4655 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4656}
4657
4658bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4659 bool Complain,
4660 ASTReaderListener &Listener) {
4661 HeaderSearchOptions HSOpts;
4662 unsigned Idx = 0;
4663 HSOpts.Sysroot = ReadString(Record, Idx);
4664
4665 // Include entries.
4666 for (unsigned N = Record[Idx++]; N; --N) {
4667 std::string Path = ReadString(Record, Idx);
4668 frontend::IncludeDirGroup Group
4669 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004670 bool IsFramework = Record[Idx++];
4671 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004672 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004673 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004674 }
4675
4676 // System header prefixes.
4677 for (unsigned N = Record[Idx++]; N; --N) {
4678 std::string Prefix = ReadString(Record, Idx);
4679 bool IsSystemHeader = Record[Idx++];
4680 HSOpts.SystemHeaderPrefixes.push_back(
4681 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4682 }
4683
4684 HSOpts.ResourceDir = ReadString(Record, Idx);
4685 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004686 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004687 HSOpts.DisableModuleHash = Record[Idx++];
4688 HSOpts.UseBuiltinIncludes = Record[Idx++];
4689 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4690 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4691 HSOpts.UseLibcxx = Record[Idx++];
4692
4693 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4694}
4695
4696bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4697 bool Complain,
4698 ASTReaderListener &Listener,
4699 std::string &SuggestedPredefines) {
4700 PreprocessorOptions PPOpts;
4701 unsigned Idx = 0;
4702
4703 // Macro definitions/undefs
4704 for (unsigned N = Record[Idx++]; N; --N) {
4705 std::string Macro = ReadString(Record, Idx);
4706 bool IsUndef = Record[Idx++];
4707 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4708 }
4709
4710 // Includes
4711 for (unsigned N = Record[Idx++]; N; --N) {
4712 PPOpts.Includes.push_back(ReadString(Record, Idx));
4713 }
4714
4715 // Macro Includes
4716 for (unsigned N = Record[Idx++]; N; --N) {
4717 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4718 }
4719
4720 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004721 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004722 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4723 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4724 PPOpts.ObjCXXARCStandardLibrary =
4725 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4726 SuggestedPredefines.clear();
4727 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4728 SuggestedPredefines);
4729}
4730
4731std::pair<ModuleFile *, unsigned>
4732ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4733 GlobalPreprocessedEntityMapType::iterator
4734 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4735 assert(I != GlobalPreprocessedEntityMap.end() &&
4736 "Corrupted global preprocessed entity map");
4737 ModuleFile *M = I->second;
4738 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4739 return std::make_pair(M, LocalIndex);
4740}
4741
4742std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4743ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4744 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4745 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4746 Mod.NumPreprocessedEntities);
4747
4748 return std::make_pair(PreprocessingRecord::iterator(),
4749 PreprocessingRecord::iterator());
4750}
4751
4752std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4753ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4754 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4755 ModuleDeclIterator(this, &Mod,
4756 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4757}
4758
4759PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4760 PreprocessedEntityID PPID = Index+1;
4761 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4762 ModuleFile &M = *PPInfo.first;
4763 unsigned LocalIndex = PPInfo.second;
4764 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4765
Guy Benyei11169dd2012-12-18 14:30:41 +00004766 if (!PP.getPreprocessingRecord()) {
4767 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004768 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004769 }
4770
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004771 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4772 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4773
4774 llvm::BitstreamEntry Entry =
4775 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4776 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004777 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004778
Guy Benyei11169dd2012-12-18 14:30:41 +00004779 // Read the record.
4780 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4781 ReadSourceLocation(M, PPOffs.End));
4782 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004783 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004784 RecordData Record;
4785 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004786 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4787 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004788 switch (RecType) {
4789 case PPD_MACRO_EXPANSION: {
4790 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004791 IdentifierInfo *Name = nullptr;
4792 MacroDefinition *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004793 if (isBuiltin)
4794 Name = getLocalIdentifier(M, Record[1]);
4795 else {
4796 PreprocessedEntityID
4797 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4798 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4799 }
4800
4801 MacroExpansion *ME;
4802 if (isBuiltin)
4803 ME = new (PPRec) MacroExpansion(Name, Range);
4804 else
4805 ME = new (PPRec) MacroExpansion(Def, Range);
4806
4807 return ME;
4808 }
4809
4810 case PPD_MACRO_DEFINITION: {
4811 // Decode the identifier info and then check again; if the macro is
4812 // still defined and associated with the identifier,
4813 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4814 MacroDefinition *MD
4815 = new (PPRec) MacroDefinition(II, Range);
4816
4817 if (DeserializationListener)
4818 DeserializationListener->MacroDefinitionRead(PPID, MD);
4819
4820 return MD;
4821 }
4822
4823 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004824 const char *FullFileNameStart = Blob.data() + Record[0];
4825 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004826 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004827 if (!FullFileName.empty())
4828 File = PP.getFileManager().getFile(FullFileName);
4829
4830 // FIXME: Stable encoding
4831 InclusionDirective::InclusionKind Kind
4832 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4833 InclusionDirective *ID
4834 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004835 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004836 Record[1], Record[3],
4837 File,
4838 Range);
4839 return ID;
4840 }
4841 }
4842
4843 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4844}
4845
4846/// \brief \arg SLocMapI points at a chunk of a module that contains no
4847/// preprocessed entities or the entities it contains are not the ones we are
4848/// looking for. Find the next module that contains entities and return the ID
4849/// of the first entry.
4850PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4851 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4852 ++SLocMapI;
4853 for (GlobalSLocOffsetMapType::const_iterator
4854 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4855 ModuleFile &M = *SLocMapI->second;
4856 if (M.NumPreprocessedEntities)
4857 return M.BasePreprocessedEntityID;
4858 }
4859
4860 return getTotalNumPreprocessedEntities();
4861}
4862
4863namespace {
4864
4865template <unsigned PPEntityOffset::*PPLoc>
4866struct PPEntityComp {
4867 const ASTReader &Reader;
4868 ModuleFile &M;
4869
4870 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4871
4872 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4873 SourceLocation LHS = getLoc(L);
4874 SourceLocation RHS = getLoc(R);
4875 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4876 }
4877
4878 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4879 SourceLocation LHS = getLoc(L);
4880 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4881 }
4882
4883 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4884 SourceLocation RHS = getLoc(R);
4885 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4886 }
4887
4888 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4889 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4890 }
4891};
4892
4893}
4894
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004895PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4896 bool EndsAfter) const {
4897 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004898 return getTotalNumPreprocessedEntities();
4899
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004900 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4901 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004902 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4903 "Corrupted global sloc offset map");
4904
4905 if (SLocMapI->second->NumPreprocessedEntities == 0)
4906 return findNextPreprocessedEntity(SLocMapI);
4907
4908 ModuleFile &M = *SLocMapI->second;
4909 typedef const PPEntityOffset *pp_iterator;
4910 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4911 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4912
4913 size_t Count = M.NumPreprocessedEntities;
4914 size_t Half;
4915 pp_iterator First = pp_begin;
4916 pp_iterator PPI;
4917
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004918 if (EndsAfter) {
4919 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4920 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4921 } else {
4922 // Do a binary search manually instead of using std::lower_bound because
4923 // The end locations of entities may be unordered (when a macro expansion
4924 // is inside another macro argument), but for this case it is not important
4925 // whether we get the first macro expansion or its containing macro.
4926 while (Count > 0) {
4927 Half = Count / 2;
4928 PPI = First;
4929 std::advance(PPI, Half);
4930 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4931 Loc)) {
4932 First = PPI;
4933 ++First;
4934 Count = Count - Half - 1;
4935 } else
4936 Count = Half;
4937 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004938 }
4939
4940 if (PPI == pp_end)
4941 return findNextPreprocessedEntity(SLocMapI);
4942
4943 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4944}
4945
Guy Benyei11169dd2012-12-18 14:30:41 +00004946/// \brief Returns a pair of [Begin, End) indices of preallocated
4947/// preprocessed entities that \arg Range encompasses.
4948std::pair<unsigned, unsigned>
4949 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4950 if (Range.isInvalid())
4951 return std::make_pair(0,0);
4952 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4953
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004954 PreprocessedEntityID BeginID =
4955 findPreprocessedEntity(Range.getBegin(), false);
4956 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004957 return std::make_pair(BeginID, EndID);
4958}
4959
4960/// \brief Optionally returns true or false if the preallocated preprocessed
4961/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004962Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004963 FileID FID) {
4964 if (FID.isInvalid())
4965 return false;
4966
4967 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4968 ModuleFile &M = *PPInfo.first;
4969 unsigned LocalIndex = PPInfo.second;
4970 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4971
4972 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4973 if (Loc.isInvalid())
4974 return false;
4975
4976 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4977 return true;
4978 else
4979 return false;
4980}
4981
4982namespace {
4983 /// \brief Visitor used to search for information about a header file.
4984 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004985 const FileEntry *FE;
4986
David Blaikie05785d12013-02-20 22:23:23 +00004987 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004988
4989 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004990 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4991 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004992
4993 static bool visit(ModuleFile &M, void *UserData) {
4994 HeaderFileInfoVisitor *This
4995 = static_cast<HeaderFileInfoVisitor *>(UserData);
4996
Guy Benyei11169dd2012-12-18 14:30:41 +00004997 HeaderFileInfoLookupTable *Table
4998 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4999 if (!Table)
5000 return false;
5001
5002 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00005003 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005004 if (Pos == Table->end())
5005 return false;
5006
5007 This->HFI = *Pos;
5008 return true;
5009 }
5010
David Blaikie05785d12013-02-20 22:23:23 +00005011 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005012 };
5013}
5014
5015HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005016 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005017 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005018 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005019 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005020
5021 return HeaderFileInfo();
5022}
5023
5024void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5025 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005026 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005027 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5028 ModuleFile &F = *(*I);
5029 unsigned Idx = 0;
5030 DiagStates.clear();
5031 assert(!Diag.DiagStates.empty());
5032 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5033 while (Idx < F.PragmaDiagMappings.size()) {
5034 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5035 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5036 if (DiagStateID != 0) {
5037 Diag.DiagStatePoints.push_back(
5038 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5039 FullSourceLoc(Loc, SourceMgr)));
5040 continue;
5041 }
5042
5043 assert(DiagStateID == 0);
5044 // A new DiagState was created here.
5045 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5046 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5047 DiagStates.push_back(NewState);
5048 Diag.DiagStatePoints.push_back(
5049 DiagnosticsEngine::DiagStatePoint(NewState,
5050 FullSourceLoc(Loc, SourceMgr)));
5051 while (1) {
5052 assert(Idx < F.PragmaDiagMappings.size() &&
5053 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5054 if (Idx >= F.PragmaDiagMappings.size()) {
5055 break; // Something is messed up but at least avoid infinite loop in
5056 // release build.
5057 }
5058 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5059 if (DiagID == (unsigned)-1) {
5060 break; // no more diag/map pairs for this location.
5061 }
Alp Tokerc726c362014-06-10 09:31:37 +00005062 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5063 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5064 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005065 }
5066 }
5067 }
5068}
5069
5070/// \brief Get the correct cursor and offset for loading a type.
5071ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5072 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5073 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5074 ModuleFile *M = I->second;
5075 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5076}
5077
5078/// \brief Read and return the type with the given index..
5079///
5080/// The index is the type ID, shifted and minus the number of predefs. This
5081/// routine actually reads the record corresponding to the type at the given
5082/// location. It is a helper routine for GetType, which deals with reading type
5083/// IDs.
5084QualType ASTReader::readTypeRecord(unsigned Index) {
5085 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005086 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005087
5088 // Keep track of where we are in the stream, then jump back there
5089 // after reading this type.
5090 SavedStreamPosition SavedPosition(DeclsCursor);
5091
5092 ReadingKindTracker ReadingKind(Read_Type, *this);
5093
5094 // Note that we are loading a type record.
5095 Deserializing AType(this);
5096
5097 unsigned Idx = 0;
5098 DeclsCursor.JumpToBit(Loc.Offset);
5099 RecordData Record;
5100 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005101 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005102 case TYPE_EXT_QUAL: {
5103 if (Record.size() != 2) {
5104 Error("Incorrect encoding of extended qualifier type");
5105 return QualType();
5106 }
5107 QualType Base = readType(*Loc.F, Record, Idx);
5108 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5109 return Context.getQualifiedType(Base, Quals);
5110 }
5111
5112 case TYPE_COMPLEX: {
5113 if (Record.size() != 1) {
5114 Error("Incorrect encoding of complex type");
5115 return QualType();
5116 }
5117 QualType ElemType = readType(*Loc.F, Record, Idx);
5118 return Context.getComplexType(ElemType);
5119 }
5120
5121 case TYPE_POINTER: {
5122 if (Record.size() != 1) {
5123 Error("Incorrect encoding of pointer type");
5124 return QualType();
5125 }
5126 QualType PointeeType = readType(*Loc.F, Record, Idx);
5127 return Context.getPointerType(PointeeType);
5128 }
5129
Reid Kleckner8a365022013-06-24 17:51:48 +00005130 case TYPE_DECAYED: {
5131 if (Record.size() != 1) {
5132 Error("Incorrect encoding of decayed type");
5133 return QualType();
5134 }
5135 QualType OriginalType = readType(*Loc.F, Record, Idx);
5136 QualType DT = Context.getAdjustedParameterType(OriginalType);
5137 if (!isa<DecayedType>(DT))
5138 Error("Decayed type does not decay");
5139 return DT;
5140 }
5141
Reid Kleckner0503a872013-12-05 01:23:43 +00005142 case TYPE_ADJUSTED: {
5143 if (Record.size() != 2) {
5144 Error("Incorrect encoding of adjusted type");
5145 return QualType();
5146 }
5147 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5148 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5149 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5150 }
5151
Guy Benyei11169dd2012-12-18 14:30:41 +00005152 case TYPE_BLOCK_POINTER: {
5153 if (Record.size() != 1) {
5154 Error("Incorrect encoding of block pointer type");
5155 return QualType();
5156 }
5157 QualType PointeeType = readType(*Loc.F, Record, Idx);
5158 return Context.getBlockPointerType(PointeeType);
5159 }
5160
5161 case TYPE_LVALUE_REFERENCE: {
5162 if (Record.size() != 2) {
5163 Error("Incorrect encoding of lvalue reference type");
5164 return QualType();
5165 }
5166 QualType PointeeType = readType(*Loc.F, Record, Idx);
5167 return Context.getLValueReferenceType(PointeeType, Record[1]);
5168 }
5169
5170 case TYPE_RVALUE_REFERENCE: {
5171 if (Record.size() != 1) {
5172 Error("Incorrect encoding of rvalue reference type");
5173 return QualType();
5174 }
5175 QualType PointeeType = readType(*Loc.F, Record, Idx);
5176 return Context.getRValueReferenceType(PointeeType);
5177 }
5178
5179 case TYPE_MEMBER_POINTER: {
5180 if (Record.size() != 2) {
5181 Error("Incorrect encoding of member pointer type");
5182 return QualType();
5183 }
5184 QualType PointeeType = readType(*Loc.F, Record, Idx);
5185 QualType ClassType = readType(*Loc.F, Record, Idx);
5186 if (PointeeType.isNull() || ClassType.isNull())
5187 return QualType();
5188
5189 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5190 }
5191
5192 case TYPE_CONSTANT_ARRAY: {
5193 QualType ElementType = readType(*Loc.F, Record, Idx);
5194 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5195 unsigned IndexTypeQuals = Record[2];
5196 unsigned Idx = 3;
5197 llvm::APInt Size = ReadAPInt(Record, Idx);
5198 return Context.getConstantArrayType(ElementType, Size,
5199 ASM, IndexTypeQuals);
5200 }
5201
5202 case TYPE_INCOMPLETE_ARRAY: {
5203 QualType ElementType = readType(*Loc.F, Record, Idx);
5204 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5205 unsigned IndexTypeQuals = Record[2];
5206 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5207 }
5208
5209 case TYPE_VARIABLE_ARRAY: {
5210 QualType ElementType = readType(*Loc.F, Record, Idx);
5211 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5212 unsigned IndexTypeQuals = Record[2];
5213 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5214 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5215 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5216 ASM, IndexTypeQuals,
5217 SourceRange(LBLoc, RBLoc));
5218 }
5219
5220 case TYPE_VECTOR: {
5221 if (Record.size() != 3) {
5222 Error("incorrect encoding of vector type in AST file");
5223 return QualType();
5224 }
5225
5226 QualType ElementType = readType(*Loc.F, Record, Idx);
5227 unsigned NumElements = Record[1];
5228 unsigned VecKind = Record[2];
5229 return Context.getVectorType(ElementType, NumElements,
5230 (VectorType::VectorKind)VecKind);
5231 }
5232
5233 case TYPE_EXT_VECTOR: {
5234 if (Record.size() != 3) {
5235 Error("incorrect encoding of extended vector type in AST file");
5236 return QualType();
5237 }
5238
5239 QualType ElementType = readType(*Loc.F, Record, Idx);
5240 unsigned NumElements = Record[1];
5241 return Context.getExtVectorType(ElementType, NumElements);
5242 }
5243
5244 case TYPE_FUNCTION_NO_PROTO: {
5245 if (Record.size() != 6) {
5246 Error("incorrect encoding of no-proto function type");
5247 return QualType();
5248 }
5249 QualType ResultType = readType(*Loc.F, Record, Idx);
5250 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5251 (CallingConv)Record[4], Record[5]);
5252 return Context.getFunctionNoProtoType(ResultType, Info);
5253 }
5254
5255 case TYPE_FUNCTION_PROTO: {
5256 QualType ResultType = readType(*Loc.F, Record, Idx);
5257
5258 FunctionProtoType::ExtProtoInfo EPI;
5259 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5260 /*hasregparm*/ Record[2],
5261 /*regparm*/ Record[3],
5262 static_cast<CallingConv>(Record[4]),
5263 /*produces*/ Record[5]);
5264
5265 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005266
5267 EPI.Variadic = Record[Idx++];
5268 EPI.HasTrailingReturn = Record[Idx++];
5269 EPI.TypeQuals = Record[Idx++];
5270 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005271 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005272 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005273
5274 unsigned NumParams = Record[Idx++];
5275 SmallVector<QualType, 16> ParamTypes;
5276 for (unsigned I = 0; I != NumParams; ++I)
5277 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5278
Jordan Rose5c382722013-03-08 21:51:21 +00005279 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005280 }
5281
5282 case TYPE_UNRESOLVED_USING: {
5283 unsigned Idx = 0;
5284 return Context.getTypeDeclType(
5285 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5286 }
5287
5288 case TYPE_TYPEDEF: {
5289 if (Record.size() != 2) {
5290 Error("incorrect encoding of typedef type");
5291 return QualType();
5292 }
5293 unsigned Idx = 0;
5294 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5295 QualType Canonical = readType(*Loc.F, Record, Idx);
5296 if (!Canonical.isNull())
5297 Canonical = Context.getCanonicalType(Canonical);
5298 return Context.getTypedefType(Decl, Canonical);
5299 }
5300
5301 case TYPE_TYPEOF_EXPR:
5302 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5303
5304 case TYPE_TYPEOF: {
5305 if (Record.size() != 1) {
5306 Error("incorrect encoding of typeof(type) in AST file");
5307 return QualType();
5308 }
5309 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5310 return Context.getTypeOfType(UnderlyingType);
5311 }
5312
5313 case TYPE_DECLTYPE: {
5314 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5315 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5316 }
5317
5318 case TYPE_UNARY_TRANSFORM: {
5319 QualType BaseType = readType(*Loc.F, Record, Idx);
5320 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5321 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5322 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5323 }
5324
Richard Smith74aeef52013-04-26 16:15:35 +00005325 case TYPE_AUTO: {
5326 QualType Deduced = readType(*Loc.F, Record, Idx);
5327 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005328 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005329 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005330 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005331
5332 case TYPE_RECORD: {
5333 if (Record.size() != 2) {
5334 Error("incorrect encoding of record type");
5335 return QualType();
5336 }
5337 unsigned Idx = 0;
5338 bool IsDependent = Record[Idx++];
5339 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5340 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5341 QualType T = Context.getRecordType(RD);
5342 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5343 return T;
5344 }
5345
5346 case TYPE_ENUM: {
5347 if (Record.size() != 2) {
5348 Error("incorrect encoding of enum type");
5349 return QualType();
5350 }
5351 unsigned Idx = 0;
5352 bool IsDependent = Record[Idx++];
5353 QualType T
5354 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5355 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5356 return T;
5357 }
5358
5359 case TYPE_ATTRIBUTED: {
5360 if (Record.size() != 3) {
5361 Error("incorrect encoding of attributed type");
5362 return QualType();
5363 }
5364 QualType modifiedType = readType(*Loc.F, Record, Idx);
5365 QualType equivalentType = readType(*Loc.F, Record, Idx);
5366 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5367 return Context.getAttributedType(kind, modifiedType, equivalentType);
5368 }
5369
5370 case TYPE_PAREN: {
5371 if (Record.size() != 1) {
5372 Error("incorrect encoding of paren type");
5373 return QualType();
5374 }
5375 QualType InnerType = readType(*Loc.F, Record, Idx);
5376 return Context.getParenType(InnerType);
5377 }
5378
5379 case TYPE_PACK_EXPANSION: {
5380 if (Record.size() != 2) {
5381 Error("incorrect encoding of pack expansion type");
5382 return QualType();
5383 }
5384 QualType Pattern = readType(*Loc.F, Record, Idx);
5385 if (Pattern.isNull())
5386 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005387 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005388 if (Record[1])
5389 NumExpansions = Record[1] - 1;
5390 return Context.getPackExpansionType(Pattern, NumExpansions);
5391 }
5392
5393 case TYPE_ELABORATED: {
5394 unsigned Idx = 0;
5395 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5396 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5397 QualType NamedType = readType(*Loc.F, Record, Idx);
5398 return Context.getElaboratedType(Keyword, NNS, NamedType);
5399 }
5400
5401 case TYPE_OBJC_INTERFACE: {
5402 unsigned Idx = 0;
5403 ObjCInterfaceDecl *ItfD
5404 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5405 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5406 }
5407
5408 case TYPE_OBJC_OBJECT: {
5409 unsigned Idx = 0;
5410 QualType Base = readType(*Loc.F, Record, Idx);
5411 unsigned NumProtos = Record[Idx++];
5412 SmallVector<ObjCProtocolDecl*, 4> Protos;
5413 for (unsigned I = 0; I != NumProtos; ++I)
5414 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5415 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5416 }
5417
5418 case TYPE_OBJC_OBJECT_POINTER: {
5419 unsigned Idx = 0;
5420 QualType Pointee = readType(*Loc.F, Record, Idx);
5421 return Context.getObjCObjectPointerType(Pointee);
5422 }
5423
5424 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5425 unsigned Idx = 0;
5426 QualType Parm = readType(*Loc.F, Record, Idx);
5427 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005428 return Context.getSubstTemplateTypeParmType(
5429 cast<TemplateTypeParmType>(Parm),
5430 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005431 }
5432
5433 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5434 unsigned Idx = 0;
5435 QualType Parm = readType(*Loc.F, Record, Idx);
5436 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5437 return Context.getSubstTemplateTypeParmPackType(
5438 cast<TemplateTypeParmType>(Parm),
5439 ArgPack);
5440 }
5441
5442 case TYPE_INJECTED_CLASS_NAME: {
5443 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5444 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5445 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5446 // for AST reading, too much interdependencies.
Richard Smithf17fdbd2014-04-24 02:25:27 +00005447 const Type *T;
5448 if (const Type *Existing = D->getTypeForDecl())
5449 T = Existing;
5450 else if (auto *Prev = D->getPreviousDecl())
5451 T = Prev->getTypeForDecl();
5452 else
5453 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
5454 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005455 }
5456
5457 case TYPE_TEMPLATE_TYPE_PARM: {
5458 unsigned Idx = 0;
5459 unsigned Depth = Record[Idx++];
5460 unsigned Index = Record[Idx++];
5461 bool Pack = Record[Idx++];
5462 TemplateTypeParmDecl *D
5463 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5464 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5465 }
5466
5467 case TYPE_DEPENDENT_NAME: {
5468 unsigned Idx = 0;
5469 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5470 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5471 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5472 QualType Canon = readType(*Loc.F, Record, Idx);
5473 if (!Canon.isNull())
5474 Canon = Context.getCanonicalType(Canon);
5475 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5476 }
5477
5478 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5479 unsigned Idx = 0;
5480 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5481 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5482 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5483 unsigned NumArgs = Record[Idx++];
5484 SmallVector<TemplateArgument, 8> Args;
5485 Args.reserve(NumArgs);
5486 while (NumArgs--)
5487 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5488 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5489 Args.size(), Args.data());
5490 }
5491
5492 case TYPE_DEPENDENT_SIZED_ARRAY: {
5493 unsigned Idx = 0;
5494
5495 // ArrayType
5496 QualType ElementType = readType(*Loc.F, Record, Idx);
5497 ArrayType::ArraySizeModifier ASM
5498 = (ArrayType::ArraySizeModifier)Record[Idx++];
5499 unsigned IndexTypeQuals = Record[Idx++];
5500
5501 // DependentSizedArrayType
5502 Expr *NumElts = ReadExpr(*Loc.F);
5503 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5504
5505 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5506 IndexTypeQuals, Brackets);
5507 }
5508
5509 case TYPE_TEMPLATE_SPECIALIZATION: {
5510 unsigned Idx = 0;
5511 bool IsDependent = Record[Idx++];
5512 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5513 SmallVector<TemplateArgument, 8> Args;
5514 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5515 QualType Underlying = readType(*Loc.F, Record, Idx);
5516 QualType T;
5517 if (Underlying.isNull())
5518 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5519 Args.size());
5520 else
5521 T = Context.getTemplateSpecializationType(Name, Args.data(),
5522 Args.size(), Underlying);
5523 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5524 return T;
5525 }
5526
5527 case TYPE_ATOMIC: {
5528 if (Record.size() != 1) {
5529 Error("Incorrect encoding of atomic type");
5530 return QualType();
5531 }
5532 QualType ValueType = readType(*Loc.F, Record, Idx);
5533 return Context.getAtomicType(ValueType);
5534 }
5535 }
5536 llvm_unreachable("Invalid TypeCode!");
5537}
5538
Richard Smith564417a2014-03-20 21:47:22 +00005539void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5540 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005541 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005542 const RecordData &Record, unsigned &Idx) {
5543 ExceptionSpecificationType EST =
5544 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005545 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005546 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005547 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005548 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005549 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005550 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005551 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005552 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005553 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5554 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005555 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005556 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005557 }
5558}
5559
Guy Benyei11169dd2012-12-18 14:30:41 +00005560class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5561 ASTReader &Reader;
5562 ModuleFile &F;
5563 const ASTReader::RecordData &Record;
5564 unsigned &Idx;
5565
5566 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5567 unsigned &I) {
5568 return Reader.ReadSourceLocation(F, R, I);
5569 }
5570
5571 template<typename T>
5572 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5573 return Reader.ReadDeclAs<T>(F, Record, Idx);
5574 }
5575
5576public:
5577 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5578 const ASTReader::RecordData &Record, unsigned &Idx)
5579 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5580 { }
5581
5582 // We want compile-time assurance that we've enumerated all of
5583 // these, so unfortunately we have to declare them first, then
5584 // define them out-of-line.
5585#define ABSTRACT_TYPELOC(CLASS, PARENT)
5586#define TYPELOC(CLASS, PARENT) \
5587 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5588#include "clang/AST/TypeLocNodes.def"
5589
5590 void VisitFunctionTypeLoc(FunctionTypeLoc);
5591 void VisitArrayTypeLoc(ArrayTypeLoc);
5592};
5593
5594void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5595 // nothing to do
5596}
5597void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5598 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5599 if (TL.needsExtraLocalData()) {
5600 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5601 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5602 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5603 TL.setModeAttr(Record[Idx++]);
5604 }
5605}
5606void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5607 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5608}
5609void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5610 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5611}
Reid Kleckner8a365022013-06-24 17:51:48 +00005612void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5613 // nothing to do
5614}
Reid Kleckner0503a872013-12-05 01:23:43 +00005615void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5616 // nothing to do
5617}
Guy Benyei11169dd2012-12-18 14:30:41 +00005618void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5619 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5620}
5621void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5622 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5623}
5624void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5625 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5626}
5627void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5628 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5629 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5630}
5631void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5632 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5633 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5634 if (Record[Idx++])
5635 TL.setSizeExpr(Reader.ReadExpr(F));
5636 else
Craig Toppera13603a2014-05-22 05:54:18 +00005637 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005638}
5639void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5640 VisitArrayTypeLoc(TL);
5641}
5642void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5643 VisitArrayTypeLoc(TL);
5644}
5645void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5646 VisitArrayTypeLoc(TL);
5647}
5648void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5649 DependentSizedArrayTypeLoc TL) {
5650 VisitArrayTypeLoc(TL);
5651}
5652void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5653 DependentSizedExtVectorTypeLoc TL) {
5654 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5655}
5656void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5657 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5658}
5659void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5660 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5661}
5662void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5663 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5664 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5665 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5666 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005667 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5668 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005669 }
5670}
5671void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5672 VisitFunctionTypeLoc(TL);
5673}
5674void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5675 VisitFunctionTypeLoc(TL);
5676}
5677void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5678 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5679}
5680void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5681 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5682}
5683void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5684 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5685 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5686 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5687}
5688void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5689 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5690 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5691 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5692 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5693}
5694void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5695 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5696}
5697void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5698 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5699 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5700 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5701 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5702}
5703void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5704 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5705}
5706void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5707 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5708}
5709void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5710 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5711}
5712void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5713 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5714 if (TL.hasAttrOperand()) {
5715 SourceRange range;
5716 range.setBegin(ReadSourceLocation(Record, Idx));
5717 range.setEnd(ReadSourceLocation(Record, Idx));
5718 TL.setAttrOperandParensRange(range);
5719 }
5720 if (TL.hasAttrExprOperand()) {
5721 if (Record[Idx++])
5722 TL.setAttrExprOperand(Reader.ReadExpr(F));
5723 else
Craig Toppera13603a2014-05-22 05:54:18 +00005724 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005725 } else if (TL.hasAttrEnumOperand())
5726 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5727}
5728void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5729 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5730}
5731void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5732 SubstTemplateTypeParmTypeLoc TL) {
5733 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5734}
5735void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5736 SubstTemplateTypeParmPackTypeLoc TL) {
5737 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5738}
5739void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5740 TemplateSpecializationTypeLoc TL) {
5741 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5742 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5743 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5744 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5745 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5746 TL.setArgLocInfo(i,
5747 Reader.GetTemplateArgumentLocInfo(F,
5748 TL.getTypePtr()->getArg(i).getKind(),
5749 Record, Idx));
5750}
5751void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5752 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5753 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5754}
5755void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5756 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5757 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5758}
5759void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5760 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5761}
5762void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5763 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5764 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5765 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5766}
5767void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5768 DependentTemplateSpecializationTypeLoc TL) {
5769 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5770 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5771 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5772 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5773 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5774 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5775 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5776 TL.setArgLocInfo(I,
5777 Reader.GetTemplateArgumentLocInfo(F,
5778 TL.getTypePtr()->getArg(I).getKind(),
5779 Record, Idx));
5780}
5781void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5782 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5783}
5784void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5785 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5786}
5787void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5788 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5789 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5790 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5791 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5792 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5793}
5794void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5795 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5796}
5797void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5798 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5799 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5800 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5801}
5802
5803TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5804 const RecordData &Record,
5805 unsigned &Idx) {
5806 QualType InfoTy = readType(F, Record, Idx);
5807 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005808 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005809
5810 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5811 TypeLocReader TLR(*this, F, Record, Idx);
5812 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5813 TLR.Visit(TL);
5814 return TInfo;
5815}
5816
5817QualType ASTReader::GetType(TypeID ID) {
5818 unsigned FastQuals = ID & Qualifiers::FastMask;
5819 unsigned Index = ID >> Qualifiers::FastWidth;
5820
5821 if (Index < NUM_PREDEF_TYPE_IDS) {
5822 QualType T;
5823 switch ((PredefinedTypeIDs)Index) {
5824 case PREDEF_TYPE_NULL_ID: return QualType();
5825 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5826 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5827
5828 case PREDEF_TYPE_CHAR_U_ID:
5829 case PREDEF_TYPE_CHAR_S_ID:
5830 // FIXME: Check that the signedness of CharTy is correct!
5831 T = Context.CharTy;
5832 break;
5833
5834 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5835 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5836 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5837 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5838 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5839 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5840 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5841 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5842 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5843 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5844 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5845 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5846 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5847 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5848 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5849 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5850 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5851 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5852 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5853 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5854 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5855 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5856 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5857 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5858 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5859 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5860 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5861 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005862 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5863 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5864 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5865 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5866 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5867 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005868 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005869 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005870 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5871
5872 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5873 T = Context.getAutoRRefDeductType();
5874 break;
5875
5876 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5877 T = Context.ARCUnbridgedCastTy;
5878 break;
5879
5880 case PREDEF_TYPE_VA_LIST_TAG:
5881 T = Context.getVaListTagType();
5882 break;
5883
5884 case PREDEF_TYPE_BUILTIN_FN:
5885 T = Context.BuiltinFnTy;
5886 break;
5887 }
5888
5889 assert(!T.isNull() && "Unknown predefined type");
5890 return T.withFastQualifiers(FastQuals);
5891 }
5892
5893 Index -= NUM_PREDEF_TYPE_IDS;
5894 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5895 if (TypesLoaded[Index].isNull()) {
5896 TypesLoaded[Index] = readTypeRecord(Index);
5897 if (TypesLoaded[Index].isNull())
5898 return QualType();
5899
5900 TypesLoaded[Index]->setFromAST();
5901 if (DeserializationListener)
5902 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5903 TypesLoaded[Index]);
5904 }
5905
5906 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5907}
5908
5909QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5910 return GetType(getGlobalTypeID(F, LocalID));
5911}
5912
5913serialization::TypeID
5914ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5915 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5916 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5917
5918 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5919 return LocalID;
5920
5921 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5922 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5923 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5924
5925 unsigned GlobalIndex = LocalIndex + I->second;
5926 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5927}
5928
5929TemplateArgumentLocInfo
5930ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5931 TemplateArgument::ArgKind Kind,
5932 const RecordData &Record,
5933 unsigned &Index) {
5934 switch (Kind) {
5935 case TemplateArgument::Expression:
5936 return ReadExpr(F);
5937 case TemplateArgument::Type:
5938 return GetTypeSourceInfo(F, Record, Index);
5939 case TemplateArgument::Template: {
5940 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5941 Index);
5942 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5943 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5944 SourceLocation());
5945 }
5946 case TemplateArgument::TemplateExpansion: {
5947 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5948 Index);
5949 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5950 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5951 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5952 EllipsisLoc);
5953 }
5954 case TemplateArgument::Null:
5955 case TemplateArgument::Integral:
5956 case TemplateArgument::Declaration:
5957 case TemplateArgument::NullPtr:
5958 case TemplateArgument::Pack:
5959 // FIXME: Is this right?
5960 return TemplateArgumentLocInfo();
5961 }
5962 llvm_unreachable("unexpected template argument loc");
5963}
5964
5965TemplateArgumentLoc
5966ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5967 const RecordData &Record, unsigned &Index) {
5968 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5969
5970 if (Arg.getKind() == TemplateArgument::Expression) {
5971 if (Record[Index++]) // bool InfoHasSameExpr.
5972 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5973 }
5974 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5975 Record, Index));
5976}
5977
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005978const ASTTemplateArgumentListInfo*
5979ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5980 const RecordData &Record,
5981 unsigned &Index) {
5982 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5983 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5984 unsigned NumArgsAsWritten = Record[Index++];
5985 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5986 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5987 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5988 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5989}
5990
Guy Benyei11169dd2012-12-18 14:30:41 +00005991Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5992 return GetDecl(ID);
5993}
5994
Richard Smith053f6c62014-05-16 23:01:30 +00005995void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005996 if (NumCurrentElementsDeserializing) {
5997 // We arrange to not care about the complete redeclaration chain while we're
5998 // deserializing. Just remember that the AST has marked this one as complete
5999 // but that it's not actually complete yet, so we know we still need to
6000 // complete it later.
6001 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6002 return;
6003 }
6004
Richard Smith053f6c62014-05-16 23:01:30 +00006005 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6006
6007 // Recursively ensure that the decl context itself is complete
6008 // (in particular, this matters if the decl context is a namespace).
6009 //
6010 // FIXME: This should be performed by lookup instead of here.
6011 cast<Decl>(DC)->getMostRecentDecl();
6012
6013 // If this is a named declaration, complete it by looking it up
6014 // within its context.
6015 //
6016 // FIXME: We don't currently handle the cases where we can't do this;
6017 // merging a class definition that contains unnamed entities should merge
6018 // those entities. Likewise, merging a function definition should merge
6019 // all mergeable entities within it.
6020 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6021 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6022 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
6023 auto *II = Name.getAsIdentifierInfo();
6024 if (isa<TranslationUnitDecl>(DC) && II) {
6025 // Outside of C++, we don't have a lookup table for the TU, so update
6026 // the identifier instead. In C++, either way should work fine.
6027 if (II->isOutOfDate())
6028 updateOutOfDateIdentifier(*II);
6029 } else
6030 DC->lookup(Name);
6031 }
6032 }
6033}
6034
Richard Smithcd45dbc2014-04-19 03:48:30 +00006035uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6036 const RecordData &Record,
6037 unsigned &Idx) {
6038 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6039 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006040 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006041 }
6042
Guy Benyei11169dd2012-12-18 14:30:41 +00006043 unsigned LocalID = Record[Idx++];
6044 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6045}
6046
6047CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6048 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006049 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006050 SavedStreamPosition SavedPosition(Cursor);
6051 Cursor.JumpToBit(Loc.Offset);
6052 ReadingKindTracker ReadingKind(Read_Decl, *this);
6053 RecordData Record;
6054 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006055 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006056 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006057 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006058 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006059 }
6060
6061 unsigned Idx = 0;
6062 unsigned NumBases = Record[Idx++];
6063 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6064 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6065 for (unsigned I = 0; I != NumBases; ++I)
6066 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6067 return Bases;
6068}
6069
6070serialization::DeclID
6071ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6072 if (LocalID < NUM_PREDEF_DECL_IDS)
6073 return LocalID;
6074
6075 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6076 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6077 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6078
6079 return LocalID + I->second;
6080}
6081
6082bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6083 ModuleFile &M) const {
6084 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6085 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6086 return &M == I->second;
6087}
6088
Douglas Gregor9f782892013-01-21 15:25:38 +00006089ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006090 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006091 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006092 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6093 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6094 return I->second;
6095}
6096
6097SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6098 if (ID < NUM_PREDEF_DECL_IDS)
6099 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006100
Guy Benyei11169dd2012-12-18 14:30:41 +00006101 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6102
6103 if (Index > DeclsLoaded.size()) {
6104 Error("declaration ID out-of-range for AST file");
6105 return SourceLocation();
6106 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006107
Guy Benyei11169dd2012-12-18 14:30:41 +00006108 if (Decl *D = DeclsLoaded[Index])
6109 return D->getLocation();
6110
6111 unsigned RawLocation = 0;
6112 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6113 return ReadSourceLocation(*Rec.F, RawLocation);
6114}
6115
Richard Smithcd45dbc2014-04-19 03:48:30 +00006116Decl *ASTReader::GetExistingDecl(DeclID ID) {
6117 if (ID < NUM_PREDEF_DECL_IDS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006118 switch ((PredefinedDeclIDs)ID) {
6119 case PREDEF_DECL_NULL_ID:
Craig Toppera13603a2014-05-22 05:54:18 +00006120 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006121
Guy Benyei11169dd2012-12-18 14:30:41 +00006122 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6123 return Context.getTranslationUnitDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006124
Guy Benyei11169dd2012-12-18 14:30:41 +00006125 case PREDEF_DECL_OBJC_ID_ID:
6126 return Context.getObjCIdDecl();
6127
6128 case PREDEF_DECL_OBJC_SEL_ID:
6129 return Context.getObjCSelDecl();
6130
6131 case PREDEF_DECL_OBJC_CLASS_ID:
6132 return Context.getObjCClassDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006133
Guy Benyei11169dd2012-12-18 14:30:41 +00006134 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6135 return Context.getObjCProtocolDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006136
Guy Benyei11169dd2012-12-18 14:30:41 +00006137 case PREDEF_DECL_INT_128_ID:
6138 return Context.getInt128Decl();
6139
6140 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6141 return Context.getUInt128Decl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006142
Guy Benyei11169dd2012-12-18 14:30:41 +00006143 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6144 return Context.getObjCInstanceTypeDecl();
6145
6146 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6147 return Context.getBuiltinVaListDecl();
6148 }
6149 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006150
Guy Benyei11169dd2012-12-18 14:30:41 +00006151 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6152
6153 if (Index >= DeclsLoaded.size()) {
6154 assert(0 && "declaration ID out-of-range for AST file");
6155 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006156 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006157 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006158
6159 return DeclsLoaded[Index];
6160}
6161
6162Decl *ASTReader::GetDecl(DeclID ID) {
6163 if (ID < NUM_PREDEF_DECL_IDS)
6164 return GetExistingDecl(ID);
6165
6166 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6167
6168 if (Index >= DeclsLoaded.size()) {
6169 assert(0 && "declaration ID out-of-range for AST file");
6170 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006171 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006172 }
6173
Guy Benyei11169dd2012-12-18 14:30:41 +00006174 if (!DeclsLoaded[Index]) {
6175 ReadDeclRecord(ID);
6176 if (DeserializationListener)
6177 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6178 }
6179
6180 return DeclsLoaded[Index];
6181}
6182
6183DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6184 DeclID GlobalID) {
6185 if (GlobalID < NUM_PREDEF_DECL_IDS)
6186 return GlobalID;
6187
6188 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6189 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6190 ModuleFile *Owner = I->second;
6191
6192 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6193 = M.GlobalToLocalDeclIDs.find(Owner);
6194 if (Pos == M.GlobalToLocalDeclIDs.end())
6195 return 0;
6196
6197 return GlobalID - Owner->BaseDeclID + Pos->second;
6198}
6199
6200serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6201 const RecordData &Record,
6202 unsigned &Idx) {
6203 if (Idx >= Record.size()) {
6204 Error("Corrupted AST file");
6205 return 0;
6206 }
6207
6208 return getGlobalDeclID(F, Record[Idx++]);
6209}
6210
6211/// \brief Resolve the offset of a statement into a statement.
6212///
6213/// This operation will read a new statement from the external
6214/// source each time it is called, and is meant to be used via a
6215/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6216Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6217 // Switch case IDs are per Decl.
6218 ClearSwitchCaseIDs();
6219
6220 // Offset here is a global offset across the entire chain.
6221 RecordLocation Loc = getLocalBitOffset(Offset);
6222 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6223 return ReadStmtFromStream(*Loc.F);
6224}
6225
6226namespace {
6227 class FindExternalLexicalDeclsVisitor {
6228 ASTReader &Reader;
6229 const DeclContext *DC;
6230 bool (*isKindWeWant)(Decl::Kind);
6231
6232 SmallVectorImpl<Decl*> &Decls;
6233 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6234
6235 public:
6236 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6237 bool (*isKindWeWant)(Decl::Kind),
6238 SmallVectorImpl<Decl*> &Decls)
6239 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6240 {
6241 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6242 PredefsVisited[I] = false;
6243 }
6244
6245 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6246 if (Preorder)
6247 return false;
6248
6249 FindExternalLexicalDeclsVisitor *This
6250 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6251
6252 ModuleFile::DeclContextInfosMap::iterator Info
6253 = M.DeclContextInfos.find(This->DC);
6254 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6255 return false;
6256
6257 // Load all of the declaration IDs
6258 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6259 *IDE = ID + Info->second.NumLexicalDecls;
6260 ID != IDE; ++ID) {
6261 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6262 continue;
6263
6264 // Don't add predefined declarations to the lexical context more
6265 // than once.
6266 if (ID->second < NUM_PREDEF_DECL_IDS) {
6267 if (This->PredefsVisited[ID->second])
6268 continue;
6269
6270 This->PredefsVisited[ID->second] = true;
6271 }
6272
6273 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6274 if (!This->DC->isDeclInLexicalTraversal(D))
6275 This->Decls.push_back(D);
6276 }
6277 }
6278
6279 return false;
6280 }
6281 };
6282}
6283
6284ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6285 bool (*isKindWeWant)(Decl::Kind),
6286 SmallVectorImpl<Decl*> &Decls) {
6287 // There might be lexical decls in multiple modules, for the TU at
6288 // least. Walk all of the modules in the order they were loaded.
6289 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6290 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6291 ++NumLexicalDeclContextsRead;
6292 return ELR_Success;
6293}
6294
6295namespace {
6296
6297class DeclIDComp {
6298 ASTReader &Reader;
6299 ModuleFile &Mod;
6300
6301public:
6302 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6303
6304 bool operator()(LocalDeclID L, LocalDeclID R) const {
6305 SourceLocation LHS = getLocation(L);
6306 SourceLocation RHS = getLocation(R);
6307 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6308 }
6309
6310 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6311 SourceLocation RHS = getLocation(R);
6312 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6313 }
6314
6315 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6316 SourceLocation LHS = getLocation(L);
6317 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6318 }
6319
6320 SourceLocation getLocation(LocalDeclID ID) const {
6321 return Reader.getSourceManager().getFileLoc(
6322 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6323 }
6324};
6325
6326}
6327
6328void ASTReader::FindFileRegionDecls(FileID File,
6329 unsigned Offset, unsigned Length,
6330 SmallVectorImpl<Decl *> &Decls) {
6331 SourceManager &SM = getSourceManager();
6332
6333 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6334 if (I == FileDeclIDs.end())
6335 return;
6336
6337 FileDeclsInfo &DInfo = I->second;
6338 if (DInfo.Decls.empty())
6339 return;
6340
6341 SourceLocation
6342 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6343 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6344
6345 DeclIDComp DIDComp(*this, *DInfo.Mod);
6346 ArrayRef<serialization::LocalDeclID>::iterator
6347 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6348 BeginLoc, DIDComp);
6349 if (BeginIt != DInfo.Decls.begin())
6350 --BeginIt;
6351
6352 // If we are pointing at a top-level decl inside an objc container, we need
6353 // to backtrack until we find it otherwise we will fail to report that the
6354 // region overlaps with an objc container.
6355 while (BeginIt != DInfo.Decls.begin() &&
6356 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6357 ->isTopLevelDeclInObjCContainer())
6358 --BeginIt;
6359
6360 ArrayRef<serialization::LocalDeclID>::iterator
6361 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6362 EndLoc, DIDComp);
6363 if (EndIt != DInfo.Decls.end())
6364 ++EndIt;
6365
6366 for (ArrayRef<serialization::LocalDeclID>::iterator
6367 DIt = BeginIt; DIt != EndIt; ++DIt)
6368 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6369}
6370
6371namespace {
6372 /// \brief ModuleFile visitor used to perform name lookup into a
6373 /// declaration context.
6374 class DeclContextNameLookupVisitor {
6375 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006376 SmallVectorImpl<const DeclContext *> &Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006377 DeclarationName Name;
6378 SmallVectorImpl<NamedDecl *> &Decls;
6379
6380 public:
6381 DeclContextNameLookupVisitor(ASTReader &Reader,
6382 SmallVectorImpl<const DeclContext *> &Contexts,
6383 DeclarationName Name,
6384 SmallVectorImpl<NamedDecl *> &Decls)
6385 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
6386
6387 static bool visit(ModuleFile &M, void *UserData) {
6388 DeclContextNameLookupVisitor *This
6389 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6390
6391 // Check whether we have any visible declaration information for
6392 // this context in this module.
6393 ModuleFile::DeclContextInfosMap::iterator Info;
6394 bool FoundInfo = false;
6395 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6396 Info = M.DeclContextInfos.find(This->Contexts[I]);
6397 if (Info != M.DeclContextInfos.end() &&
6398 Info->second.NameLookupTableData) {
6399 FoundInfo = true;
6400 break;
6401 }
6402 }
6403
6404 if (!FoundInfo)
6405 return false;
6406
6407 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006408 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006409 Info->second.NameLookupTableData;
6410 ASTDeclContextNameLookupTable::iterator Pos
6411 = LookupTable->find(This->Name);
6412 if (Pos == LookupTable->end())
6413 return false;
6414
6415 bool FoundAnything = false;
6416 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6417 for (; Data.first != Data.second; ++Data.first) {
6418 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6419 if (!ND)
6420 continue;
6421
6422 if (ND->getDeclName() != This->Name) {
6423 // A name might be null because the decl's redeclarable part is
6424 // currently read before reading its name. The lookup is triggered by
6425 // building that decl (likely indirectly), and so it is later in the
6426 // sense of "already existing" and can be ignored here.
6427 continue;
6428 }
6429
6430 // Record this declaration.
6431 FoundAnything = true;
6432 This->Decls.push_back(ND);
6433 }
6434
6435 return FoundAnything;
6436 }
6437 };
6438}
6439
Douglas Gregor9f782892013-01-21 15:25:38 +00006440/// \brief Retrieve the "definitive" module file for the definition of the
6441/// given declaration context, if there is one.
6442///
6443/// The "definitive" module file is the only place where we need to look to
6444/// find information about the declarations within the given declaration
6445/// context. For example, C++ and Objective-C classes, C structs/unions, and
6446/// Objective-C protocols, categories, and extensions are all defined in a
6447/// single place in the source code, so they have definitive module files
6448/// associated with them. C++ namespaces, on the other hand, can have
6449/// definitions in multiple different module files.
6450///
6451/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6452/// NDEBUG checking.
6453static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6454 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006455 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6456 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006457
Craig Toppera13603a2014-05-22 05:54:18 +00006458 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006459}
6460
Richard Smith9ce12e32013-02-07 03:30:24 +00006461bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006462ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6463 DeclarationName Name) {
6464 assert(DC->hasExternalVisibleStorage() &&
6465 "DeclContext has no visible decls in storage");
6466 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006467 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006468
6469 SmallVector<NamedDecl *, 64> Decls;
6470
6471 // Compute the declaration contexts we need to look into. Multiple such
6472 // declaration contexts occur when two declaration contexts from disjoint
6473 // modules get merged, e.g., when two namespaces with the same name are
6474 // independently defined in separate modules.
6475 SmallVector<const DeclContext *, 2> Contexts;
6476 Contexts.push_back(DC);
6477
6478 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006479 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006480 if (Merged != MergedDecls.end()) {
6481 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6482 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6483 }
6484 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006485 if (isa<CXXRecordDecl>(DC)) {
6486 auto Merged = MergedLookups.find(DC);
6487 if (Merged != MergedLookups.end())
6488 Contexts.insert(Contexts.end(), Merged->second.begin(),
6489 Merged->second.end());
6490 }
6491
Guy Benyei11169dd2012-12-18 14:30:41 +00006492 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor9f782892013-01-21 15:25:38 +00006493
6494 // If we can definitively determine which module file to look into,
6495 // only look there. Otherwise, look in all module files.
6496 ModuleFile *Definitive;
6497 if (Contexts.size() == 1 &&
6498 (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
6499 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6500 } else {
6501 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6502 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006503 ++NumVisibleDeclContextsRead;
6504 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006505 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006506}
6507
6508namespace {
6509 /// \brief ModuleFile visitor used to retrieve all visible names in a
6510 /// declaration context.
6511 class DeclContextAllNamesVisitor {
6512 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006513 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006514 DeclsMap &Decls;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006515 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006516
6517 public:
6518 DeclContextAllNamesVisitor(ASTReader &Reader,
6519 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006520 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006521 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006522
6523 static bool visit(ModuleFile &M, void *UserData) {
6524 DeclContextAllNamesVisitor *This
6525 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6526
6527 // Check whether we have any visible declaration information for
6528 // this context in this module.
6529 ModuleFile::DeclContextInfosMap::iterator Info;
6530 bool FoundInfo = false;
6531 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6532 Info = M.DeclContextInfos.find(This->Contexts[I]);
6533 if (Info != M.DeclContextInfos.end() &&
6534 Info->second.NameLookupTableData) {
6535 FoundInfo = true;
6536 break;
6537 }
6538 }
6539
6540 if (!FoundInfo)
6541 return false;
6542
Richard Smith52e3fba2014-03-11 07:17:35 +00006543 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006544 Info->second.NameLookupTableData;
6545 bool FoundAnything = false;
6546 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006547 I = LookupTable->data_begin(), E = LookupTable->data_end();
6548 I != E;
6549 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006550 ASTDeclContextNameLookupTrait::data_type Data = *I;
6551 for (; Data.first != Data.second; ++Data.first) {
6552 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6553 *Data.first);
6554 if (!ND)
6555 continue;
6556
6557 // Record this declaration.
6558 FoundAnything = true;
6559 This->Decls[ND->getDeclName()].push_back(ND);
6560 }
6561 }
6562
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006563 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006564 }
6565 };
6566}
6567
6568void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6569 if (!DC->hasExternalVisibleStorage())
6570 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006571 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006572
6573 // Compute the declaration contexts we need to look into. Multiple such
6574 // declaration contexts occur when two declaration contexts from disjoint
6575 // modules get merged, e.g., when two namespaces with the same name are
6576 // independently defined in separate modules.
6577 SmallVector<const DeclContext *, 2> Contexts;
6578 Contexts.push_back(DC);
6579
6580 if (DC->isNamespace()) {
6581 MergedDeclsMap::iterator Merged
6582 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6583 if (Merged != MergedDecls.end()) {
6584 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6585 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6586 }
6587 }
6588
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006589 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6590 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006591 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6592 ++NumVisibleDeclContextsRead;
6593
Craig Topper79be4cd2013-07-05 04:33:53 +00006594 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006595 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6596 }
6597 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6598}
6599
6600/// \brief Under non-PCH compilation the consumer receives the objc methods
6601/// before receiving the implementation, and codegen depends on this.
6602/// We simulate this by deserializing and passing to consumer the methods of the
6603/// implementation before passing the deserialized implementation decl.
6604static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6605 ASTConsumer *Consumer) {
6606 assert(ImplD && Consumer);
6607
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006608 for (auto *I : ImplD->methods())
6609 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006610
6611 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6612}
6613
6614void ASTReader::PassInterestingDeclsToConsumer() {
6615 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006616
6617 if (PassingDeclsToConsumer)
6618 return;
6619
6620 // Guard variable to avoid recursively redoing the process of passing
6621 // decls to consumer.
6622 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6623 true);
6624
Guy Benyei11169dd2012-12-18 14:30:41 +00006625 while (!InterestingDecls.empty()) {
6626 Decl *D = InterestingDecls.front();
6627 InterestingDecls.pop_front();
6628
6629 PassInterestingDeclToConsumer(D);
6630 }
6631}
6632
6633void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6634 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6635 PassObjCImplDeclToConsumer(ImplD, Consumer);
6636 else
6637 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6638}
6639
6640void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6641 this->Consumer = Consumer;
6642
6643 if (!Consumer)
6644 return;
6645
Ben Langmuir332aafe2014-01-31 01:06:56 +00006646 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006647 // Force deserialization of this decl, which will cause it to be queued for
6648 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006649 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006650 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006651 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006652
6653 PassInterestingDeclsToConsumer();
6654}
6655
6656void ASTReader::PrintStats() {
6657 std::fprintf(stderr, "*** AST File Statistics:\n");
6658
6659 unsigned NumTypesLoaded
6660 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6661 QualType());
6662 unsigned NumDeclsLoaded
6663 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006664 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006665 unsigned NumIdentifiersLoaded
6666 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6667 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006668 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006669 unsigned NumMacrosLoaded
6670 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6671 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006672 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006673 unsigned NumSelectorsLoaded
6674 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6675 SelectorsLoaded.end(),
6676 Selector());
6677
6678 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6679 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6680 NumSLocEntriesRead, TotalNumSLocEntries,
6681 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6682 if (!TypesLoaded.empty())
6683 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6684 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6685 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6686 if (!DeclsLoaded.empty())
6687 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6688 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6689 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6690 if (!IdentifiersLoaded.empty())
6691 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6692 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6693 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6694 if (!MacrosLoaded.empty())
6695 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6696 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6697 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6698 if (!SelectorsLoaded.empty())
6699 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6700 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6701 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6702 if (TotalNumStatements)
6703 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6704 NumStatementsRead, TotalNumStatements,
6705 ((float)NumStatementsRead/TotalNumStatements * 100));
6706 if (TotalNumMacros)
6707 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6708 NumMacrosRead, TotalNumMacros,
6709 ((float)NumMacrosRead/TotalNumMacros * 100));
6710 if (TotalLexicalDeclContexts)
6711 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6712 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6713 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6714 * 100));
6715 if (TotalVisibleDeclContexts)
6716 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6717 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6718 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6719 * 100));
6720 if (TotalNumMethodPoolEntries) {
6721 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6722 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6723 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6724 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006725 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006726 if (NumMethodPoolLookups) {
6727 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6728 NumMethodPoolHits, NumMethodPoolLookups,
6729 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6730 }
6731 if (NumMethodPoolTableLookups) {
6732 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6733 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6734 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6735 * 100.0));
6736 }
6737
Douglas Gregor00a50f72013-01-25 00:38:33 +00006738 if (NumIdentifierLookupHits) {
6739 std::fprintf(stderr,
6740 " %u / %u identifier table lookups succeeded (%f%%)\n",
6741 NumIdentifierLookupHits, NumIdentifierLookups,
6742 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6743 }
6744
Douglas Gregore060e572013-01-25 01:03:03 +00006745 if (GlobalIndex) {
6746 std::fprintf(stderr, "\n");
6747 GlobalIndex->printStats();
6748 }
6749
Guy Benyei11169dd2012-12-18 14:30:41 +00006750 std::fprintf(stderr, "\n");
6751 dump();
6752 std::fprintf(stderr, "\n");
6753}
6754
6755template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6756static void
6757dumpModuleIDMap(StringRef Name,
6758 const ContinuousRangeMap<Key, ModuleFile *,
6759 InitialCapacity> &Map) {
6760 if (Map.begin() == Map.end())
6761 return;
6762
6763 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6764 llvm::errs() << Name << ":\n";
6765 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6766 I != IEnd; ++I) {
6767 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6768 << "\n";
6769 }
6770}
6771
6772void ASTReader::dump() {
6773 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6774 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6775 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6776 dumpModuleIDMap("Global type map", GlobalTypeMap);
6777 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6778 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6779 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6780 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6781 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6782 dumpModuleIDMap("Global preprocessed entity map",
6783 GlobalPreprocessedEntityMap);
6784
6785 llvm::errs() << "\n*** PCH/Modules Loaded:";
6786 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6787 MEnd = ModuleMgr.end();
6788 M != MEnd; ++M)
6789 (*M)->dump();
6790}
6791
6792/// Return the amount of memory used by memory buffers, breaking down
6793/// by heap-backed versus mmap'ed memory.
6794void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6795 for (ModuleConstIterator I = ModuleMgr.begin(),
6796 E = ModuleMgr.end(); I != E; ++I) {
6797 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6798 size_t bytes = buf->getBufferSize();
6799 switch (buf->getBufferKind()) {
6800 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6801 sizes.malloc_bytes += bytes;
6802 break;
6803 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6804 sizes.mmap_bytes += bytes;
6805 break;
6806 }
6807 }
6808 }
6809}
6810
6811void ASTReader::InitializeSema(Sema &S) {
6812 SemaObj = &S;
6813 S.addExternalSource(this);
6814
6815 // Makes sure any declarations that were deserialized "too early"
6816 // still get added to the identifier's declaration chains.
6817 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00006818 pushExternalDeclIntoScope(PreloadedDecls[I],
6819 PreloadedDecls[I]->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006820 }
6821 PreloadedDecls.clear();
6822
Richard Smith3d8e97e2013-10-18 06:54:39 +00006823 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006824 if (!FPPragmaOptions.empty()) {
6825 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6826 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6827 }
6828
Richard Smith3d8e97e2013-10-18 06:54:39 +00006829 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006830 if (!OpenCLExtensions.empty()) {
6831 unsigned I = 0;
6832#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6833#include "clang/Basic/OpenCLExtensions.def"
6834
6835 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6836 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006837
6838 UpdateSema();
6839}
6840
6841void ASTReader::UpdateSema() {
6842 assert(SemaObj && "no Sema to update");
6843
6844 // Load the offsets of the declarations that Sema references.
6845 // They will be lazily deserialized when needed.
6846 if (!SemaDeclRefs.empty()) {
6847 assert(SemaDeclRefs.size() % 2 == 0);
6848 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6849 if (!SemaObj->StdNamespace)
6850 SemaObj->StdNamespace = SemaDeclRefs[I];
6851 if (!SemaObj->StdBadAlloc)
6852 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6853 }
6854 SemaDeclRefs.clear();
6855 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006856
6857 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6858 // encountered the pragma in the source.
6859 if(OptimizeOffPragmaLocation.isValid())
6860 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006861}
6862
6863IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6864 // Note that we are loading an identifier.
6865 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006866 StringRef Name(NameStart, NameEnd - NameStart);
6867
6868 // If there is a global index, look there first to determine which modules
6869 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006870 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00006871 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00006872 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006873 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6874 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006875 }
6876 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006877 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006878 NumIdentifierLookups,
6879 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006880 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006881 IdentifierInfo *II = Visitor.getIdentifierInfo();
6882 markIdentifierUpToDate(II);
6883 return II;
6884}
6885
6886namespace clang {
6887 /// \brief An identifier-lookup iterator that enumerates all of the
6888 /// identifiers stored within a set of AST files.
6889 class ASTIdentifierIterator : public IdentifierIterator {
6890 /// \brief The AST reader whose identifiers are being enumerated.
6891 const ASTReader &Reader;
6892
6893 /// \brief The current index into the chain of AST files stored in
6894 /// the AST reader.
6895 unsigned Index;
6896
6897 /// \brief The current position within the identifier lookup table
6898 /// of the current AST file.
6899 ASTIdentifierLookupTable::key_iterator Current;
6900
6901 /// \brief The end position within the identifier lookup table of
6902 /// the current AST file.
6903 ASTIdentifierLookupTable::key_iterator End;
6904
6905 public:
6906 explicit ASTIdentifierIterator(const ASTReader &Reader);
6907
Craig Topper3e89dfe2014-03-13 02:13:41 +00006908 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006909 };
6910}
6911
6912ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6913 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6914 ASTIdentifierLookupTable *IdTable
6915 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6916 Current = IdTable->key_begin();
6917 End = IdTable->key_end();
6918}
6919
6920StringRef ASTIdentifierIterator::Next() {
6921 while (Current == End) {
6922 // If we have exhausted all of our AST files, we're done.
6923 if (Index == 0)
6924 return StringRef();
6925
6926 --Index;
6927 ASTIdentifierLookupTable *IdTable
6928 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6929 IdentifierLookupTable;
6930 Current = IdTable->key_begin();
6931 End = IdTable->key_end();
6932 }
6933
6934 // We have any identifiers remaining in the current AST file; return
6935 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006936 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006937 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006938 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006939}
6940
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006941IdentifierIterator *ASTReader::getIdentifiers() {
6942 if (!loadGlobalIndex())
6943 return GlobalIndex->createIdentifierIterator();
6944
Guy Benyei11169dd2012-12-18 14:30:41 +00006945 return new ASTIdentifierIterator(*this);
6946}
6947
6948namespace clang { namespace serialization {
6949 class ReadMethodPoolVisitor {
6950 ASTReader &Reader;
6951 Selector Sel;
6952 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006953 unsigned InstanceBits;
6954 unsigned FactoryBits;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006955 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6956 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006957
6958 public:
6959 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6960 unsigned PriorGeneration)
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006961 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6962 InstanceBits(0), FactoryBits(0) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006963
6964 static bool visit(ModuleFile &M, void *UserData) {
6965 ReadMethodPoolVisitor *This
6966 = static_cast<ReadMethodPoolVisitor *>(UserData);
6967
6968 if (!M.SelectorLookupTable)
6969 return false;
6970
6971 // If we've already searched this module file, skip it now.
6972 if (M.Generation <= This->PriorGeneration)
6973 return true;
6974
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006975 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006976 ASTSelectorLookupTable *PoolTable
6977 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6978 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6979 if (Pos == PoolTable->end())
6980 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006981
6982 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006983 ++This->Reader.NumSelectorsRead;
6984 // FIXME: Not quite happy with the statistics here. We probably should
6985 // disable this tracking when called via LoadSelector.
6986 // Also, should entries without methods count as misses?
6987 ++This->Reader.NumMethodPoolEntriesRead;
6988 ASTSelectorLookupTrait::data_type Data = *Pos;
6989 if (This->Reader.DeserializationListener)
6990 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6991 This->Sel);
6992
6993 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6994 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006995 This->InstanceBits = Data.InstanceBits;
6996 This->FactoryBits = Data.FactoryBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006997 return true;
6998 }
6999
7000 /// \brief Retrieve the instance methods found by this visitor.
7001 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7002 return InstanceMethods;
7003 }
7004
7005 /// \brief Retrieve the instance methods found by this visitor.
7006 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7007 return FactoryMethods;
7008 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007009
7010 unsigned getInstanceBits() const { return InstanceBits; }
7011 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007012 };
7013} } // end namespace clang::serialization
7014
7015/// \brief Add the given set of methods to the method list.
7016static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7017 ObjCMethodList &List) {
7018 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7019 S.addMethodToGlobalList(&List, Methods[I]);
7020 }
7021}
7022
7023void ASTReader::ReadMethodPool(Selector Sel) {
7024 // Get the selector generation and update it to the current generation.
7025 unsigned &Generation = SelectorGeneration[Sel];
7026 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007027 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007028
7029 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007030 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007031 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7032 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
7033
7034 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007035 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007036 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007037
7038 ++NumMethodPoolHits;
7039
Guy Benyei11169dd2012-12-18 14:30:41 +00007040 if (!getSema())
7041 return;
7042
7043 Sema &S = *getSema();
7044 Sema::GlobalMethodPool::iterator Pos
7045 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
7046
7047 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7048 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007049 Pos->second.first.setBits(Visitor.getInstanceBits());
7050 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei11169dd2012-12-18 14:30:41 +00007051}
7052
7053void ASTReader::ReadKnownNamespaces(
7054 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7055 Namespaces.clear();
7056
7057 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7058 if (NamespaceDecl *Namespace
7059 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7060 Namespaces.push_back(Namespace);
7061 }
7062}
7063
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007064void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007065 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007066 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7067 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007068 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007069 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007070 Undefined.insert(std::make_pair(D, Loc));
7071 }
7072}
Nick Lewycky8334af82013-01-26 00:35:08 +00007073
Guy Benyei11169dd2012-12-18 14:30:41 +00007074void ASTReader::ReadTentativeDefinitions(
7075 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7076 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7077 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7078 if (Var)
7079 TentativeDefs.push_back(Var);
7080 }
7081 TentativeDefinitions.clear();
7082}
7083
7084void ASTReader::ReadUnusedFileScopedDecls(
7085 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7086 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7087 DeclaratorDecl *D
7088 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7089 if (D)
7090 Decls.push_back(D);
7091 }
7092 UnusedFileScopedDecls.clear();
7093}
7094
7095void ASTReader::ReadDelegatingConstructors(
7096 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7097 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7098 CXXConstructorDecl *D
7099 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7100 if (D)
7101 Decls.push_back(D);
7102 }
7103 DelegatingCtorDecls.clear();
7104}
7105
7106void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7107 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7108 TypedefNameDecl *D
7109 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7110 if (D)
7111 Decls.push_back(D);
7112 }
7113 ExtVectorDecls.clear();
7114}
7115
7116void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
7117 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
7118 CXXRecordDecl *D
7119 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
7120 if (D)
7121 Decls.push_back(D);
7122 }
7123 DynamicClasses.clear();
7124}
7125
7126void
Richard Smith78165b52013-01-10 23:43:47 +00007127ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
7128 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
7129 NamedDecl *D
7130 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007131 if (D)
7132 Decls.push_back(D);
7133 }
Richard Smith78165b52013-01-10 23:43:47 +00007134 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007135}
7136
7137void ASTReader::ReadReferencedSelectors(
7138 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7139 if (ReferencedSelectorsData.empty())
7140 return;
7141
7142 // If there are @selector references added them to its pool. This is for
7143 // implementation of -Wselector.
7144 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7145 unsigned I = 0;
7146 while (I < DataSize) {
7147 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7148 SourceLocation SelLoc
7149 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7150 Sels.push_back(std::make_pair(Sel, SelLoc));
7151 }
7152 ReferencedSelectorsData.clear();
7153}
7154
7155void ASTReader::ReadWeakUndeclaredIdentifiers(
7156 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7157 if (WeakUndeclaredIdentifiers.empty())
7158 return;
7159
7160 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7161 IdentifierInfo *WeakId
7162 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7163 IdentifierInfo *AliasId
7164 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7165 SourceLocation Loc
7166 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7167 bool Used = WeakUndeclaredIdentifiers[I++];
7168 WeakInfo WI(AliasId, Loc);
7169 WI.setUsed(Used);
7170 WeakIDs.push_back(std::make_pair(WeakId, WI));
7171 }
7172 WeakUndeclaredIdentifiers.clear();
7173}
7174
7175void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7176 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7177 ExternalVTableUse VT;
7178 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7179 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7180 VT.DefinitionRequired = VTableUses[Idx++];
7181 VTables.push_back(VT);
7182 }
7183
7184 VTableUses.clear();
7185}
7186
7187void ASTReader::ReadPendingInstantiations(
7188 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7189 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7190 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7191 SourceLocation Loc
7192 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7193
7194 Pending.push_back(std::make_pair(D, Loc));
7195 }
7196 PendingInstantiations.clear();
7197}
7198
Richard Smithe40f2ba2013-08-07 21:41:30 +00007199void ASTReader::ReadLateParsedTemplates(
7200 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7201 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7202 /* In loop */) {
7203 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7204
7205 LateParsedTemplate *LT = new LateParsedTemplate;
7206 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7207
7208 ModuleFile *F = getOwningModuleFile(LT->D);
7209 assert(F && "No module");
7210
7211 unsigned TokN = LateParsedTemplates[Idx++];
7212 LT->Toks.reserve(TokN);
7213 for (unsigned T = 0; T < TokN; ++T)
7214 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7215
7216 LPTMap[FD] = LT;
7217 }
7218
7219 LateParsedTemplates.clear();
7220}
7221
Guy Benyei11169dd2012-12-18 14:30:41 +00007222void ASTReader::LoadSelector(Selector Sel) {
7223 // It would be complicated to avoid reading the methods anyway. So don't.
7224 ReadMethodPool(Sel);
7225}
7226
7227void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7228 assert(ID && "Non-zero identifier ID required");
7229 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7230 IdentifiersLoaded[ID - 1] = II;
7231 if (DeserializationListener)
7232 DeserializationListener->IdentifierRead(ID, II);
7233}
7234
7235/// \brief Set the globally-visible declarations associated with the given
7236/// identifier.
7237///
7238/// If the AST reader is currently in a state where the given declaration IDs
7239/// cannot safely be resolved, they are queued until it is safe to resolve
7240/// them.
7241///
7242/// \param II an IdentifierInfo that refers to one or more globally-visible
7243/// declarations.
7244///
7245/// \param DeclIDs the set of declaration IDs with the name @p II that are
7246/// visible at global scope.
7247///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007248/// \param Decls if non-null, this vector will be populated with the set of
7249/// deserialized declarations. These declarations will not be pushed into
7250/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007251void
7252ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7253 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007254 SmallVectorImpl<Decl *> *Decls) {
7255 if (NumCurrentElementsDeserializing && !Decls) {
7256 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007257 return;
7258 }
7259
7260 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
7261 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7262 if (SemaObj) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00007263 // If we're simply supposed to record the declarations, do so now.
7264 if (Decls) {
7265 Decls->push_back(D);
7266 continue;
7267 }
7268
Guy Benyei11169dd2012-12-18 14:30:41 +00007269 // Introduce this declaration into the translation-unit scope
7270 // and add it to the declaration chain for this identifier, so
7271 // that (unqualified) name lookup will find it.
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00007272 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007273 } else {
7274 // Queue this declaration so that it will be added to the
7275 // translation unit scope and identifier's declaration chain
7276 // once a Sema object is known.
7277 PreloadedDecls.push_back(D);
7278 }
7279 }
7280}
7281
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007282IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID 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 (IdentifiersLoaded.empty()) {
7287 Error("no identifier 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 -= 1;
7292 if (!IdentifiersLoaded[ID]) {
7293 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7294 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7295 ModuleFile *M = I->second;
7296 unsigned Index = ID - M->BaseIdentifierID;
7297 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7298
7299 // All of the strings in the AST file are preceded by a 16-bit length.
7300 // Extract that 16-bit length to avoid having to execute strlen().
7301 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7302 // unsigned integers. This is important to avoid integer overflow when
7303 // we cast them to 'unsigned'.
7304 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7305 unsigned StrLen = (((unsigned) StrLenPtr[0])
7306 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007307 IdentifiersLoaded[ID]
7308 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007309 if (DeserializationListener)
7310 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7311 }
7312
7313 return IdentifiersLoaded[ID];
7314}
7315
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007316IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7317 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007318}
7319
7320IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7321 if (LocalID < NUM_PREDEF_IDENT_IDS)
7322 return LocalID;
7323
7324 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7325 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7326 assert(I != M.IdentifierRemap.end()
7327 && "Invalid index into identifier index remap");
7328
7329 return LocalID + I->second;
7330}
7331
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007332MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007333 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007334 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007335
7336 if (MacrosLoaded.empty()) {
7337 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007338 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007339 }
7340
7341 ID -= NUM_PREDEF_MACRO_IDS;
7342 if (!MacrosLoaded[ID]) {
7343 GlobalMacroMapType::iterator I
7344 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7345 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7346 ModuleFile *M = I->second;
7347 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007348 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7349
7350 if (DeserializationListener)
7351 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7352 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007353 }
7354
7355 return MacrosLoaded[ID];
7356}
7357
7358MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7359 if (LocalID < NUM_PREDEF_MACRO_IDS)
7360 return LocalID;
7361
7362 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7363 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7364 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7365
7366 return LocalID + I->second;
7367}
7368
7369serialization::SubmoduleID
7370ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7371 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7372 return LocalID;
7373
7374 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7375 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7376 assert(I != M.SubmoduleRemap.end()
7377 && "Invalid index into submodule index remap");
7378
7379 return LocalID + I->second;
7380}
7381
7382Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7383 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7384 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007385 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007386 }
7387
7388 if (GlobalID > SubmodulesLoaded.size()) {
7389 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007390 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007391 }
7392
7393 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7394}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007395
7396Module *ASTReader::getModule(unsigned ID) {
7397 return getSubmodule(ID);
7398}
7399
Guy Benyei11169dd2012-12-18 14:30:41 +00007400Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7401 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7402}
7403
7404Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7405 if (ID == 0)
7406 return Selector();
7407
7408 if (ID > SelectorsLoaded.size()) {
7409 Error("selector ID out of range in AST file");
7410 return Selector();
7411 }
7412
Craig Toppera13603a2014-05-22 05:54:18 +00007413 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007414 // Load this selector from the selector table.
7415 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7416 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7417 ModuleFile &M = *I->second;
7418 ASTSelectorLookupTrait Trait(*this, M);
7419 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7420 SelectorsLoaded[ID - 1] =
7421 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7422 if (DeserializationListener)
7423 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7424 }
7425
7426 return SelectorsLoaded[ID - 1];
7427}
7428
7429Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7430 return DecodeSelector(ID);
7431}
7432
7433uint32_t ASTReader::GetNumExternalSelectors() {
7434 // ID 0 (the null selector) is considered an external selector.
7435 return getTotalNumSelectors() + 1;
7436}
7437
7438serialization::SelectorID
7439ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7440 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7441 return LocalID;
7442
7443 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7444 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7445 assert(I != M.SelectorRemap.end()
7446 && "Invalid index into selector index remap");
7447
7448 return LocalID + I->second;
7449}
7450
7451DeclarationName
7452ASTReader::ReadDeclarationName(ModuleFile &F,
7453 const RecordData &Record, unsigned &Idx) {
7454 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7455 switch (Kind) {
7456 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007457 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007458
7459 case DeclarationName::ObjCZeroArgSelector:
7460 case DeclarationName::ObjCOneArgSelector:
7461 case DeclarationName::ObjCMultiArgSelector:
7462 return DeclarationName(ReadSelector(F, Record, Idx));
7463
7464 case DeclarationName::CXXConstructorName:
7465 return Context.DeclarationNames.getCXXConstructorName(
7466 Context.getCanonicalType(readType(F, Record, Idx)));
7467
7468 case DeclarationName::CXXDestructorName:
7469 return Context.DeclarationNames.getCXXDestructorName(
7470 Context.getCanonicalType(readType(F, Record, Idx)));
7471
7472 case DeclarationName::CXXConversionFunctionName:
7473 return Context.DeclarationNames.getCXXConversionFunctionName(
7474 Context.getCanonicalType(readType(F, Record, Idx)));
7475
7476 case DeclarationName::CXXOperatorName:
7477 return Context.DeclarationNames.getCXXOperatorName(
7478 (OverloadedOperatorKind)Record[Idx++]);
7479
7480 case DeclarationName::CXXLiteralOperatorName:
7481 return Context.DeclarationNames.getCXXLiteralOperatorName(
7482 GetIdentifierInfo(F, Record, Idx));
7483
7484 case DeclarationName::CXXUsingDirective:
7485 return DeclarationName::getUsingDirectiveName();
7486 }
7487
7488 llvm_unreachable("Invalid NameKind!");
7489}
7490
7491void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7492 DeclarationNameLoc &DNLoc,
7493 DeclarationName Name,
7494 const RecordData &Record, unsigned &Idx) {
7495 switch (Name.getNameKind()) {
7496 case DeclarationName::CXXConstructorName:
7497 case DeclarationName::CXXDestructorName:
7498 case DeclarationName::CXXConversionFunctionName:
7499 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7500 break;
7501
7502 case DeclarationName::CXXOperatorName:
7503 DNLoc.CXXOperatorName.BeginOpNameLoc
7504 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7505 DNLoc.CXXOperatorName.EndOpNameLoc
7506 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7507 break;
7508
7509 case DeclarationName::CXXLiteralOperatorName:
7510 DNLoc.CXXLiteralOperatorName.OpNameLoc
7511 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7512 break;
7513
7514 case DeclarationName::Identifier:
7515 case DeclarationName::ObjCZeroArgSelector:
7516 case DeclarationName::ObjCOneArgSelector:
7517 case DeclarationName::ObjCMultiArgSelector:
7518 case DeclarationName::CXXUsingDirective:
7519 break;
7520 }
7521}
7522
7523void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7524 DeclarationNameInfo &NameInfo,
7525 const RecordData &Record, unsigned &Idx) {
7526 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7527 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7528 DeclarationNameLoc DNLoc;
7529 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7530 NameInfo.setInfo(DNLoc);
7531}
7532
7533void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7534 const RecordData &Record, unsigned &Idx) {
7535 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7536 unsigned NumTPLists = Record[Idx++];
7537 Info.NumTemplParamLists = NumTPLists;
7538 if (NumTPLists) {
7539 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7540 for (unsigned i=0; i != NumTPLists; ++i)
7541 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7542 }
7543}
7544
7545TemplateName
7546ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7547 unsigned &Idx) {
7548 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7549 switch (Kind) {
7550 case TemplateName::Template:
7551 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7552
7553 case TemplateName::OverloadedTemplate: {
7554 unsigned size = Record[Idx++];
7555 UnresolvedSet<8> Decls;
7556 while (size--)
7557 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7558
7559 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7560 }
7561
7562 case TemplateName::QualifiedTemplate: {
7563 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7564 bool hasTemplKeyword = Record[Idx++];
7565 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7566 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7567 }
7568
7569 case TemplateName::DependentTemplate: {
7570 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7571 if (Record[Idx++]) // isIdentifier
7572 return Context.getDependentTemplateName(NNS,
7573 GetIdentifierInfo(F, Record,
7574 Idx));
7575 return Context.getDependentTemplateName(NNS,
7576 (OverloadedOperatorKind)Record[Idx++]);
7577 }
7578
7579 case TemplateName::SubstTemplateTemplateParm: {
7580 TemplateTemplateParmDecl *param
7581 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7582 if (!param) return TemplateName();
7583 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7584 return Context.getSubstTemplateTemplateParm(param, replacement);
7585 }
7586
7587 case TemplateName::SubstTemplateTemplateParmPack: {
7588 TemplateTemplateParmDecl *Param
7589 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7590 if (!Param)
7591 return TemplateName();
7592
7593 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7594 if (ArgPack.getKind() != TemplateArgument::Pack)
7595 return TemplateName();
7596
7597 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7598 }
7599 }
7600
7601 llvm_unreachable("Unhandled template name kind!");
7602}
7603
7604TemplateArgument
7605ASTReader::ReadTemplateArgument(ModuleFile &F,
7606 const RecordData &Record, unsigned &Idx) {
7607 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7608 switch (Kind) {
7609 case TemplateArgument::Null:
7610 return TemplateArgument();
7611 case TemplateArgument::Type:
7612 return TemplateArgument(readType(F, Record, Idx));
7613 case TemplateArgument::Declaration: {
7614 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7615 bool ForReferenceParam = Record[Idx++];
7616 return TemplateArgument(D, ForReferenceParam);
7617 }
7618 case TemplateArgument::NullPtr:
7619 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7620 case TemplateArgument::Integral: {
7621 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7622 QualType T = readType(F, Record, Idx);
7623 return TemplateArgument(Context, Value, T);
7624 }
7625 case TemplateArgument::Template:
7626 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7627 case TemplateArgument::TemplateExpansion: {
7628 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007629 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007630 if (unsigned NumExpansions = Record[Idx++])
7631 NumTemplateExpansions = NumExpansions - 1;
7632 return TemplateArgument(Name, NumTemplateExpansions);
7633 }
7634 case TemplateArgument::Expression:
7635 return TemplateArgument(ReadExpr(F));
7636 case TemplateArgument::Pack: {
7637 unsigned NumArgs = Record[Idx++];
7638 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7639 for (unsigned I = 0; I != NumArgs; ++I)
7640 Args[I] = ReadTemplateArgument(F, Record, Idx);
7641 return TemplateArgument(Args, NumArgs);
7642 }
7643 }
7644
7645 llvm_unreachable("Unhandled template argument kind!");
7646}
7647
7648TemplateParameterList *
7649ASTReader::ReadTemplateParameterList(ModuleFile &F,
7650 const RecordData &Record, unsigned &Idx) {
7651 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7652 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7653 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7654
7655 unsigned NumParams = Record[Idx++];
7656 SmallVector<NamedDecl *, 16> Params;
7657 Params.reserve(NumParams);
7658 while (NumParams--)
7659 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7660
7661 TemplateParameterList* TemplateParams =
7662 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7663 Params.data(), Params.size(), RAngleLoc);
7664 return TemplateParams;
7665}
7666
7667void
7668ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007669ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007670 ModuleFile &F, const RecordData &Record,
7671 unsigned &Idx) {
7672 unsigned NumTemplateArgs = Record[Idx++];
7673 TemplArgs.reserve(NumTemplateArgs);
7674 while (NumTemplateArgs--)
7675 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7676}
7677
7678/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007679void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007680 const RecordData &Record, unsigned &Idx) {
7681 unsigned NumDecls = Record[Idx++];
7682 Set.reserve(Context, NumDecls);
7683 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007684 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007685 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007686 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007687 }
7688}
7689
7690CXXBaseSpecifier
7691ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7692 const RecordData &Record, unsigned &Idx) {
7693 bool isVirtual = static_cast<bool>(Record[Idx++]);
7694 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7695 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7696 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7697 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7698 SourceRange Range = ReadSourceRange(F, Record, Idx);
7699 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7700 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7701 EllipsisLoc);
7702 Result.setInheritConstructors(inheritConstructors);
7703 return Result;
7704}
7705
7706std::pair<CXXCtorInitializer **, unsigned>
7707ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7708 unsigned &Idx) {
Craig Toppera13603a2014-05-22 05:54:18 +00007709 CXXCtorInitializer **CtorInitializers = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007710 unsigned NumInitializers = Record[Idx++];
7711 if (NumInitializers) {
7712 CtorInitializers
7713 = new (Context) CXXCtorInitializer*[NumInitializers];
7714 for (unsigned i=0; i != NumInitializers; ++i) {
Craig Toppera13603a2014-05-22 05:54:18 +00007715 TypeSourceInfo *TInfo = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007716 bool IsBaseVirtual = false;
Craig Toppera13603a2014-05-22 05:54:18 +00007717 FieldDecl *Member = nullptr;
7718 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007719
7720 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7721 switch (Type) {
7722 case CTOR_INITIALIZER_BASE:
7723 TInfo = GetTypeSourceInfo(F, Record, Idx);
7724 IsBaseVirtual = Record[Idx++];
7725 break;
7726
7727 case CTOR_INITIALIZER_DELEGATING:
7728 TInfo = GetTypeSourceInfo(F, Record, Idx);
7729 break;
7730
7731 case CTOR_INITIALIZER_MEMBER:
7732 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7733 break;
7734
7735 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7736 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7737 break;
7738 }
7739
7740 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7741 Expr *Init = ReadExpr(F);
7742 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7743 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7744 bool IsWritten = Record[Idx++];
7745 unsigned SourceOrderOrNumArrayIndices;
7746 SmallVector<VarDecl *, 8> Indices;
7747 if (IsWritten) {
7748 SourceOrderOrNumArrayIndices = Record[Idx++];
7749 } else {
7750 SourceOrderOrNumArrayIndices = Record[Idx++];
7751 Indices.reserve(SourceOrderOrNumArrayIndices);
7752 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7753 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7754 }
7755
7756 CXXCtorInitializer *BOMInit;
7757 if (Type == CTOR_INITIALIZER_BASE) {
7758 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7759 LParenLoc, Init, RParenLoc,
7760 MemberOrEllipsisLoc);
7761 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7762 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7763 Init, RParenLoc);
7764 } else if (IsWritten) {
7765 if (Member)
7766 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7767 LParenLoc, Init, RParenLoc);
7768 else
7769 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7770 MemberOrEllipsisLoc, LParenLoc,
7771 Init, RParenLoc);
7772 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007773 if (IndirectMember) {
7774 assert(Indices.empty() && "Indirect field improperly initialized");
7775 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7776 MemberOrEllipsisLoc, LParenLoc,
7777 Init, RParenLoc);
7778 } else {
7779 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7780 LParenLoc, Init, RParenLoc,
7781 Indices.data(), Indices.size());
7782 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007783 }
7784
7785 if (IsWritten)
7786 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7787 CtorInitializers[i] = BOMInit;
7788 }
7789 }
7790
7791 return std::make_pair(CtorInitializers, NumInitializers);
7792}
7793
7794NestedNameSpecifier *
7795ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7796 const RecordData &Record, unsigned &Idx) {
7797 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007798 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007799 for (unsigned I = 0; I != N; ++I) {
7800 NestedNameSpecifier::SpecifierKind Kind
7801 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7802 switch (Kind) {
7803 case NestedNameSpecifier::Identifier: {
7804 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7805 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7806 break;
7807 }
7808
7809 case NestedNameSpecifier::Namespace: {
7810 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7811 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7812 break;
7813 }
7814
7815 case NestedNameSpecifier::NamespaceAlias: {
7816 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7817 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7818 break;
7819 }
7820
7821 case NestedNameSpecifier::TypeSpec:
7822 case NestedNameSpecifier::TypeSpecWithTemplate: {
7823 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7824 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007825 return nullptr;
7826
Guy Benyei11169dd2012-12-18 14:30:41 +00007827 bool Template = Record[Idx++];
7828 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7829 break;
7830 }
7831
7832 case NestedNameSpecifier::Global: {
7833 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7834 // No associated value, and there can't be a prefix.
7835 break;
7836 }
7837 }
7838 Prev = NNS;
7839 }
7840 return NNS;
7841}
7842
7843NestedNameSpecifierLoc
7844ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7845 unsigned &Idx) {
7846 unsigned N = Record[Idx++];
7847 NestedNameSpecifierLocBuilder Builder;
7848 for (unsigned I = 0; I != N; ++I) {
7849 NestedNameSpecifier::SpecifierKind Kind
7850 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7851 switch (Kind) {
7852 case NestedNameSpecifier::Identifier: {
7853 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7854 SourceRange Range = ReadSourceRange(F, Record, Idx);
7855 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7856 break;
7857 }
7858
7859 case NestedNameSpecifier::Namespace: {
7860 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7861 SourceRange Range = ReadSourceRange(F, Record, Idx);
7862 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7863 break;
7864 }
7865
7866 case NestedNameSpecifier::NamespaceAlias: {
7867 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7868 SourceRange Range = ReadSourceRange(F, Record, Idx);
7869 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7870 break;
7871 }
7872
7873 case NestedNameSpecifier::TypeSpec:
7874 case NestedNameSpecifier::TypeSpecWithTemplate: {
7875 bool Template = Record[Idx++];
7876 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7877 if (!T)
7878 return NestedNameSpecifierLoc();
7879 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7880
7881 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7882 Builder.Extend(Context,
7883 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7884 T->getTypeLoc(), ColonColonLoc);
7885 break;
7886 }
7887
7888 case NestedNameSpecifier::Global: {
7889 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7890 Builder.MakeGlobal(Context, ColonColonLoc);
7891 break;
7892 }
7893 }
7894 }
7895
7896 return Builder.getWithLocInContext(Context);
7897}
7898
7899SourceRange
7900ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7901 unsigned &Idx) {
7902 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7903 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7904 return SourceRange(beg, end);
7905}
7906
7907/// \brief Read an integral value
7908llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7909 unsigned BitWidth = Record[Idx++];
7910 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7911 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7912 Idx += NumWords;
7913 return Result;
7914}
7915
7916/// \brief Read a signed integral value
7917llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7918 bool isUnsigned = Record[Idx++];
7919 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7920}
7921
7922/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007923llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7924 const llvm::fltSemantics &Sem,
7925 unsigned &Idx) {
7926 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007927}
7928
7929// \brief Read a string
7930std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7931 unsigned Len = Record[Idx++];
7932 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7933 Idx += Len;
7934 return Result;
7935}
7936
7937VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7938 unsigned &Idx) {
7939 unsigned Major = Record[Idx++];
7940 unsigned Minor = Record[Idx++];
7941 unsigned Subminor = Record[Idx++];
7942 if (Minor == 0)
7943 return VersionTuple(Major);
7944 if (Subminor == 0)
7945 return VersionTuple(Major, Minor - 1);
7946 return VersionTuple(Major, Minor - 1, Subminor - 1);
7947}
7948
7949CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7950 const RecordData &Record,
7951 unsigned &Idx) {
7952 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7953 return CXXTemporary::Create(Context, Decl);
7954}
7955
7956DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007957 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007958}
7959
7960DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7961 return Diags.Report(Loc, DiagID);
7962}
7963
7964/// \brief Retrieve the identifier table associated with the
7965/// preprocessor.
7966IdentifierTable &ASTReader::getIdentifierTable() {
7967 return PP.getIdentifierTable();
7968}
7969
7970/// \brief Record that the given ID maps to the given switch-case
7971/// statement.
7972void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007973 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007974 "Already have a SwitchCase with this ID");
7975 (*CurrSwitchCaseStmts)[ID] = SC;
7976}
7977
7978/// \brief Retrieve the switch-case statement with the given ID.
7979SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007980 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00007981 return (*CurrSwitchCaseStmts)[ID];
7982}
7983
7984void ASTReader::ClearSwitchCaseIDs() {
7985 CurrSwitchCaseStmts->clear();
7986}
7987
7988void ASTReader::ReadComments() {
7989 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007990 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007991 serialization::ModuleFile *> >::iterator
7992 I = CommentsCursors.begin(),
7993 E = CommentsCursors.end();
7994 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007995 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007996 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007997 serialization::ModuleFile &F = *I->second;
7998 SavedStreamPosition SavedPosition(Cursor);
7999
8000 RecordData Record;
8001 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008002 llvm::BitstreamEntry Entry =
8003 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008004
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008005 switch (Entry.Kind) {
8006 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8007 case llvm::BitstreamEntry::Error:
8008 Error("malformed block record in AST file");
8009 return;
8010 case llvm::BitstreamEntry::EndBlock:
8011 goto NextCursor;
8012 case llvm::BitstreamEntry::Record:
8013 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008014 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008015 }
8016
8017 // Read a record.
8018 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008019 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008020 case COMMENTS_RAW_COMMENT: {
8021 unsigned Idx = 0;
8022 SourceRange SR = ReadSourceRange(F, Record, Idx);
8023 RawComment::CommentKind Kind =
8024 (RawComment::CommentKind) Record[Idx++];
8025 bool IsTrailingComment = Record[Idx++];
8026 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008027 Comments.push_back(new (Context) RawComment(
8028 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8029 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008030 break;
8031 }
8032 }
8033 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008034 NextCursor:
8035 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008036 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008037}
8038
Richard Smithcd45dbc2014-04-19 03:48:30 +00008039std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8040 // If we know the owning module, use it.
8041 if (Module *M = D->getOwningModule())
8042 return M->getFullModuleName();
8043
8044 // Otherwise, use the name of the top-level module the decl is within.
8045 if (ModuleFile *M = getOwningModuleFile(D))
8046 return M->ModuleName;
8047
8048 // Not from a module.
8049 return "";
8050}
8051
Guy Benyei11169dd2012-12-18 14:30:41 +00008052void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008053 while (!PendingIdentifierInfos.empty() ||
8054 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008055 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008056 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008057 // If any identifiers with corresponding top-level declarations have
8058 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008059 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8060 TopLevelDeclsMap;
8061 TopLevelDeclsMap TopLevelDecls;
8062
Guy Benyei11169dd2012-12-18 14:30:41 +00008063 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008064 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008065 SmallVector<uint32_t, 4> DeclIDs =
8066 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008067 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008068
8069 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008070 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008071
Richard Smith851072e2014-05-19 20:59:20 +00008072 // For each decl chain that we wanted to complete while deserializing, mark
8073 // it as "still needs to be completed".
8074 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8075 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8076 }
8077 PendingIncompleteDeclChains.clear();
8078
Guy Benyei11169dd2012-12-18 14:30:41 +00008079 // Load pending declaration chains.
8080 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
8081 loadPendingDeclChain(PendingDeclChains[I]);
8082 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
8083 }
8084 PendingDeclChains.clear();
8085
Douglas Gregor6168bd22013-02-18 15:53:43 +00008086 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008087 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8088 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008089 IdentifierInfo *II = TLD->first;
8090 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008091 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008092 }
8093 }
8094
Guy Benyei11169dd2012-12-18 14:30:41 +00008095 // Load any pending macro definitions.
8096 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008097 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8098 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8099 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8100 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008101 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008102 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008103 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8104 if (Info.M->Kind != MK_Module)
8105 resolvePendingMacro(II, Info);
8106 }
8107 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008108 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008109 ++IDIdx) {
8110 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8111 if (Info.M->Kind == MK_Module)
8112 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008113 }
8114 }
8115 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008116
8117 // Wire up the DeclContexts for Decls that we delayed setting until
8118 // recursive loading is completed.
8119 while (!PendingDeclContextInfos.empty()) {
8120 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8121 PendingDeclContextInfos.pop_front();
8122 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8123 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8124 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8125 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008126
Richard Smithd1c46742014-04-30 02:24:17 +00008127 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008128 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008129 auto Update = PendingUpdateRecords.pop_back_val();
8130 ReadingKindTracker ReadingKind(Read_Decl, *this);
8131 loadDeclUpdateRecords(Update.first, Update.second);
8132 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008133 }
8134
8135 // If we deserialized any C++ or Objective-C class definitions, any
8136 // Objective-C protocol definitions, or any redeclarable templates, make sure
8137 // that all redeclarations point to the definitions. Note that this can only
8138 // happen now, after the redeclaration chains have been fully wired.
8139 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
8140 DEnd = PendingDefinitions.end();
8141 D != DEnd; ++D) {
8142 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008143 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008144 // Make sure that the TagType points at the definition.
8145 const_cast<TagType*>(TagT)->decl = TD;
8146 }
8147
Aaron Ballman86c93902014-03-06 23:45:36 +00008148 if (auto RD = dyn_cast<CXXRecordDecl>(*D)) {
8149 for (auto R : RD->redecls())
8150 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Guy Benyei11169dd2012-12-18 14:30:41 +00008151 }
8152
8153 continue;
8154 }
8155
Aaron Ballman86c93902014-03-06 23:45:36 +00008156 if (auto ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008157 // Make sure that the ObjCInterfaceType points at the definition.
8158 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8159 ->Decl = ID;
8160
Aaron Ballman86c93902014-03-06 23:45:36 +00008161 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008162 R->Data = ID->Data;
8163
8164 continue;
8165 }
8166
Aaron Ballman86c93902014-03-06 23:45:36 +00008167 if (auto PD = dyn_cast<ObjCProtocolDecl>(*D)) {
8168 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008169 R->Data = PD->Data;
8170
8171 continue;
8172 }
8173
Aaron Ballman86c93902014-03-06 23:45:36 +00008174 auto RTD = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
8175 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008176 R->Common = RTD->Common;
8177 }
8178 PendingDefinitions.clear();
8179
8180 // Load the bodies of any functions or methods we've encountered. We do
8181 // this now (delayed) so that we can be sure that the declaration chains
8182 // have been fully wired up.
8183 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8184 PBEnd = PendingBodies.end();
8185 PB != PBEnd; ++PB) {
8186 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8187 // FIXME: Check for =delete/=default?
8188 // FIXME: Complain about ODR violations here?
8189 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8190 FD->setLazyBody(PB->second);
8191 continue;
8192 }
8193
8194 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8195 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8196 MD->setLazyBody(PB->second);
8197 }
8198 PendingBodies.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008199}
8200
8201void ASTReader::diagnoseOdrViolations() {
8202 // Trigger the import of the full definition of each class that had any
8203 // odr-merging problems, so we can produce better diagnostics for them.
8204 for (auto &Merge : PendingOdrMergeFailures) {
8205 Merge.first->buildLookup();
8206 Merge.first->decls_begin();
8207 Merge.first->bases_begin();
8208 Merge.first->vbases_begin();
8209 for (auto *RD : Merge.second) {
8210 RD->decls_begin();
8211 RD->bases_begin();
8212 RD->vbases_begin();
8213 }
8214 }
8215
8216 // For each declaration from a merged context, check that the canonical
8217 // definition of that context also contains a declaration of the same
8218 // entity.
8219 //
8220 // Caution: this loop does things that might invalidate iterators into
8221 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8222 while (!PendingOdrMergeChecks.empty()) {
8223 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8224
8225 // FIXME: Skip over implicit declarations for now. This matters for things
8226 // like implicitly-declared special member functions. This isn't entirely
8227 // correct; we can end up with multiple unmerged declarations of the same
8228 // implicit entity.
8229 if (D->isImplicit())
8230 continue;
8231
8232 DeclContext *CanonDef = D->getDeclContext();
8233 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
8234
8235 bool Found = false;
8236 const Decl *DCanon = D->getCanonicalDecl();
8237
8238 llvm::SmallVector<const NamedDecl*, 4> Candidates;
8239 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8240 !Found && I != E; ++I) {
8241 for (auto RI : (*I)->redecls()) {
8242 if (RI->getLexicalDeclContext() == CanonDef) {
8243 // This declaration is present in the canonical definition. If it's
8244 // in the same redecl chain, it's the one we're looking for.
8245 if (RI->getCanonicalDecl() == DCanon)
8246 Found = true;
8247 else
8248 Candidates.push_back(cast<NamedDecl>(RI));
8249 break;
8250 }
8251 }
8252 }
8253
8254 if (!Found) {
8255 D->setInvalidDecl();
8256
8257 std::string CanonDefModule =
8258 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8259 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8260 << D << getOwningModuleNameForDiagnostic(D)
8261 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8262
8263 if (Candidates.empty())
8264 Diag(cast<Decl>(CanonDef)->getLocation(),
8265 diag::note_module_odr_violation_no_possible_decls) << D;
8266 else {
8267 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8268 Diag(Candidates[I]->getLocation(),
8269 diag::note_module_odr_violation_possible_decl)
8270 << Candidates[I];
8271 }
8272
8273 DiagnosedOdrMergeFailures.insert(CanonDef);
8274 }
8275 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008276
8277 // Issue any pending ODR-failure diagnostics.
8278 for (auto &Merge : PendingOdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008279 // If we've already pointed out a specific problem with this class, don't
8280 // bother issuing a general "something's different" diagnostic.
Richard Smithcd45dbc2014-04-19 03:48:30 +00008281 if (!DiagnosedOdrMergeFailures.insert(Merge.first))
8282 continue;
8283
8284 bool Diagnosed = false;
8285 for (auto *RD : Merge.second) {
8286 // Multiple different declarations got merged together; tell the user
8287 // where they came from.
8288 if (Merge.first != RD) {
8289 // FIXME: Walk the definition, figure out what's different,
8290 // and diagnose that.
8291 if (!Diagnosed) {
8292 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8293 Diag(Merge.first->getLocation(),
8294 diag::err_module_odr_violation_different_definitions)
8295 << Merge.first << Module.empty() << Module;
8296 Diagnosed = true;
8297 }
8298
8299 Diag(RD->getLocation(),
8300 diag::note_module_odr_violation_different_definitions)
8301 << getOwningModuleNameForDiagnostic(RD);
8302 }
8303 }
8304
8305 if (!Diagnosed) {
8306 // All definitions are updates to the same declaration. This happens if a
8307 // module instantiates the declaration of a class template specialization
8308 // and two or more other modules instantiate its definition.
8309 //
8310 // FIXME: Indicate which modules had instantiations of this definition.
8311 // FIXME: How can this even happen?
8312 Diag(Merge.first->getLocation(),
8313 diag::err_module_odr_violation_different_instantiations)
8314 << Merge.first;
8315 }
8316 }
8317 PendingOdrMergeFailures.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00008318}
8319
8320void ASTReader::FinishedDeserializing() {
8321 assert(NumCurrentElementsDeserializing &&
8322 "FinishedDeserializing not paired with StartedDeserializing");
8323 if (NumCurrentElementsDeserializing == 1) {
8324 // We decrease NumCurrentElementsDeserializing only after pending actions
8325 // are finished, to avoid recursively re-calling finishPendingActions().
8326 finishPendingActions();
8327 }
8328 --NumCurrentElementsDeserializing;
8329
Richard Smitha0ce9c42014-07-29 23:23:27 +00008330 if (NumCurrentElementsDeserializing == 0) {
8331 diagnoseOdrViolations();
8332
Richard Smith04d05b52014-03-23 00:27:18 +00008333 // We are not in recursive loading, so it's safe to pass the "interesting"
8334 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008335 if (Consumer)
8336 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008337 }
8338}
8339
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008340void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00008341 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008342
8343 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8344 SemaObj->TUScope->AddDecl(D);
8345 } else if (SemaObj->TUScope) {
8346 // Adding the decl to IdResolver may have failed because it was already in
8347 // (even though it was not added in scope). If it is already in, make sure
8348 // it gets in the scope as well.
8349 if (std::find(SemaObj->IdResolver.begin(Name),
8350 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8351 SemaObj->TUScope->AddDecl(D);
8352 }
8353}
8354
Nico Weber824285e2014-05-08 04:26:47 +00008355ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8356 bool DisableValidation, bool AllowASTWithCompilerErrors,
8357 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008358 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008359 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008360 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Craig Toppera13603a2014-05-22 05:54:18 +00008361 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
8362 SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
8363 ModuleMgr(PP.getFileManager()), isysroot(isysroot),
8364 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008365 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8366 AllowConfigurationMismatch(AllowConfigurationMismatch),
8367 ValidateSystemInputs(ValidateSystemInputs),
8368 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Richard Smith053f6c62014-05-16 23:01:30 +00008369 CurrSwitchCaseStmts(&SwitchCaseStmts),
Nico Weber824285e2014-05-08 04:26:47 +00008370 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8371 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8372 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8373 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8374 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8375 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8376 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8377 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8378 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8379 PassingDeclsToConsumer(false), NumCXXBaseSpecifiersLoaded(0),
8380 ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008381 SourceMgr.setExternalSLocEntrySource(this);
8382}
8383
8384ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008385 if (OwnsDeserializationListener)
8386 delete DeserializationListener;
8387
Guy Benyei11169dd2012-12-18 14:30:41 +00008388 for (DeclContextVisibleUpdatesPending::iterator
8389 I = PendingVisibleUpdates.begin(),
8390 E = PendingVisibleUpdates.end();
8391 I != E; ++I) {
8392 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8393 F = I->second.end();
8394 J != F; ++J)
8395 delete J->first;
8396 }
8397}