blob: b253704a3616e89614cdb245b405a710b4499208 [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}
Richard Smith1e2cf0d2014-10-31 02:28:58 +000083bool
84ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
85 bool Complain,
86 bool AllowCompatibleDifferences) {
87 return First->ReadLanguageOptions(LangOpts, Complain,
88 AllowCompatibleDifferences) ||
89 Second->ReadLanguageOptions(LangOpts, Complain,
90 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000091}
92bool
93ChainedASTReaderListener::ReadTargetOptions(const TargetOptions &TargetOpts,
94 bool Complain) {
95 return First->ReadTargetOptions(TargetOpts, Complain) ||
96 Second->ReadTargetOptions(TargetOpts, Complain);
97}
98bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +000099 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000100 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
101 Second->ReadDiagnosticOptions(DiagOpts, Complain);
102}
103bool
104ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
105 bool Complain) {
106 return First->ReadFileSystemOptions(FSOpts, Complain) ||
107 Second->ReadFileSystemOptions(FSOpts, Complain);
108}
109
110bool ChainedASTReaderListener::ReadHeaderSearchOptions(
111 const HeaderSearchOptions &HSOpts, bool Complain) {
112 return First->ReadHeaderSearchOptions(HSOpts, Complain) ||
113 Second->ReadHeaderSearchOptions(HSOpts, Complain);
114}
115bool ChainedASTReaderListener::ReadPreprocessorOptions(
116 const PreprocessorOptions &PPOpts, bool Complain,
117 std::string &SuggestedPredefines) {
118 return First->ReadPreprocessorOptions(PPOpts, Complain,
119 SuggestedPredefines) ||
120 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
121}
122void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
123 unsigned Value) {
124 First->ReadCounter(M, Value);
125 Second->ReadCounter(M, Value);
126}
127bool ChainedASTReaderListener::needsInputFileVisitation() {
128 return First->needsInputFileVisitation() ||
129 Second->needsInputFileVisitation();
130}
131bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
132 return First->needsSystemInputFileVisitation() ||
133 Second->needsSystemInputFileVisitation();
134}
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000135void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
136 First->visitModuleFile(Filename);
137 Second->visitModuleFile(Filename);
138}
Ben Langmuircb69b572014-03-07 06:40:32 +0000139bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000140 bool isSystem,
141 bool isOverridden) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000142 bool Continue = false;
143 if (First->needsInputFileVisitation() &&
144 (!isSystem || First->needsSystemInputFileVisitation()))
145 Continue |= First->visitInputFile(Filename, isSystem, isOverridden);
146 if (Second->needsInputFileVisitation() &&
147 (!isSystem || Second->needsSystemInputFileVisitation()))
148 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden);
149 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000150}
151
Guy Benyei11169dd2012-12-18 14:30:41 +0000152//===----------------------------------------------------------------------===//
153// PCH validator implementation
154//===----------------------------------------------------------------------===//
155
156ASTReaderListener::~ASTReaderListener() {}
157
158/// \brief Compare the given set of language options against an existing set of
159/// language options.
160///
161/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000162/// \param AllowCompatibleDifferences If true, differences between compatible
163/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000164///
165/// \returns true if the languagae options mis-match, false otherwise.
166static bool checkLanguageOptions(const LangOptions &LangOpts,
167 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000168 DiagnosticsEngine *Diags,
169 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000170#define LANGOPT(Name, Bits, Default, Description) \
171 if (ExistingLangOpts.Name != LangOpts.Name) { \
172 if (Diags) \
173 Diags->Report(diag::err_pch_langopt_mismatch) \
174 << Description << LangOpts.Name << ExistingLangOpts.Name; \
175 return true; \
176 }
177
178#define VALUE_LANGOPT(Name, Bits, Default, Description) \
179 if (ExistingLangOpts.Name != LangOpts.Name) { \
180 if (Diags) \
181 Diags->Report(diag::err_pch_langopt_value_mismatch) \
182 << Description; \
183 return true; \
184 }
185
186#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
187 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
188 if (Diags) \
189 Diags->Report(diag::err_pch_langopt_value_mismatch) \
190 << Description; \
191 return true; \
192 }
193
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000194#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
195 if (!AllowCompatibleDifferences) \
196 LANGOPT(Name, Bits, Default, Description)
197
198#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
199 if (!AllowCompatibleDifferences) \
200 ENUM_LANGOPT(Name, Bits, Default, Description)
201
Guy Benyei11169dd2012-12-18 14:30:41 +0000202#define BENIGN_LANGOPT(Name, Bits, Default, Description)
203#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
204#include "clang/Basic/LangOptions.def"
205
206 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
207 if (Diags)
208 Diags->Report(diag::err_pch_langopt_value_mismatch)
209 << "target Objective-C runtime";
210 return true;
211 }
212
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000213 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
214 LangOpts.CommentOpts.BlockCommandNames) {
215 if (Diags)
216 Diags->Report(diag::err_pch_langopt_value_mismatch)
217 << "block command names";
218 return true;
219 }
220
Guy Benyei11169dd2012-12-18 14:30:41 +0000221 return false;
222}
223
224/// \brief Compare the given set of target options against an existing set of
225/// target options.
226///
227/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
228///
229/// \returns true if the target options mis-match, false otherwise.
230static bool checkTargetOptions(const TargetOptions &TargetOpts,
231 const TargetOptions &ExistingTargetOpts,
232 DiagnosticsEngine *Diags) {
233#define CHECK_TARGET_OPT(Field, Name) \
234 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
235 if (Diags) \
236 Diags->Report(diag::err_pch_targetopt_mismatch) \
237 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
238 return true; \
239 }
240
241 CHECK_TARGET_OPT(Triple, "target");
242 CHECK_TARGET_OPT(CPU, "target CPU");
243 CHECK_TARGET_OPT(ABI, "target ABI");
Guy Benyei11169dd2012-12-18 14:30:41 +0000244#undef CHECK_TARGET_OPT
245
246 // Compare feature sets.
247 SmallVector<StringRef, 4> ExistingFeatures(
248 ExistingTargetOpts.FeaturesAsWritten.begin(),
249 ExistingTargetOpts.FeaturesAsWritten.end());
250 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
251 TargetOpts.FeaturesAsWritten.end());
252 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
253 std::sort(ReadFeatures.begin(), ReadFeatures.end());
254
255 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
256 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
257 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
258 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
259 ++ExistingIdx;
260 ++ReadIdx;
261 continue;
262 }
263
264 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
265 if (Diags)
266 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
267 << false << ReadFeatures[ReadIdx];
268 return true;
269 }
270
271 if (Diags)
272 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
273 << true << ExistingFeatures[ExistingIdx];
274 return true;
275 }
276
277 if (ExistingIdx < ExistingN) {
278 if (Diags)
279 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
280 << true << ExistingFeatures[ExistingIdx];
281 return true;
282 }
283
284 if (ReadIdx < ReadN) {
285 if (Diags)
286 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
287 << false << ReadFeatures[ReadIdx];
288 return true;
289 }
290
291 return false;
292}
293
294bool
295PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000296 bool Complain,
297 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000298 const LangOptions &ExistingLangOpts = PP.getLangOpts();
299 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000300 Complain ? &Reader.Diags : nullptr,
301 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000302}
303
304bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
305 bool Complain) {
306 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
307 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000308 Complain? &Reader.Diags : nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000309}
310
311namespace {
312 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
313 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000314 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
315 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000316}
317
Ben Langmuirb92de022014-04-29 16:25:26 +0000318static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
319 DiagnosticsEngine &Diags,
320 bool Complain) {
321 typedef DiagnosticsEngine::Level Level;
322
323 // Check current mappings for new -Werror mappings, and the stored mappings
324 // for cases that were explicitly mapped to *not* be errors that are now
325 // errors because of options like -Werror.
326 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
327
328 for (DiagnosticsEngine *MappingSource : MappingSources) {
329 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
330 diag::kind DiagID = DiagIDMappingPair.first;
331 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
332 if (CurLevel < DiagnosticsEngine::Error)
333 continue; // not significant
334 Level StoredLevel =
335 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
336 if (StoredLevel < DiagnosticsEngine::Error) {
337 if (Complain)
338 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
339 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
340 return true;
341 }
342 }
343 }
344
345 return false;
346}
347
Alp Tokerac4e8e52014-06-22 21:58:33 +0000348static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
349 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
350 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
351 return true;
352 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000353}
354
355static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
356 DiagnosticsEngine &Diags,
357 bool IsSystem, bool Complain) {
358 // Top-level options
359 if (IsSystem) {
360 if (Diags.getSuppressSystemWarnings())
361 return false;
362 // If -Wsystem-headers was not enabled before, be conservative
363 if (StoredDiags.getSuppressSystemWarnings()) {
364 if (Complain)
365 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
366 return true;
367 }
368 }
369
370 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
371 if (Complain)
372 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
373 return true;
374 }
375
376 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
377 !StoredDiags.getEnableAllWarnings()) {
378 if (Complain)
379 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
380 return true;
381 }
382
383 if (isExtHandlingFromDiagsError(Diags) &&
384 !isExtHandlingFromDiagsError(StoredDiags)) {
385 if (Complain)
386 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
387 return true;
388 }
389
390 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
391}
392
393bool PCHValidator::ReadDiagnosticOptions(
394 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
395 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
396 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
397 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000398 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000399 // This should never fail, because we would have processed these options
400 // before writing them to an ASTFile.
401 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
402
403 ModuleManager &ModuleMgr = Reader.getModuleManager();
404 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
405
406 // If the original import came from a file explicitly generated by the user,
407 // don't check the diagnostic mappings.
408 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000409 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000410 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
411 // the transitive closure of its imports, since unrelated modules cannot be
412 // imported until after this module finishes validation.
413 ModuleFile *TopImport = *ModuleMgr.rbegin();
414 while (!TopImport->ImportedBy.empty())
415 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000416 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000417 return false;
418
419 StringRef ModuleName = TopImport->ModuleName;
420 assert(!ModuleName.empty() && "diagnostic options read before module name");
421
422 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
423 assert(M && "missing module");
424
425 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
426 // contains the union of their flags.
427 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
428}
429
Guy Benyei11169dd2012-12-18 14:30:41 +0000430/// \brief Collect the macro definitions provided by the given preprocessor
431/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000432static void
433collectMacroDefinitions(const PreprocessorOptions &PPOpts,
434 MacroDefinitionsMap &Macros,
435 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000436 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
437 StringRef Macro = PPOpts.Macros[I].first;
438 bool IsUndef = PPOpts.Macros[I].second;
439
440 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
441 StringRef MacroName = MacroPair.first;
442 StringRef MacroBody = MacroPair.second;
443
444 // For an #undef'd macro, we only care about the name.
445 if (IsUndef) {
446 if (MacroNames && !Macros.count(MacroName))
447 MacroNames->push_back(MacroName);
448
449 Macros[MacroName] = std::make_pair("", true);
450 continue;
451 }
452
453 // For a #define'd macro, figure out the actual definition.
454 if (MacroName.size() == Macro.size())
455 MacroBody = "1";
456 else {
457 // Note: GCC drops anything following an end-of-line character.
458 StringRef::size_type End = MacroBody.find_first_of("\n\r");
459 MacroBody = MacroBody.substr(0, End);
460 }
461
462 if (MacroNames && !Macros.count(MacroName))
463 MacroNames->push_back(MacroName);
464 Macros[MacroName] = std::make_pair(MacroBody, false);
465 }
466}
467
468/// \brief Check the preprocessor options deserialized from the control block
469/// against the preprocessor options in an existing preprocessor.
470///
471/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
472static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
473 const PreprocessorOptions &ExistingPPOpts,
474 DiagnosticsEngine *Diags,
475 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000476 std::string &SuggestedPredefines,
477 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000478 // Check macro definitions.
479 MacroDefinitionsMap ASTFileMacros;
480 collectMacroDefinitions(PPOpts, ASTFileMacros);
481 MacroDefinitionsMap ExistingMacros;
482 SmallVector<StringRef, 4> ExistingMacroNames;
483 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
484
485 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
486 // Dig out the macro definition in the existing preprocessor options.
487 StringRef MacroName = ExistingMacroNames[I];
488 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
489
490 // Check whether we know anything about this macro name or not.
491 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
492 = ASTFileMacros.find(MacroName);
493 if (Known == ASTFileMacros.end()) {
494 // FIXME: Check whether this identifier was referenced anywhere in the
495 // AST file. If so, we should reject the AST file. Unfortunately, this
496 // information isn't in the control block. What shall we do about it?
497
498 if (Existing.second) {
499 SuggestedPredefines += "#undef ";
500 SuggestedPredefines += MacroName.str();
501 SuggestedPredefines += '\n';
502 } else {
503 SuggestedPredefines += "#define ";
504 SuggestedPredefines += MacroName.str();
505 SuggestedPredefines += ' ';
506 SuggestedPredefines += Existing.first.str();
507 SuggestedPredefines += '\n';
508 }
509 continue;
510 }
511
512 // If the macro was defined in one but undef'd in the other, we have a
513 // conflict.
514 if (Existing.second != Known->second.second) {
515 if (Diags) {
516 Diags->Report(diag::err_pch_macro_def_undef)
517 << MacroName << Known->second.second;
518 }
519 return true;
520 }
521
522 // If the macro was #undef'd in both, or if the macro bodies are identical,
523 // it's fine.
524 if (Existing.second || Existing.first == Known->second.first)
525 continue;
526
527 // The macro bodies differ; complain.
528 if (Diags) {
529 Diags->Report(diag::err_pch_macro_def_conflict)
530 << MacroName << Known->second.first << Existing.first;
531 }
532 return true;
533 }
534
535 // Check whether we're using predefines.
536 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
537 if (Diags) {
538 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
539 }
540 return true;
541 }
542
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000543 // Detailed record is important since it is used for the module cache hash.
544 if (LangOpts.Modules &&
545 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
546 if (Diags) {
547 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
548 }
549 return true;
550 }
551
Guy Benyei11169dd2012-12-18 14:30:41 +0000552 // Compute the #include and #include_macros lines we need.
553 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
554 StringRef File = ExistingPPOpts.Includes[I];
555 if (File == ExistingPPOpts.ImplicitPCHInclude)
556 continue;
557
558 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
559 != PPOpts.Includes.end())
560 continue;
561
562 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000563 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000564 SuggestedPredefines += "\"\n";
565 }
566
567 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
568 StringRef File = ExistingPPOpts.MacroIncludes[I];
569 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
570 File)
571 != PPOpts.MacroIncludes.end())
572 continue;
573
574 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000575 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000576 SuggestedPredefines += "\"\n##\n";
577 }
578
579 return false;
580}
581
582bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
583 bool Complain,
584 std::string &SuggestedPredefines) {
585 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
586
587 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000588 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000589 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000590 SuggestedPredefines,
591 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000592}
593
Guy Benyei11169dd2012-12-18 14:30:41 +0000594void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
595 PP.setCounterValue(Value);
596}
597
598//===----------------------------------------------------------------------===//
599// AST reader implementation
600//===----------------------------------------------------------------------===//
601
Nico Weber824285e2014-05-08 04:26:47 +0000602void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
603 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000604 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000605 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000606}
607
608
609
610unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
611 return serialization::ComputeHash(Sel);
612}
613
614
615std::pair<unsigned, unsigned>
616ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000617 using namespace llvm::support;
618 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
619 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000620 return std::make_pair(KeyLen, DataLen);
621}
622
623ASTSelectorLookupTrait::internal_key_type
624ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000625 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000626 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000627 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
628 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
629 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000630 if (N == 0)
631 return SelTable.getNullarySelector(FirstII);
632 else if (N == 1)
633 return SelTable.getUnarySelector(FirstII);
634
635 SmallVector<IdentifierInfo *, 16> Args;
636 Args.push_back(FirstII);
637 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000638 Args.push_back(Reader.getLocalIdentifier(
639 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000640
641 return SelTable.getSelector(N, Args.data());
642}
643
644ASTSelectorLookupTrait::data_type
645ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
646 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000647 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000648
649 data_type Result;
650
Justin Bogner57ba0b22014-03-28 22:03:24 +0000651 Result.ID = Reader.getGlobalSelectorID(
652 F, endian::readNext<uint32_t, little, unaligned>(d));
653 unsigned NumInstanceMethodsAndBits =
654 endian::readNext<uint16_t, little, unaligned>(d);
655 unsigned NumFactoryMethodsAndBits =
656 endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +0000657 Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
658 Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
659 unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
660 unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
Guy Benyei11169dd2012-12-18 14:30:41 +0000661
662 // Load instance methods
663 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000664 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
665 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000666 Result.Instance.push_back(Method);
667 }
668
669 // Load factory methods
670 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000671 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
672 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000673 Result.Factory.push_back(Method);
674 }
675
676 return Result;
677}
678
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000679unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
680 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000681}
682
683std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000684ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000685 using namespace llvm::support;
686 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
687 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000688 return std::make_pair(KeyLen, DataLen);
689}
690
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000691ASTIdentifierLookupTraitBase::internal_key_type
692ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000693 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000694 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000695}
696
Douglas Gregordcf25082013-02-11 18:16:18 +0000697/// \brief Whether the given identifier is "interesting".
698static bool isInterestingIdentifier(IdentifierInfo &II) {
699 return II.isPoisoned() ||
700 II.isExtensionToken() ||
701 II.getObjCOrBuiltinID() ||
702 II.hasRevertedTokenIDToIdentifier() ||
703 II.hadMacroDefinition() ||
704 II.getFETokenInfo<void>();
705}
706
Guy Benyei11169dd2012-12-18 14:30:41 +0000707IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
708 const unsigned char* d,
709 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000710 using namespace llvm::support;
711 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000712 bool IsInteresting = RawID & 0x01;
713
714 // Wipe out the "is interesting" bit.
715 RawID = RawID >> 1;
716
717 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
718 if (!IsInteresting) {
719 // For uninteresting identifiers, just build the IdentifierInfo
720 // and associate it with the persistent ID.
721 IdentifierInfo *II = KnownII;
722 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000723 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000724 KnownII = II;
725 }
726 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000727 if (!II->isFromAST()) {
728 bool WasInteresting = isInterestingIdentifier(*II);
729 II->setIsFromAST();
730 if (WasInteresting)
731 II->setChangedSinceDeserialization();
732 }
733 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000734 return II;
735 }
736
Justin Bogner57ba0b22014-03-28 22:03:24 +0000737 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
738 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000739 bool CPlusPlusOperatorKeyword = Bits & 0x01;
740 Bits >>= 1;
741 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
742 Bits >>= 1;
743 bool Poisoned = Bits & 0x01;
744 Bits >>= 1;
745 bool ExtensionToken = Bits & 0x01;
746 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000747 bool hasSubmoduleMacros = Bits & 0x01;
748 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000749 bool hadMacroDefinition = Bits & 0x01;
750 Bits >>= 1;
751
752 assert(Bits == 0 && "Extra bits in the identifier?");
753 DataLen -= 8;
754
755 // Build the IdentifierInfo itself and link the identifier ID with
756 // the new IdentifierInfo.
757 IdentifierInfo *II = KnownII;
758 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000759 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000760 KnownII = II;
761 }
762 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000763 if (!II->isFromAST()) {
764 bool WasInteresting = isInterestingIdentifier(*II);
765 II->setIsFromAST();
766 if (WasInteresting)
767 II->setChangedSinceDeserialization();
768 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000769
770 // Set or check the various bits in the IdentifierInfo structure.
771 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000772 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000773 II->RevertTokenIDToIdentifier();
774 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
775 assert(II->isExtensionToken() == ExtensionToken &&
776 "Incorrect extension token flag");
777 (void)ExtensionToken;
778 if (Poisoned)
779 II->setIsPoisoned(true);
780 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
781 "Incorrect C++ operator keyword flag");
782 (void)CPlusPlusOperatorKeyword;
783
784 // If this identifier is a macro, deserialize the macro
785 // definition.
786 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000787 uint32_t MacroDirectivesOffset =
788 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000789 DataLen -= 4;
790 SmallVector<uint32_t, 8> LocalMacroIDs;
791 if (hasSubmoduleMacros) {
Richard Smithdaa69e02014-07-25 04:40:03 +0000792 while (true) {
793 uint32_t LocalMacroID =
794 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000795 DataLen -= 4;
Richard Smithdaa69e02014-07-25 04:40:03 +0000796 if (LocalMacroID == 0xdeadbeef) break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000797 LocalMacroIDs.push_back(LocalMacroID);
798 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000799 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000800
Richard Smithe842a472014-10-22 02:05:46 +0000801 if (F.Kind == MK_ImplicitModule || F.Kind == MK_ExplicitModule) {
Richard Smith49f906a2014-03-01 00:08:04 +0000802 // Macro definitions are stored from newest to oldest, so reverse them
803 // before registering them.
804 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000805 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000806 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
807 unsigned Size = 1;
808
809 static const uint32_t HasOverridesFlag = 0x80000000U;
810 if (I + 1 != E && (I[1] & HasOverridesFlag))
811 Size += 1 + (I[1] & ~HasOverridesFlag);
812
813 MacroSizes.push_back(Size);
814 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000815 }
Richard Smith49f906a2014-03-01 00:08:04 +0000816
817 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
818 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
819 SE = MacroSizes.rend();
820 SI != SE; ++SI) {
821 I -= *SI;
822
823 uint32_t LocalMacroID = *I;
Craig Topper00bbdcf2014-06-28 23:22:23 +0000824 ArrayRef<uint32_t> Overrides;
Richard Smith49f906a2014-03-01 00:08:04 +0000825 if (*SI != 1)
826 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
827 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
828 }
829 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000830 } else {
831 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
832 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000833 }
834
835 Reader.SetIdentifierInfo(ID, II);
836
837 // Read all of the declarations visible at global scope with this
838 // name.
839 if (DataLen > 0) {
840 SmallVector<uint32_t, 4> DeclIDs;
841 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000842 DeclIDs.push_back(Reader.getGlobalDeclID(
843 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000844 Reader.SetGloballyVisibleDecls(II, DeclIDs);
845 }
846
847 return II;
848}
849
850unsigned
851ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
852 llvm::FoldingSetNodeID ID;
853 ID.AddInteger(Key.Kind);
854
855 switch (Key.Kind) {
856 case DeclarationName::Identifier:
857 case DeclarationName::CXXLiteralOperatorName:
858 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
859 break;
860 case DeclarationName::ObjCZeroArgSelector:
861 case DeclarationName::ObjCOneArgSelector:
862 case DeclarationName::ObjCMultiArgSelector:
863 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
864 break;
865 case DeclarationName::CXXOperatorName:
866 ID.AddInteger((OverloadedOperatorKind)Key.Data);
867 break;
868 case DeclarationName::CXXConstructorName:
869 case DeclarationName::CXXDestructorName:
870 case DeclarationName::CXXConversionFunctionName:
871 case DeclarationName::CXXUsingDirective:
872 break;
873 }
874
875 return ID.ComputeHash();
876}
877
878ASTDeclContextNameLookupTrait::internal_key_type
879ASTDeclContextNameLookupTrait::GetInternalKey(
880 const external_key_type& Name) const {
881 DeclNameKey Key;
882 Key.Kind = Name.getNameKind();
883 switch (Name.getNameKind()) {
884 case DeclarationName::Identifier:
885 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
886 break;
887 case DeclarationName::ObjCZeroArgSelector:
888 case DeclarationName::ObjCOneArgSelector:
889 case DeclarationName::ObjCMultiArgSelector:
890 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
891 break;
892 case DeclarationName::CXXOperatorName:
893 Key.Data = Name.getCXXOverloadedOperator();
894 break;
895 case DeclarationName::CXXLiteralOperatorName:
896 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
897 break;
898 case DeclarationName::CXXConstructorName:
899 case DeclarationName::CXXDestructorName:
900 case DeclarationName::CXXConversionFunctionName:
901 case DeclarationName::CXXUsingDirective:
902 Key.Data = 0;
903 break;
904 }
905
906 return Key;
907}
908
909std::pair<unsigned, unsigned>
910ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000911 using namespace llvm::support;
912 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
913 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000914 return std::make_pair(KeyLen, DataLen);
915}
916
917ASTDeclContextNameLookupTrait::internal_key_type
918ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000919 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000920
921 DeclNameKey Key;
922 Key.Kind = (DeclarationName::NameKind)*d++;
923 switch (Key.Kind) {
924 case DeclarationName::Identifier:
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::ObjCZeroArgSelector:
929 case DeclarationName::ObjCOneArgSelector:
930 case DeclarationName::ObjCMultiArgSelector:
931 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000932 (uint64_t)Reader.getLocalSelector(
933 F, endian::readNext<uint32_t, little, unaligned>(
934 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000935 break;
936 case DeclarationName::CXXOperatorName:
937 Key.Data = *d++; // OverloadedOperatorKind
938 break;
939 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000940 Key.Data = (uint64_t)Reader.getLocalIdentifier(
941 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000942 break;
943 case DeclarationName::CXXConstructorName:
944 case DeclarationName::CXXDestructorName:
945 case DeclarationName::CXXConversionFunctionName:
946 case DeclarationName::CXXUsingDirective:
947 Key.Data = 0;
948 break;
949 }
950
951 return Key;
952}
953
954ASTDeclContextNameLookupTrait::data_type
955ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
956 const unsigned char* d,
957 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000958 using namespace llvm::support;
959 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000960 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
961 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000962 return std::make_pair(Start, Start + NumDecls);
963}
964
965bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000966 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000967 const std::pair<uint64_t, uint64_t> &Offsets,
968 DeclContextInfo &Info) {
969 SavedStreamPosition SavedPosition(Cursor);
970 // First the lexical decls.
971 if (Offsets.first != 0) {
972 Cursor.JumpToBit(Offsets.first);
973
974 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000975 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000976 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000977 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000978 if (RecCode != DECL_CONTEXT_LEXICAL) {
979 Error("Expected lexical block");
980 return true;
981 }
982
Chris Lattner0e6c9402013-01-20 02:38:54 +0000983 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
984 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000985 }
986
987 // Now the lookup table.
988 if (Offsets.second != 0) {
989 Cursor.JumpToBit(Offsets.second);
990
991 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000992 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000993 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000994 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000995 if (RecCode != DECL_CONTEXT_VISIBLE) {
996 Error("Expected visible lookup table block");
997 return true;
998 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000999 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
1000 (const unsigned char *)Blob.data() + Record[0],
1001 (const unsigned char *)Blob.data() + sizeof(uint32_t),
1002 (const unsigned char *)Blob.data(),
1003 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +00001004 }
1005
1006 return false;
1007}
1008
1009void ASTReader::Error(StringRef Msg) {
1010 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +00001011 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
1012 Diag(diag::note_module_cache_path)
1013 << PP.getHeaderSearchInfo().getModuleCachePath();
1014 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001015}
1016
1017void ASTReader::Error(unsigned DiagID,
1018 StringRef Arg1, StringRef Arg2) {
1019 if (Diags.isDiagnosticInFlight())
1020 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1021 else
1022 Diag(DiagID) << Arg1 << Arg2;
1023}
1024
1025//===----------------------------------------------------------------------===//
1026// Source Manager Deserialization
1027//===----------------------------------------------------------------------===//
1028
1029/// \brief Read the line table in the source manager block.
1030/// \returns true if there was an error.
1031bool ASTReader::ParseLineTable(ModuleFile &F,
1032 SmallVectorImpl<uint64_t> &Record) {
1033 unsigned Idx = 0;
1034 LineTableInfo &LineTable = SourceMgr.getLineTable();
1035
1036 // Parse the file names
1037 std::map<int, int> FileIDs;
1038 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1039 // Extract the file name
1040 unsigned FilenameLen = Record[Idx++];
1041 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
1042 Idx += FilenameLen;
1043 MaybeAddSystemRootToFilename(F, Filename);
1044 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1045 }
1046
1047 // Parse the line entries
1048 std::vector<LineEntry> Entries;
1049 while (Idx < Record.size()) {
1050 int FID = Record[Idx++];
1051 assert(FID >= 0 && "Serialized line entries for non-local file.");
1052 // Remap FileID from 1-based old view.
1053 FID += F.SLocEntryBaseID - 1;
1054
1055 // Extract the line entries
1056 unsigned NumEntries = Record[Idx++];
1057 assert(NumEntries && "Numentries is 00000");
1058 Entries.clear();
1059 Entries.reserve(NumEntries);
1060 for (unsigned I = 0; I != NumEntries; ++I) {
1061 unsigned FileOffset = Record[Idx++];
1062 unsigned LineNo = Record[Idx++];
1063 int FilenameID = FileIDs[Record[Idx++]];
1064 SrcMgr::CharacteristicKind FileKind
1065 = (SrcMgr::CharacteristicKind)Record[Idx++];
1066 unsigned IncludeOffset = Record[Idx++];
1067 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1068 FileKind, IncludeOffset));
1069 }
1070 LineTable.AddEntry(FileID::get(FID), Entries);
1071 }
1072
1073 return false;
1074}
1075
1076/// \brief Read a source manager block
1077bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1078 using namespace SrcMgr;
1079
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001080 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001081
1082 // Set the source-location entry cursor to the current position in
1083 // the stream. This cursor will be used to read the contents of the
1084 // source manager block initially, and then lazily read
1085 // source-location entries as needed.
1086 SLocEntryCursor = F.Stream;
1087
1088 // The stream itself is going to skip over the source manager block.
1089 if (F.Stream.SkipBlock()) {
1090 Error("malformed block record in AST file");
1091 return true;
1092 }
1093
1094 // Enter the source manager block.
1095 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1096 Error("malformed source manager block record in AST file");
1097 return true;
1098 }
1099
1100 RecordData Record;
1101 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001102 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1103
1104 switch (E.Kind) {
1105 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1106 case llvm::BitstreamEntry::Error:
1107 Error("malformed block record in AST file");
1108 return true;
1109 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001110 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001111 case llvm::BitstreamEntry::Record:
1112 // The interesting case.
1113 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001114 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001115
Guy Benyei11169dd2012-12-18 14:30:41 +00001116 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001117 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001118 StringRef Blob;
1119 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001120 default: // Default behavior: ignore.
1121 break;
1122
1123 case SM_SLOC_FILE_ENTRY:
1124 case SM_SLOC_BUFFER_ENTRY:
1125 case SM_SLOC_EXPANSION_ENTRY:
1126 // Once we hit one of the source location entries, we're done.
1127 return false;
1128 }
1129 }
1130}
1131
1132/// \brief If a header file is not found at the path that we expect it to be
1133/// and the PCH file was moved from its original location, try to resolve the
1134/// file by assuming that header+PCH were moved together and the header is in
1135/// the same place relative to the PCH.
1136static std::string
1137resolveFileRelativeToOriginalDir(const std::string &Filename,
1138 const std::string &OriginalDir,
1139 const std::string &CurrDir) {
1140 assert(OriginalDir != CurrDir &&
1141 "No point trying to resolve the file if the PCH dir didn't change");
1142 using namespace llvm::sys;
1143 SmallString<128> filePath(Filename);
1144 fs::make_absolute(filePath);
1145 assert(path::is_absolute(OriginalDir));
1146 SmallString<128> currPCHPath(CurrDir);
1147
1148 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1149 fileDirE = path::end(path::parent_path(filePath));
1150 path::const_iterator origDirI = path::begin(OriginalDir),
1151 origDirE = path::end(OriginalDir);
1152 // Skip the common path components from filePath and OriginalDir.
1153 while (fileDirI != fileDirE && origDirI != origDirE &&
1154 *fileDirI == *origDirI) {
1155 ++fileDirI;
1156 ++origDirI;
1157 }
1158 for (; origDirI != origDirE; ++origDirI)
1159 path::append(currPCHPath, "..");
1160 path::append(currPCHPath, fileDirI, fileDirE);
1161 path::append(currPCHPath, path::filename(Filename));
1162 return currPCHPath.str();
1163}
1164
1165bool ASTReader::ReadSLocEntry(int ID) {
1166 if (ID == 0)
1167 return false;
1168
1169 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1170 Error("source location entry ID out-of-range for AST file");
1171 return true;
1172 }
1173
1174 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1175 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001176 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001177 unsigned BaseOffset = F->SLocEntryBaseOffset;
1178
1179 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001180 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1181 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001182 Error("incorrectly-formatted source location entry in AST file");
1183 return true;
1184 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001185
Guy Benyei11169dd2012-12-18 14:30:41 +00001186 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001187 StringRef Blob;
1188 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001189 default:
1190 Error("incorrectly-formatted source location entry in AST file");
1191 return true;
1192
1193 case SM_SLOC_FILE_ENTRY: {
1194 // We will detect whether a file changed and return 'Failure' for it, but
1195 // we will also try to fail gracefully by setting up the SLocEntry.
1196 unsigned InputID = Record[4];
1197 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001198 const FileEntry *File = IF.getFile();
1199 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001200
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001201 // Note that we only check if a File was returned. If it was out-of-date
1202 // we have complained but we will continue creating a FileID to recover
1203 // gracefully.
1204 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001205 return true;
1206
1207 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1208 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1209 // This is the module's main file.
1210 IncludeLoc = getImportLocation(F);
1211 }
1212 SrcMgr::CharacteristicKind
1213 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1214 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1215 ID, BaseOffset + Record[0]);
1216 SrcMgr::FileInfo &FileInfo =
1217 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1218 FileInfo.NumCreatedFIDs = Record[5];
1219 if (Record[3])
1220 FileInfo.setHasLineDirectives();
1221
1222 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1223 unsigned NumFileDecls = Record[7];
1224 if (NumFileDecls) {
1225 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1226 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1227 NumFileDecls));
1228 }
1229
1230 const SrcMgr::ContentCache *ContentCache
1231 = SourceMgr.getOrCreateContentCache(File,
1232 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1233 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1234 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1235 unsigned Code = SLocEntryCursor.ReadCode();
1236 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001237 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001238
1239 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1240 Error("AST record has invalid code");
1241 return true;
1242 }
1243
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001244 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001245 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001246 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001247 }
1248
1249 break;
1250 }
1251
1252 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001253 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001254 unsigned Offset = Record[0];
1255 SrcMgr::CharacteristicKind
1256 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1257 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001258 if (IncludeLoc.isInvalid() &&
1259 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001260 IncludeLoc = getImportLocation(F);
1261 }
1262 unsigned Code = SLocEntryCursor.ReadCode();
1263 Record.clear();
1264 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001265 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001266
1267 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1268 Error("AST record has invalid code");
1269 return true;
1270 }
1271
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001272 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1273 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001274 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001275 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001276 break;
1277 }
1278
1279 case SM_SLOC_EXPANSION_ENTRY: {
1280 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1281 SourceMgr.createExpansionLoc(SpellingLoc,
1282 ReadSourceLocation(*F, Record[2]),
1283 ReadSourceLocation(*F, Record[3]),
1284 Record[4],
1285 ID,
1286 BaseOffset + Record[0]);
1287 break;
1288 }
1289 }
1290
1291 return false;
1292}
1293
1294std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1295 if (ID == 0)
1296 return std::make_pair(SourceLocation(), "");
1297
1298 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1299 Error("source location entry ID out-of-range for AST file");
1300 return std::make_pair(SourceLocation(), "");
1301 }
1302
1303 // Find which module file this entry lands in.
1304 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001305 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001306 return std::make_pair(SourceLocation(), "");
1307
1308 // FIXME: Can we map this down to a particular submodule? That would be
1309 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001310 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001311}
1312
1313/// \brief Find the location where the module F is imported.
1314SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1315 if (F->ImportLoc.isValid())
1316 return F->ImportLoc;
1317
1318 // Otherwise we have a PCH. It's considered to be "imported" at the first
1319 // location of its includer.
1320 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001321 // Main file is the importer.
1322 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1323 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001324 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001325 return F->ImportedBy[0]->FirstLoc;
1326}
1327
1328/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1329/// specified cursor. Read the abbreviations that are at the top of the block
1330/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001331bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001332 if (Cursor.EnterSubBlock(BlockID)) {
1333 Error("malformed block record in AST file");
1334 return Failure;
1335 }
1336
1337 while (true) {
1338 uint64_t Offset = Cursor.GetCurrentBitNo();
1339 unsigned Code = Cursor.ReadCode();
1340
1341 // We expect all abbrevs to be at the start of the block.
1342 if (Code != llvm::bitc::DEFINE_ABBREV) {
1343 Cursor.JumpToBit(Offset);
1344 return false;
1345 }
1346 Cursor.ReadAbbrevRecord();
1347 }
1348}
1349
Richard Smithe40f2ba2013-08-07 21:41:30 +00001350Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001351 unsigned &Idx) {
1352 Token Tok;
1353 Tok.startToken();
1354 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1355 Tok.setLength(Record[Idx++]);
1356 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1357 Tok.setIdentifierInfo(II);
1358 Tok.setKind((tok::TokenKind)Record[Idx++]);
1359 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1360 return Tok;
1361}
1362
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001363MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001364 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001365
1366 // Keep track of where we are in the stream, then jump back there
1367 // after reading this macro.
1368 SavedStreamPosition SavedPosition(Stream);
1369
1370 Stream.JumpToBit(Offset);
1371 RecordData Record;
1372 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001373 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001374
Guy Benyei11169dd2012-12-18 14:30:41 +00001375 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001376 // Advance to the next record, but if we get to the end of the block, don't
1377 // pop it (removing all the abbreviations from the cursor) since we want to
1378 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001379 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001380 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1381
1382 switch (Entry.Kind) {
1383 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1384 case llvm::BitstreamEntry::Error:
1385 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001386 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001387 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001388 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001389 case llvm::BitstreamEntry::Record:
1390 // The interesting case.
1391 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001392 }
1393
1394 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001395 Record.clear();
1396 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001397 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001398 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001399 case PP_MACRO_DIRECTIVE_HISTORY:
1400 return Macro;
1401
Guy Benyei11169dd2012-12-18 14:30:41 +00001402 case PP_MACRO_OBJECT_LIKE:
1403 case PP_MACRO_FUNCTION_LIKE: {
1404 // If we already have a macro, that means that we've hit the end
1405 // of the definition of the macro we were looking for. We're
1406 // done.
1407 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001408 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001409
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001410 unsigned NextIndex = 1; // Skip identifier ID.
1411 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001412 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001413 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001414 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001415 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001416 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001417
Guy Benyei11169dd2012-12-18 14:30:41 +00001418 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1419 // Decode function-like macro info.
1420 bool isC99VarArgs = Record[NextIndex++];
1421 bool isGNUVarArgs = Record[NextIndex++];
1422 bool hasCommaPasting = Record[NextIndex++];
1423 MacroArgs.clear();
1424 unsigned NumArgs = Record[NextIndex++];
1425 for (unsigned i = 0; i != NumArgs; ++i)
1426 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1427
1428 // Install function-like macro info.
1429 MI->setIsFunctionLike();
1430 if (isC99VarArgs) MI->setIsC99Varargs();
1431 if (isGNUVarArgs) MI->setIsGNUVarargs();
1432 if (hasCommaPasting) MI->setHasCommaPasting();
1433 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1434 PP.getPreprocessorAllocator());
1435 }
1436
Guy Benyei11169dd2012-12-18 14:30:41 +00001437 // Remember that we saw this macro last so that we add the tokens that
1438 // form its body to it.
1439 Macro = MI;
1440
1441 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1442 Record[NextIndex]) {
1443 // We have a macro definition. Register the association
1444 PreprocessedEntityID
1445 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1446 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001447 PreprocessingRecord::PPEntityID
1448 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1449 MacroDefinition *PPDef =
1450 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1451 if (PPDef)
1452 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001453 }
1454
1455 ++NumMacrosRead;
1456 break;
1457 }
1458
1459 case PP_TOKEN: {
1460 // If we see a TOKEN before a PP_MACRO_*, then the file is
1461 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001462 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001463
John McCallf413f5e2013-05-03 00:10:13 +00001464 unsigned Idx = 0;
1465 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001466 Macro->AddTokenToBody(Tok);
1467 break;
1468 }
1469 }
1470 }
1471}
1472
1473PreprocessedEntityID
1474ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1475 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1476 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1477 assert(I != M.PreprocessedEntityRemap.end()
1478 && "Invalid index into preprocessed entity index remap");
1479
1480 return LocalID + I->second;
1481}
1482
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001483unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1484 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001485}
1486
1487HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001488HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1489 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1490 FE->getName() };
1491 return ikey;
1492}
Guy Benyei11169dd2012-12-18 14:30:41 +00001493
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001494bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1495 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001496 return false;
1497
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001498 if (strcmp(a.Filename, b.Filename) == 0)
1499 return true;
1500
Guy Benyei11169dd2012-12-18 14:30:41 +00001501 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001502 FileManager &FileMgr = Reader.getFileManager();
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001503 const FileEntry *FEA = FileMgr.getFile(a.Filename);
1504 const FileEntry *FEB = FileMgr.getFile(b.Filename);
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001505 return (FEA && FEA == FEB);
Guy Benyei11169dd2012-12-18 14:30:41 +00001506}
1507
1508std::pair<unsigned, unsigned>
1509HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001510 using namespace llvm::support;
1511 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001512 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001513 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001514}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001515
1516HeaderFileInfoTrait::internal_key_type
1517HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001518 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001519 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001520 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1521 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001522 ikey.Filename = (const char *)d;
1523 return ikey;
1524}
1525
Guy Benyei11169dd2012-12-18 14:30:41 +00001526HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001527HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001528 unsigned DataLen) {
1529 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001530 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001531 HeaderFileInfo HFI;
1532 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001533 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1534 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001535 HFI.isImport = (Flags >> 5) & 0x01;
1536 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1537 HFI.DirInfo = (Flags >> 2) & 0x03;
1538 HFI.Resolved = (Flags >> 1) & 0x01;
1539 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001540 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1541 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1542 M, endian::readNext<uint32_t, little, unaligned>(d));
1543 if (unsigned FrameworkOffset =
1544 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001545 // The framework offset is 1 greater than the actual offset,
1546 // since 0 is used as an indicator for "no framework name".
1547 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1548 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1549 }
1550
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001551 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001552 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001553 if (LocalSMID) {
1554 // This header is part of a module. Associate it with the module to enable
1555 // implicit module import.
1556 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1557 Module *Mod = Reader.getSubmodule(GlobalSMID);
1558 HFI.isModuleHeader = true;
1559 FileManager &FileMgr = Reader.getFileManager();
1560 ModuleMap &ModMap =
1561 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Richard Smith3c1a41a2014-12-02 00:08:08 +00001562 // FIXME: This is wrong. We should track the filename as written; this
1563 // information should be propagated through the SUBMODULE_HEADER etc
1564 // records rather than from here.
1565 // FIXME: We don't ever mark excluded headers.
Hans Wennborg0101b542014-12-02 02:13:09 +00001566 Module::Header H = { key.Filename, FileMgr.getFile(key.Filename) };
1567 ModMap.addHeader(Mod, H, HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001568 }
1569 }
1570
Guy Benyei11169dd2012-12-18 14:30:41 +00001571 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1572 (void)End;
1573
1574 // This HeaderFileInfo was externally loaded.
1575 HFI.External = true;
1576 return HFI;
1577}
1578
Richard Smith49f906a2014-03-01 00:08:04 +00001579void
1580ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1581 GlobalMacroID GMacID,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001582 ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001583 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Craig Toppera13603a2014-05-22 05:54:18 +00001584 SubmoduleID *OverrideData = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001585 if (!Overrides.empty()) {
1586 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1587 OverrideData[0] = Overrides.size();
1588 for (unsigned I = 0; I != Overrides.size(); ++I)
1589 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1590 }
1591 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001592}
1593
1594void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1595 ModuleFile *M,
1596 uint64_t MacroDirectivesOffset) {
1597 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1598 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001599}
1600
1601void ASTReader::ReadDefinedMacros() {
1602 // Note that we are loading defined macros.
1603 Deserializing Macros(this);
1604
1605 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1606 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001607 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001608
1609 // If there was no preprocessor block, skip this file.
1610 if (!MacroCursor.getBitStreamReader())
1611 continue;
1612
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001613 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001614 Cursor.JumpToBit((*I)->MacroStartOffset);
1615
1616 RecordData Record;
1617 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001618 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1619
1620 switch (E.Kind) {
1621 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1622 case llvm::BitstreamEntry::Error:
1623 Error("malformed block record in AST file");
1624 return;
1625 case llvm::BitstreamEntry::EndBlock:
1626 goto NextCursor;
1627
1628 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001629 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001630 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001631 default: // Default behavior: ignore.
1632 break;
1633
1634 case PP_MACRO_OBJECT_LIKE:
1635 case PP_MACRO_FUNCTION_LIKE:
1636 getLocalIdentifier(**I, Record[0]);
1637 break;
1638
1639 case PP_TOKEN:
1640 // Ignore tokens.
1641 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001642 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001643 break;
1644 }
1645 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001646 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001647 }
1648}
1649
1650namespace {
1651 /// \brief Visitor class used to look up identifirs in an AST file.
1652 class IdentifierLookupVisitor {
1653 StringRef Name;
1654 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001655 unsigned &NumIdentifierLookups;
1656 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001657 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001658
Guy Benyei11169dd2012-12-18 14:30:41 +00001659 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001660 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1661 unsigned &NumIdentifierLookups,
1662 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001663 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001664 NumIdentifierLookups(NumIdentifierLookups),
1665 NumIdentifierLookupHits(NumIdentifierLookupHits),
1666 Found()
1667 {
1668 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001669
1670 static bool visit(ModuleFile &M, void *UserData) {
1671 IdentifierLookupVisitor *This
1672 = static_cast<IdentifierLookupVisitor *>(UserData);
1673
1674 // If we've already searched this module file, skip it now.
1675 if (M.Generation <= This->PriorGeneration)
1676 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001677
Guy Benyei11169dd2012-12-18 14:30:41 +00001678 ASTIdentifierLookupTable *IdTable
1679 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1680 if (!IdTable)
1681 return false;
1682
1683 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1684 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001685 ++This->NumIdentifierLookups;
1686 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001687 if (Pos == IdTable->end())
1688 return false;
1689
1690 // Dereferencing the iterator has the effect of building the
1691 // IdentifierInfo node and populating it with the various
1692 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001693 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001694 This->Found = *Pos;
1695 return true;
1696 }
1697
1698 // \brief Retrieve the identifier info found within the module
1699 // files.
1700 IdentifierInfo *getIdentifierInfo() const { return Found; }
1701 };
1702}
1703
1704void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1705 // Note that we are loading an identifier.
1706 Deserializing AnIdentifier(this);
1707
1708 unsigned PriorGeneration = 0;
1709 if (getContext().getLangOpts().Modules)
1710 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001711
1712 // If there is a global index, look there first to determine which modules
1713 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001714 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001715 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001716 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001717 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1718 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001719 }
1720 }
1721
Douglas Gregor7211ac12013-01-25 23:32:03 +00001722 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001723 NumIdentifierLookups,
1724 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001725 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001726 markIdentifierUpToDate(&II);
1727}
1728
1729void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1730 if (!II)
1731 return;
1732
1733 II->setOutOfDate(false);
1734
1735 // Update the generation for this identifier.
1736 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001737 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001738}
1739
Richard Smith49f906a2014-03-01 00:08:04 +00001740struct ASTReader::ModuleMacroInfo {
1741 SubmoduleID SubModID;
1742 MacroInfo *MI;
1743 SubmoduleID *Overrides;
1744 // FIXME: Remove this.
1745 ModuleFile *F;
1746
1747 bool isDefine() const { return MI; }
1748
1749 SubmoduleID getSubmoduleID() const { return SubModID; }
1750
Craig Topper00bbdcf2014-06-28 23:22:23 +00001751 ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
Richard Smith49f906a2014-03-01 00:08:04 +00001752 if (!Overrides)
Craig Topper00bbdcf2014-06-28 23:22:23 +00001753 return None;
Richard Smith49f906a2014-03-01 00:08:04 +00001754 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1755 }
1756
Richard Smithdaa69e02014-07-25 04:40:03 +00001757 MacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
Richard Smith49f906a2014-03-01 00:08:04 +00001758 if (!MI)
Richard Smithdaa69e02014-07-25 04:40:03 +00001759 return PP.AllocateUndefMacroDirective(ImportLoc, SubModID,
1760 getOverriddenSubmodules());
1761 return PP.AllocateDefMacroDirective(MI, ImportLoc, SubModID,
1762 getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00001763 }
1764};
1765
1766ASTReader::ModuleMacroInfo *
1767ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1768 ModuleMacroInfo Info;
1769
1770 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1771 if (ID & 1) {
1772 // Macro undefinition.
1773 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
Craig Toppera13603a2014-05-22 05:54:18 +00001774 Info.MI = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001775 } else {
1776 // Macro definition.
1777 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1778 assert(GMacID);
1779
1780 // If this macro has already been loaded, don't do so again.
1781 // FIXME: This is highly dubious. Multiple macro definitions can have the
1782 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1783 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
Craig Toppera13603a2014-05-22 05:54:18 +00001784 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001785
1786 Info.MI = getMacro(GMacID);
1787 Info.SubModID = Info.MI->getOwningModuleID();
1788 }
1789 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1790 Info.F = PMInfo.M;
1791
1792 return new (Context) ModuleMacroInfo(Info);
1793}
1794
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001795void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1796 const PendingMacroInfo &PMInfo) {
1797 assert(II);
1798
Richard Smithe842a472014-10-22 02:05:46 +00001799 if (PMInfo.M->Kind != MK_ImplicitModule &&
1800 PMInfo.M->Kind != MK_ExplicitModule) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001801 installPCHMacroDirectives(II, *PMInfo.M,
1802 PMInfo.PCHMacroData.MacroDirectivesOffset);
1803 return;
1804 }
Richard Smith49f906a2014-03-01 00:08:04 +00001805
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001806 // Module Macro.
1807
Richard Smith49f906a2014-03-01 00:08:04 +00001808 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1809 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001810 return;
1811
Richard Smith49f906a2014-03-01 00:08:04 +00001812 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1813 if (Owner && Owner->NameVisibility == Module::Hidden) {
1814 // Macros in the owning module are hidden. Just remember this macro to
1815 // install if we make this module visible.
1816 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1817 } else {
Richard Smithdaa69e02014-07-25 04:40:03 +00001818 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001819 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001820}
1821
1822void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1823 ModuleFile &M, uint64_t Offset) {
Richard Smithe842a472014-10-22 02:05:46 +00001824 assert(M.Kind != MK_ImplicitModule && M.Kind != MK_ExplicitModule);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001825
1826 BitstreamCursor &Cursor = M.MacroCursor;
1827 SavedStreamPosition SavedPosition(Cursor);
1828 Cursor.JumpToBit(Offset);
1829
1830 llvm::BitstreamEntry Entry =
1831 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1832 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1833 Error("malformed block record in AST file");
1834 return;
1835 }
1836
1837 RecordData Record;
1838 PreprocessorRecordTypes RecType =
1839 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1840 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1841 Error("malformed block record in AST file");
1842 return;
1843 }
1844
1845 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001846 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001847 unsigned Idx = 0, N = Record.size();
1848 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001849 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001850 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001851 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1852 switch (K) {
1853 case MacroDirective::MD_Define: {
1854 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1855 MacroInfo *MI = getMacro(GMacID);
Richard Smithdaa69e02014-07-25 04:40:03 +00001856 SubmoduleID ImportedFrom = Record[Idx++];
1857 bool IsAmbiguous = Record[Idx++];
1858 llvm::SmallVector<unsigned, 4> Overrides;
1859 if (ImportedFrom) {
1860 Overrides.insert(Overrides.end(),
1861 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1862 Idx += Overrides.size() + 1;
1863 }
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001864 DefMacroDirective *DefMD =
Richard Smithdaa69e02014-07-25 04:40:03 +00001865 PP.AllocateDefMacroDirective(MI, Loc, ImportedFrom, Overrides);
1866 DefMD->setAmbiguous(IsAmbiguous);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001867 MD = DefMD;
1868 break;
1869 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001870 case MacroDirective::MD_Undefine: {
1871 SubmoduleID ImportedFrom = Record[Idx++];
1872 llvm::SmallVector<unsigned, 4> Overrides;
1873 if (ImportedFrom) {
1874 Overrides.insert(Overrides.end(),
1875 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1876 Idx += Overrides.size() + 1;
1877 }
1878 MD = PP.AllocateUndefMacroDirective(Loc, ImportedFrom, Overrides);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001879 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001880 }
1881 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001882 bool isPublic = Record[Idx++];
1883 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1884 break;
1885 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001886
1887 if (!Latest)
1888 Latest = MD;
1889 if (Earliest)
1890 Earliest->setPrevious(MD);
1891 Earliest = MD;
1892 }
1893
1894 PP.setLoadedMacroDirective(II, Latest);
1895}
1896
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001897/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001898/// modules.
1899static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001900 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001901 assert(PrevMI && NewMI);
Craig Toppera13603a2014-05-22 05:54:18 +00001902 Module *PrevOwner = nullptr;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001903 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1904 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001905 SourceManager &SrcMgr = Reader.getSourceManager();
1906 bool PrevInSystem
1907 = PrevOwner? PrevOwner->IsSystem
1908 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1909 bool NewInSystem
1910 = NewOwner? NewOwner->IsSystem
1911 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1912 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001913 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001914 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001915}
1916
Richard Smith49f906a2014-03-01 00:08:04 +00001917void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001918 SourceLocation ImportLoc,
Richard Smith49f906a2014-03-01 00:08:04 +00001919 AmbiguousMacros &Ambig,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001920 ArrayRef<SubmoduleID> Overrides) {
Richard Smith49f906a2014-03-01 00:08:04 +00001921 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1922 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001923
Richard Smith49f906a2014-03-01 00:08:04 +00001924 // If this macro is not yet visible, remove it from the hidden names list.
Richard Smithbb853c72014-08-13 01:23:33 +00001925 // It won't be there if we're in the middle of making the owner visible.
Richard Smith49f906a2014-03-01 00:08:04 +00001926 Module *Owner = getSubmodule(OwnerID);
Richard Smithbb853c72014-08-13 01:23:33 +00001927 auto HiddenIt = HiddenNamesMap.find(Owner);
1928 if (HiddenIt != HiddenNamesMap.end()) {
1929 HiddenNames &Hidden = HiddenIt->second;
1930 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1931 if (HI != Hidden.HiddenMacros.end()) {
1932 // Register the macro now so we don't lose it when we re-export.
1933 PP.appendMacroDirective(II, HI->second->import(PP, ImportLoc));
Richard Smithdaa69e02014-07-25 04:40:03 +00001934
Richard Smithbb853c72014-08-13 01:23:33 +00001935 auto SubOverrides = HI->second->getOverriddenSubmodules();
1936 Hidden.HiddenMacros.erase(HI);
1937 removeOverriddenMacros(II, ImportLoc, Ambig, SubOverrides);
1938 }
Richard Smith49f906a2014-03-01 00:08:04 +00001939 }
1940
1941 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001942 Ambig.erase(
1943 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1944 return MD->getInfo()->getOwningModuleID() == OwnerID;
1945 }),
1946 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001947 }
1948}
1949
1950ASTReader::AmbiguousMacros *
1951ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001952 SourceLocation ImportLoc,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001953 ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001954 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001955 if (!Prev && Overrides.empty())
Craig Toppera13603a2014-05-22 05:54:18 +00001956 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001957
Craig Toppera13603a2014-05-22 05:54:18 +00001958 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective()
1959 : nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001960 if (PrevDef && PrevDef->isAmbiguous()) {
1961 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1962 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1963 Ambig.push_back(PrevDef);
1964
Richard Smithdaa69e02014-07-25 04:40:03 +00001965 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001966
1967 if (!Ambig.empty())
1968 return &Ambig;
1969
1970 AmbiguousMacroDefs.erase(II);
1971 } else {
1972 // There's no ambiguity yet. Maybe we're introducing one.
Benjamin Kramer834652a2014-05-03 18:44:26 +00001973 AmbiguousMacros Ambig;
Richard Smith49f906a2014-03-01 00:08:04 +00001974 if (PrevDef)
1975 Ambig.push_back(PrevDef);
1976
Richard Smithdaa69e02014-07-25 04:40:03 +00001977 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001978
1979 if (!Ambig.empty()) {
1980 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
Benjamin Kramer834652a2014-05-03 18:44:26 +00001981 std::swap(Result, Ambig);
Richard Smith49f906a2014-03-01 00:08:04 +00001982 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001983 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001984 }
Richard Smith49f906a2014-03-01 00:08:04 +00001985
1986 // We ended up with no ambiguity.
Craig Toppera13603a2014-05-22 05:54:18 +00001987 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001988}
1989
1990void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
Richard Smithdaa69e02014-07-25 04:40:03 +00001991 Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00001992 assert(II && Owner);
1993
1994 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
Richard Smithdaa69e02014-07-25 04:40:03 +00001995 if (ImportLoc.isInvalid()) {
Richard Smith49f906a2014-03-01 00:08:04 +00001996 // FIXME: If we made macros from this module visible but didn't provide a
1997 // source location for the import, we don't have a location for the macro.
1998 // Use the location at which the containing module file was first imported
1999 // for now.
2000 ImportLoc = MMI->F->DirectImportLoc;
Richard Smith56be7542014-03-21 00:33:59 +00002001 assert(ImportLoc.isValid() && "no import location for a visible macro?");
Richard Smith49f906a2014-03-01 00:08:04 +00002002 }
2003
Benjamin Kramer834652a2014-05-03 18:44:26 +00002004 AmbiguousMacros *Prev =
Richard Smithdaa69e02014-07-25 04:40:03 +00002005 removeOverriddenMacros(II, ImportLoc, MMI->getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00002006
Richard Smith49f906a2014-03-01 00:08:04 +00002007 // Create a synthetic macro definition corresponding to the import (or null
2008 // if this was an undefinition of the macro).
Richard Smithdaa69e02014-07-25 04:40:03 +00002009 MacroDirective *Imported = MMI->import(PP, ImportLoc);
2010 DefMacroDirective *MD = dyn_cast<DefMacroDirective>(Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002011
2012 // If there's no ambiguity, just install the macro.
2013 if (!Prev) {
Richard Smithdaa69e02014-07-25 04:40:03 +00002014 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002015 return;
2016 }
2017 assert(!Prev->empty());
2018
2019 if (!MD) {
2020 // We imported a #undef that didn't remove all prior definitions. The most
2021 // recent prior definition remains, and we install it in the place of the
Richard Smithdaa69e02014-07-25 04:40:03 +00002022 // imported directive, as if by a local #pragma pop_macro.
Richard Smith49f906a2014-03-01 00:08:04 +00002023 MacroInfo *NewMI = Prev->back()->getInfo();
2024 Prev->pop_back();
Richard Smithdaa69e02014-07-25 04:40:03 +00002025 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc);
2026
2027 // Install our #undef first so that we don't lose track of it. We'll replace
2028 // this with whichever macro definition ends up winning.
2029 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002030 }
2031
2032 // We're introducing a macro definition that creates or adds to an ambiguity.
2033 // We can resolve that ambiguity if this macro is token-for-token identical to
2034 // all of the existing definitions.
2035 MacroInfo *NewMI = MD->getInfo();
2036 assert(NewMI && "macro definition with no MacroInfo?");
2037 while (!Prev->empty()) {
2038 MacroInfo *PrevMI = Prev->back()->getInfo();
2039 assert(PrevMI && "macro definition with no MacroInfo?");
2040
2041 // Before marking the macros as ambiguous, check if this is a case where
2042 // both macros are in system headers. If so, we trust that the system
2043 // did not get it wrong. This also handles cases where Clang's own
2044 // headers have a different spelling of certain system macros:
2045 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
2046 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
2047 //
2048 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
2049 // overrides the system limits.h's macros, so there's no conflict here.
2050 if (NewMI != PrevMI &&
2051 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
2052 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
2053 break;
2054
2055 // The previous definition is the same as this one (or both are defined in
2056 // system modules so we can assume they're equivalent); we don't need to
2057 // track it any more.
2058 Prev->pop_back();
2059 }
2060
2061 if (!Prev->empty())
2062 MD->setAmbiguous(true);
2063
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002064 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002065}
2066
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002067ASTReader::InputFileInfo
2068ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002069 // Go find this input file.
2070 BitstreamCursor &Cursor = F.InputFilesCursor;
2071 SavedStreamPosition SavedPosition(Cursor);
2072 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2073
2074 unsigned Code = Cursor.ReadCode();
2075 RecordData Record;
2076 StringRef Blob;
2077
2078 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2079 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2080 "invalid record type for input file");
2081 (void)Result;
2082
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002083 std::string Filename;
2084 off_t StoredSize;
2085 time_t StoredTime;
2086 bool Overridden;
2087
Ben Langmuir198c1682014-03-07 07:27:49 +00002088 assert(Record[0] == ID && "Bogus stored ID or offset");
2089 StoredSize = static_cast<off_t>(Record[1]);
2090 StoredTime = static_cast<time_t>(Record[2]);
2091 Overridden = static_cast<bool>(Record[3]);
2092 Filename = Blob;
2093 MaybeAddSystemRootToFilename(F, Filename);
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002094
Hans Wennborg73945142014-03-14 17:45:06 +00002095 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
2096 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002097}
2098
2099std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002100 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00002101}
2102
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002103InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002104 // If this ID is bogus, just return an empty input file.
2105 if (ID == 0 || ID > F.InputFilesLoaded.size())
2106 return InputFile();
2107
2108 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002109 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002110 return F.InputFilesLoaded[ID-1];
2111
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002112 if (F.InputFilesLoaded[ID-1].isNotFound())
2113 return InputFile();
2114
Guy Benyei11169dd2012-12-18 14:30:41 +00002115 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002116 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002117 SavedStreamPosition SavedPosition(Cursor);
2118 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2119
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002120 InputFileInfo FI = readInputFileInfo(F, ID);
2121 off_t StoredSize = FI.StoredSize;
2122 time_t StoredTime = FI.StoredTime;
2123 bool Overridden = FI.Overridden;
2124 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002125
Ben Langmuir198c1682014-03-07 07:27:49 +00002126 const FileEntry *File
2127 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
2128 : FileMgr.getFile(Filename, /*OpenFile=*/false);
2129
2130 // If we didn't find the file, resolve it relative to the
2131 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002132 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002133 F.OriginalDir != CurrentDir) {
2134 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2135 F.OriginalDir,
2136 CurrentDir);
2137 if (!Resolved.empty())
2138 File = FileMgr.getFile(Resolved);
2139 }
2140
2141 // For an overridden file, create a virtual file with the stored
2142 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00002143 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002144 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2145 }
2146
Craig Toppera13603a2014-05-22 05:54:18 +00002147 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002148 if (Complain) {
2149 std::string ErrorStr = "could not find file '";
2150 ErrorStr += Filename;
2151 ErrorStr += "' referenced by AST file";
2152 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00002153 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002154 // Record that we didn't find the file.
2155 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2156 return InputFile();
2157 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002158
Ben Langmuir198c1682014-03-07 07:27:49 +00002159 // Check if there was a request to override the contents of the file
2160 // that was part of the precompiled header. Overridding such a file
2161 // can lead to problems when lexing using the source locations from the
2162 // PCH.
2163 SourceManager &SM = getSourceManager();
2164 if (!Overridden && SM.isFileOverridden(File)) {
2165 if (Complain)
2166 Error(diag::err_fe_pch_file_overridden, Filename);
2167 // After emitting the diagnostic, recover by disabling the override so
2168 // that the original file will be used.
2169 SM.disableFileContentsOverride(File);
2170 // The FileEntry is a virtual file entry with the size of the contents
2171 // that would override the original contents. Set it to the original's
2172 // size/time.
2173 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2174 StoredSize, StoredTime);
2175 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002176
Ben Langmuir198c1682014-03-07 07:27:49 +00002177 bool IsOutOfDate = false;
2178
2179 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002180 if (!Overridden && //
2181 (StoredSize != File->getSize() ||
2182#if defined(LLVM_ON_WIN32)
2183 false
2184#else
Ben Langmuir198c1682014-03-07 07:27:49 +00002185 // In our regression testing, the Windows file system seems to
2186 // have inconsistent modification times that sometimes
2187 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00002188 //
2189 // This also happens in networked file systems, so disable this
2190 // check if validation is disabled or if we have an explicitly
2191 // built PCM file.
2192 //
2193 // FIXME: Should we also do this for PCH files? They could also
2194 // reasonably get shared across a network during a distributed build.
2195 (StoredTime != File->getModificationTime() && !DisableValidation &&
2196 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00002197#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002198 )) {
2199 if (Complain) {
2200 // Build a list of the PCH imports that got us here (in reverse).
2201 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2202 while (ImportStack.back()->ImportedBy.size() > 0)
2203 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002204
Ben Langmuir198c1682014-03-07 07:27:49 +00002205 // The top-level PCH is stale.
2206 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2207 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002208
Ben Langmuir198c1682014-03-07 07:27:49 +00002209 // Print the import stack.
2210 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2211 Diag(diag::note_pch_required_by)
2212 << Filename << ImportStack[0]->FileName;
2213 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002214 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002215 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002216 }
2217
Ben Langmuir198c1682014-03-07 07:27:49 +00002218 if (!Diags.isDiagnosticInFlight())
2219 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002220 }
2221
Ben Langmuir198c1682014-03-07 07:27:49 +00002222 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002223 }
2224
Ben Langmuir198c1682014-03-07 07:27:49 +00002225 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2226
2227 // Note that we've loaded this input file.
2228 F.InputFilesLoaded[ID-1] = IF;
2229 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002230}
2231
2232const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
2233 ModuleFile &M = ModuleMgr.getPrimaryModule();
2234 std::string Filename = filenameStrRef;
2235 MaybeAddSystemRootToFilename(M, Filename);
2236 const FileEntry *File = FileMgr.getFile(Filename);
Craig Toppera13603a2014-05-22 05:54:18 +00002237 if (File == nullptr && !M.OriginalDir.empty() && !CurrentDir.empty() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002238 M.OriginalDir != CurrentDir) {
2239 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
2240 M.OriginalDir,
2241 CurrentDir);
2242 if (!resolved.empty())
2243 File = FileMgr.getFile(resolved);
2244 }
2245
2246 return File;
2247}
2248
2249/// \brief If we are loading a relocatable PCH file, and the filename is
2250/// not an absolute path, add the system root to the beginning of the file
2251/// name.
2252void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
2253 std::string &Filename) {
2254 // If this is not a relocatable PCH file, there's nothing to do.
2255 if (!M.RelocatablePCH)
2256 return;
2257
2258 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2259 return;
2260
2261 if (isysroot.empty()) {
2262 // If no system root was given, default to '/'
2263 Filename.insert(Filename.begin(), '/');
2264 return;
2265 }
2266
2267 unsigned Length = isysroot.size();
2268 if (isysroot[Length - 1] != '/')
2269 Filename.insert(Filename.begin(), '/');
2270
2271 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
2272}
2273
2274ASTReader::ASTReadResult
2275ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002276 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002277 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002278 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002279 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002280
2281 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2282 Error("malformed block record in AST file");
2283 return Failure;
2284 }
2285
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002286 // Should we allow the configuration of the module file to differ from the
2287 // configuration of the current translation unit in a compatible way?
2288 //
2289 // FIXME: Allow this for files explicitly specified with -include-pch too.
2290 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2291
Guy Benyei11169dd2012-12-18 14:30:41 +00002292 // Read all of the records and blocks in the control block.
2293 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002294 unsigned NumInputs = 0;
2295 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002296 while (1) {
2297 llvm::BitstreamEntry Entry = Stream.advance();
2298
2299 switch (Entry.Kind) {
2300 case llvm::BitstreamEntry::Error:
2301 Error("malformed block record in AST file");
2302 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002303 case llvm::BitstreamEntry::EndBlock: {
2304 // Validate input files.
2305 const HeaderSearchOptions &HSOpts =
2306 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002307
Richard Smitha1825302014-10-23 22:18:29 +00002308 // All user input files reside at the index range [0, NumUserInputs), and
2309 // system input files reside at [NumUserInputs, NumInputs).
Ben Langmuiracb803e2014-11-10 22:13:10 +00002310 if (!DisableValidation) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002311 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002312
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002313 // If we are reading a module, we will create a verification timestamp,
2314 // so we verify all input files. Otherwise, verify only user input
2315 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002316
2317 unsigned N = NumUserInputs;
2318 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002319 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002320 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002321 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002322 N = NumInputs;
2323
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002324 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002325 InputFile IF = getInputFile(F, I+1, Complain);
2326 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002327 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002328 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002329 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002330
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002331 if (Listener)
2332 Listener->visitModuleFile(F.FileName);
2333
Ben Langmuircb69b572014-03-07 06:40:32 +00002334 if (Listener && Listener->needsInputFileVisitation()) {
2335 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2336 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002337 for (unsigned I = 0; I < N; ++I) {
2338 bool IsSystem = I >= NumUserInputs;
2339 InputFileInfo FI = readInputFileInfo(F, I+1);
2340 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2341 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002342 }
2343
Guy Benyei11169dd2012-12-18 14:30:41 +00002344 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002345 }
2346
Chris Lattnere7b154b2013-01-19 21:39:22 +00002347 case llvm::BitstreamEntry::SubBlock:
2348 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002349 case INPUT_FILES_BLOCK_ID:
2350 F.InputFilesCursor = Stream;
2351 if (Stream.SkipBlock() || // Skip with the main cursor
2352 // Read the abbreviations
2353 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2354 Error("malformed block record in AST file");
2355 return Failure;
2356 }
2357 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002358
Guy Benyei11169dd2012-12-18 14:30:41 +00002359 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002360 if (Stream.SkipBlock()) {
2361 Error("malformed block record in AST file");
2362 return Failure;
2363 }
2364 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002365 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002366
2367 case llvm::BitstreamEntry::Record:
2368 // The interesting case.
2369 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002370 }
2371
2372 // Read and process a record.
2373 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002374 StringRef Blob;
2375 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002376 case METADATA: {
2377 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2378 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002379 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2380 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002381 return VersionMismatch;
2382 }
2383
2384 bool hasErrors = Record[5];
2385 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2386 Diag(diag::err_pch_with_compiler_errors);
2387 return HadErrors;
2388 }
2389
2390 F.RelocatablePCH = Record[4];
2391
2392 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002393 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002394 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2395 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002396 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002397 return VersionMismatch;
2398 }
2399 break;
2400 }
2401
Ben Langmuir487ea142014-10-23 18:05:36 +00002402 case SIGNATURE:
2403 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2404 F.Signature = Record[0];
2405 break;
2406
Guy Benyei11169dd2012-12-18 14:30:41 +00002407 case IMPORTS: {
2408 // Load each of the imported PCH files.
2409 unsigned Idx = 0, N = Record.size();
2410 while (Idx < N) {
2411 // Read information about the AST file.
2412 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2413 // The import location will be the local one for now; we will adjust
2414 // all import locations of module imports after the global source
2415 // location info are setup.
2416 SourceLocation ImportLoc =
2417 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002418 off_t StoredSize = (off_t)Record[Idx++];
2419 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002420 ASTFileSignature StoredSignature = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002421 unsigned Length = Record[Idx++];
2422 SmallString<128> ImportedFile(Record.begin() + Idx,
2423 Record.begin() + Idx + Length);
2424 Idx += Length;
2425
2426 // Load the AST file.
2427 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00002428 StoredSize, StoredModTime, StoredSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00002429 ClientLoadCapabilities)) {
2430 case Failure: return Failure;
2431 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002432 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002433 case OutOfDate: return OutOfDate;
2434 case VersionMismatch: return VersionMismatch;
2435 case ConfigurationMismatch: return ConfigurationMismatch;
2436 case HadErrors: return HadErrors;
2437 case Success: break;
2438 }
2439 }
2440 break;
2441 }
2442
2443 case LANGUAGE_OPTIONS: {
2444 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002445 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002446 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002447 ParseLanguageOptions(Record, Complain, *Listener,
2448 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002449 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002450 return ConfigurationMismatch;
2451 break;
2452 }
2453
2454 case TARGET_OPTIONS: {
2455 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2456 if (Listener && &F == *ModuleMgr.begin() &&
2457 ParseTargetOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002458 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002459 return ConfigurationMismatch;
2460 break;
2461 }
2462
2463 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002464 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002465 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002466 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002467 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002468 !DisableValidation)
2469 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002470 break;
2471 }
2472
2473 case FILE_SYSTEM_OPTIONS: {
2474 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2475 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002476 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002477 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002478 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002479 return ConfigurationMismatch;
2480 break;
2481 }
2482
2483 case HEADER_SEARCH_OPTIONS: {
2484 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2485 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002486 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002487 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002488 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002489 return ConfigurationMismatch;
2490 break;
2491 }
2492
2493 case PREPROCESSOR_OPTIONS: {
2494 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2495 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002496 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002497 ParsePreprocessorOptions(Record, Complain, *Listener,
2498 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002499 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002500 return ConfigurationMismatch;
2501 break;
2502 }
2503
2504 case ORIGINAL_FILE:
2505 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002506 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002507 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2508 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
2509 break;
2510
2511 case ORIGINAL_FILE_ID:
2512 F.OriginalSourceFileID = FileID::get(Record[0]);
2513 break;
2514
2515 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002516 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002517 break;
2518
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002519 case MODULE_NAME:
2520 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002521 if (Listener)
2522 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002523 break;
2524
2525 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002526 if (ASTReadResult Result =
2527 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2528 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002529 break;
2530
Guy Benyei11169dd2012-12-18 14:30:41 +00002531 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002532 NumInputs = Record[0];
2533 NumUserInputs = Record[1];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002534 F.InputFileOffsets = (const uint32_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002535 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002536 break;
2537 }
2538 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002539}
2540
Ben Langmuir2c9af442014-04-10 17:57:43 +00002541ASTReader::ASTReadResult
2542ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002543 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002544
2545 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2546 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002547 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002548 }
2549
2550 // Read all of the records and blocks for the AST file.
2551 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002552 while (1) {
2553 llvm::BitstreamEntry Entry = Stream.advance();
2554
2555 switch (Entry.Kind) {
2556 case llvm::BitstreamEntry::Error:
2557 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002558 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002559 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002560 // Outside of C++, we do not store a lookup map for the translation unit.
2561 // Instead, mark it as needing a lookup map to be built if this module
2562 // contains any declarations lexically within it (which it always does!).
2563 // This usually has no cost, since we very rarely need the lookup map for
2564 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002565 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002566 if (DC->hasExternalLexicalStorage() &&
2567 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002568 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002569
Ben Langmuir2c9af442014-04-10 17:57:43 +00002570 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002571 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002572 case llvm::BitstreamEntry::SubBlock:
2573 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002574 case DECLTYPES_BLOCK_ID:
2575 // We lazily load the decls block, but we want to set up the
2576 // DeclsCursor cursor to point into it. Clone our current bitcode
2577 // cursor to it, enter the block and read the abbrevs in that block.
2578 // With the main cursor, we just skip over it.
2579 F.DeclsCursor = Stream;
2580 if (Stream.SkipBlock() || // Skip with the main cursor.
2581 // Read the abbrevs.
2582 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2583 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002584 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002585 }
2586 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002587
Guy Benyei11169dd2012-12-18 14:30:41 +00002588 case PREPROCESSOR_BLOCK_ID:
2589 F.MacroCursor = Stream;
2590 if (!PP.getExternalSource())
2591 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002592
Guy Benyei11169dd2012-12-18 14:30:41 +00002593 if (Stream.SkipBlock() ||
2594 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2595 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002596 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002597 }
2598 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2599 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002600
Guy Benyei11169dd2012-12-18 14:30:41 +00002601 case PREPROCESSOR_DETAIL_BLOCK_ID:
2602 F.PreprocessorDetailCursor = Stream;
2603 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002604 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002605 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002606 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002607 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002608 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002609 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002610 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2611
Guy Benyei11169dd2012-12-18 14:30:41 +00002612 if (!PP.getPreprocessingRecord())
2613 PP.createPreprocessingRecord();
2614 if (!PP.getPreprocessingRecord()->getExternalSource())
2615 PP.getPreprocessingRecord()->SetExternalSource(*this);
2616 break;
2617
2618 case SOURCE_MANAGER_BLOCK_ID:
2619 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002620 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002621 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002622
Guy Benyei11169dd2012-12-18 14:30:41 +00002623 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002624 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2625 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002626 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002627
Guy Benyei11169dd2012-12-18 14:30:41 +00002628 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002629 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002630 if (Stream.SkipBlock() ||
2631 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2632 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002633 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002634 }
2635 CommentsCursors.push_back(std::make_pair(C, &F));
2636 break;
2637 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002638
Guy Benyei11169dd2012-12-18 14:30:41 +00002639 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002640 if (Stream.SkipBlock()) {
2641 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002642 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002643 }
2644 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002645 }
2646 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002647
2648 case llvm::BitstreamEntry::Record:
2649 // The interesting case.
2650 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002651 }
2652
2653 // Read and process a record.
2654 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002655 StringRef Blob;
2656 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002657 default: // Default behavior: ignore.
2658 break;
2659
2660 case TYPE_OFFSET: {
2661 if (F.LocalNumTypes != 0) {
2662 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002663 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002664 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002665 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002666 F.LocalNumTypes = Record[0];
2667 unsigned LocalBaseTypeIndex = Record[1];
2668 F.BaseTypeIndex = getTotalNumTypes();
2669
2670 if (F.LocalNumTypes > 0) {
2671 // Introduce the global -> local mapping for types within this module.
2672 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2673
2674 // Introduce the local -> global mapping for types within this module.
2675 F.TypeRemap.insertOrReplace(
2676 std::make_pair(LocalBaseTypeIndex,
2677 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002678
2679 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002680 }
2681 break;
2682 }
2683
2684 case DECL_OFFSET: {
2685 if (F.LocalNumDecls != 0) {
2686 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002687 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002688 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002689 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002690 F.LocalNumDecls = Record[0];
2691 unsigned LocalBaseDeclID = Record[1];
2692 F.BaseDeclID = getTotalNumDecls();
2693
2694 if (F.LocalNumDecls > 0) {
2695 // Introduce the global -> local mapping for declarations within this
2696 // module.
2697 GlobalDeclMap.insert(
2698 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2699
2700 // Introduce the local -> global mapping for declarations within this
2701 // module.
2702 F.DeclRemap.insertOrReplace(
2703 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2704
2705 // Introduce the global -> local mapping for declarations within this
2706 // module.
2707 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002708
Ben Langmuir52ca6782014-10-20 16:27:32 +00002709 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2710 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002711 break;
2712 }
2713
2714 case TU_UPDATE_LEXICAL: {
2715 DeclContext *TU = Context.getTranslationUnitDecl();
2716 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002717 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002718 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002719 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002720 TU->setHasExternalLexicalStorage(true);
2721 break;
2722 }
2723
2724 case UPDATE_VISIBLE: {
2725 unsigned Idx = 0;
2726 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2727 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002728 ASTDeclContextNameLookupTable::Create(
2729 (const unsigned char *)Blob.data() + Record[Idx++],
2730 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2731 (const unsigned char *)Blob.data(),
2732 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002733 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002734 auto *DC = cast<DeclContext>(D);
2735 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002736 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2737 delete LookupTable;
2738 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002739 } else
2740 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2741 break;
2742 }
2743
2744 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002745 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002746 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002747 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2748 (const unsigned char *)F.IdentifierTableData + Record[0],
2749 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2750 (const unsigned char *)F.IdentifierTableData,
2751 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002752
2753 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2754 }
2755 break;
2756
2757 case IDENTIFIER_OFFSET: {
2758 if (F.LocalNumIdentifiers != 0) {
2759 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002760 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002761 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002762 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002763 F.LocalNumIdentifiers = Record[0];
2764 unsigned LocalBaseIdentifierID = Record[1];
2765 F.BaseIdentifierID = getTotalNumIdentifiers();
2766
2767 if (F.LocalNumIdentifiers > 0) {
2768 // Introduce the global -> local mapping for identifiers within this
2769 // module.
2770 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2771 &F));
2772
2773 // Introduce the local -> global mapping for identifiers within this
2774 // module.
2775 F.IdentifierRemap.insertOrReplace(
2776 std::make_pair(LocalBaseIdentifierID,
2777 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002778
Ben Langmuir52ca6782014-10-20 16:27:32 +00002779 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2780 + F.LocalNumIdentifiers);
2781 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002782 break;
2783 }
2784
Ben Langmuir332aafe2014-01-31 01:06:56 +00002785 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002786 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002787 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002788 break;
2789
2790 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002791 if (SpecialTypes.empty()) {
2792 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2793 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2794 break;
2795 }
2796
2797 if (SpecialTypes.size() != Record.size()) {
2798 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002799 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002800 }
2801
2802 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2803 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2804 if (!SpecialTypes[I])
2805 SpecialTypes[I] = ID;
2806 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2807 // merge step?
2808 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002809 break;
2810
2811 case STATISTICS:
2812 TotalNumStatements += Record[0];
2813 TotalNumMacros += Record[1];
2814 TotalLexicalDeclContexts += Record[2];
2815 TotalVisibleDeclContexts += Record[3];
2816 break;
2817
2818 case UNUSED_FILESCOPED_DECLS:
2819 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2820 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2821 break;
2822
2823 case DELEGATING_CTORS:
2824 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2825 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2826 break;
2827
2828 case WEAK_UNDECLARED_IDENTIFIERS:
2829 if (Record.size() % 4 != 0) {
2830 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002831 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002832 }
2833
2834 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2835 // files. This isn't the way to do it :)
2836 WeakUndeclaredIdentifiers.clear();
2837
2838 // Translate the weak, undeclared identifiers into global IDs.
2839 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2840 WeakUndeclaredIdentifiers.push_back(
2841 getGlobalIdentifierID(F, Record[I++]));
2842 WeakUndeclaredIdentifiers.push_back(
2843 getGlobalIdentifierID(F, Record[I++]));
2844 WeakUndeclaredIdentifiers.push_back(
2845 ReadSourceLocation(F, Record, I).getRawEncoding());
2846 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2847 }
2848 break;
2849
Richard Smith78165b52013-01-10 23:43:47 +00002850 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002851 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith78165b52013-01-10 23:43:47 +00002852 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002853 break;
2854
2855 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002856 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002857 F.LocalNumSelectors = Record[0];
2858 unsigned LocalBaseSelectorID = Record[1];
2859 F.BaseSelectorID = getTotalNumSelectors();
2860
2861 if (F.LocalNumSelectors > 0) {
2862 // Introduce the global -> local mapping for selectors within this
2863 // module.
2864 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2865
2866 // Introduce the local -> global mapping for selectors within this
2867 // module.
2868 F.SelectorRemap.insertOrReplace(
2869 std::make_pair(LocalBaseSelectorID,
2870 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002871
2872 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002873 }
2874 break;
2875 }
2876
2877 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002878 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002879 if (Record[0])
2880 F.SelectorLookupTable
2881 = ASTSelectorLookupTable::Create(
2882 F.SelectorLookupTableData + Record[0],
2883 F.SelectorLookupTableData,
2884 ASTSelectorLookupTrait(*this, F));
2885 TotalNumMethodPoolEntries += Record[1];
2886 break;
2887
2888 case REFERENCED_SELECTOR_POOL:
2889 if (!Record.empty()) {
2890 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2891 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2892 Record[Idx++]));
2893 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2894 getRawEncoding());
2895 }
2896 }
2897 break;
2898
2899 case PP_COUNTER_VALUE:
2900 if (!Record.empty() && Listener)
2901 Listener->ReadCounter(F, Record[0]);
2902 break;
2903
2904 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002905 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002906 F.NumFileSortedDecls = Record[0];
2907 break;
2908
2909 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002910 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002911 F.LocalNumSLocEntries = Record[0];
2912 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002913 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002914 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002915 SLocSpaceSize);
2916 // Make our entry in the range map. BaseID is negative and growing, so
2917 // we invert it. Because we invert it, though, we need the other end of
2918 // the range.
2919 unsigned RangeStart =
2920 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2921 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2922 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2923
2924 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2925 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2926 GlobalSLocOffsetMap.insert(
2927 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2928 - SLocSpaceSize,&F));
2929
2930 // Initialize the remapping table.
2931 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002932 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002933 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002934 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002935 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2936
2937 TotalNumSLocEntries += F.LocalNumSLocEntries;
2938 break;
2939 }
2940
2941 case MODULE_OFFSET_MAP: {
2942 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002943 const unsigned char *Data = (const unsigned char*)Blob.data();
2944 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002945
2946 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2947 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2948 F.SLocRemap.insert(std::make_pair(0U, 0));
2949 F.SLocRemap.insert(std::make_pair(2U, 1));
2950 }
2951
Guy Benyei11169dd2012-12-18 14:30:41 +00002952 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002953 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2954 RemapBuilder;
2955 RemapBuilder SLocRemap(F.SLocRemap);
2956 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2957 RemapBuilder MacroRemap(F.MacroRemap);
2958 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2959 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2960 RemapBuilder SelectorRemap(F.SelectorRemap);
2961 RemapBuilder DeclRemap(F.DeclRemap);
2962 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002963
2964 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002965 using namespace llvm::support;
2966 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002967 StringRef Name = StringRef((const char*)Data, Len);
2968 Data += Len;
2969 ModuleFile *OM = ModuleMgr.lookup(Name);
2970 if (!OM) {
2971 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002972 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002973 }
2974
Justin Bogner57ba0b22014-03-28 22:03:24 +00002975 uint32_t SLocOffset =
2976 endian::readNext<uint32_t, little, unaligned>(Data);
2977 uint32_t IdentifierIDOffset =
2978 endian::readNext<uint32_t, little, unaligned>(Data);
2979 uint32_t MacroIDOffset =
2980 endian::readNext<uint32_t, little, unaligned>(Data);
2981 uint32_t PreprocessedEntityIDOffset =
2982 endian::readNext<uint32_t, little, unaligned>(Data);
2983 uint32_t SubmoduleIDOffset =
2984 endian::readNext<uint32_t, little, unaligned>(Data);
2985 uint32_t SelectorIDOffset =
2986 endian::readNext<uint32_t, little, unaligned>(Data);
2987 uint32_t DeclIDOffset =
2988 endian::readNext<uint32_t, little, unaligned>(Data);
2989 uint32_t TypeIndexOffset =
2990 endian::readNext<uint32_t, little, unaligned>(Data);
2991
Ben Langmuir785180e2014-10-20 16:27:30 +00002992 uint32_t None = std::numeric_limits<uint32_t>::max();
2993
2994 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2995 RemapBuilder &Remap) {
2996 if (Offset != None)
2997 Remap.insert(std::make_pair(Offset,
2998 static_cast<int>(BaseOffset - Offset)));
2999 };
3000 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3001 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3002 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3003 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3004 PreprocessedEntityRemap);
3005 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3006 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3007 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3008 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00003009
3010 // Global -> local mappings.
3011 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3012 }
3013 break;
3014 }
3015
3016 case SOURCE_MANAGER_LINE_TABLE:
3017 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003018 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003019 break;
3020
3021 case SOURCE_LOCATION_PRELOADS: {
3022 // Need to transform from the local view (1-based IDs) to the global view,
3023 // which is based off F.SLocEntryBaseID.
3024 if (!F.PreloadSLocEntries.empty()) {
3025 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003026 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003027 }
3028
3029 F.PreloadSLocEntries.swap(Record);
3030 break;
3031 }
3032
3033 case EXT_VECTOR_DECLS:
3034 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3035 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3036 break;
3037
3038 case VTABLE_USES:
3039 if (Record.size() % 3 != 0) {
3040 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003041 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003042 }
3043
3044 // Later tables overwrite earlier ones.
3045 // FIXME: Modules will have some trouble with this. This is clearly not
3046 // the right way to do this.
3047 VTableUses.clear();
3048
3049 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3050 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3051 VTableUses.push_back(
3052 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3053 VTableUses.push_back(Record[Idx++]);
3054 }
3055 break;
3056
3057 case DYNAMIC_CLASSES:
3058 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3059 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
3060 break;
3061
3062 case PENDING_IMPLICIT_INSTANTIATIONS:
3063 if (PendingInstantiations.size() % 2 != 0) {
3064 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003065 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003066 }
3067
3068 if (Record.size() % 2 != 0) {
3069 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003070 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003071 }
3072
3073 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3074 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3075 PendingInstantiations.push_back(
3076 ReadSourceLocation(F, Record, I).getRawEncoding());
3077 }
3078 break;
3079
3080 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00003081 if (Record.size() != 2) {
3082 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003083 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003084 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003085 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3086 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3087 break;
3088
3089 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003090 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3091 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3092 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003093
3094 unsigned LocalBasePreprocessedEntityID = Record[0];
3095
3096 unsigned StartingID;
3097 if (!PP.getPreprocessingRecord())
3098 PP.createPreprocessingRecord();
3099 if (!PP.getPreprocessingRecord()->getExternalSource())
3100 PP.getPreprocessingRecord()->SetExternalSource(*this);
3101 StartingID
3102 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003103 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003104 F.BasePreprocessedEntityID = StartingID;
3105
3106 if (F.NumPreprocessedEntities > 0) {
3107 // Introduce the global -> local mapping for preprocessed entities in
3108 // this module.
3109 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3110
3111 // Introduce the local -> global mapping for preprocessed entities in
3112 // this module.
3113 F.PreprocessedEntityRemap.insertOrReplace(
3114 std::make_pair(LocalBasePreprocessedEntityID,
3115 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3116 }
3117
3118 break;
3119 }
3120
3121 case DECL_UPDATE_OFFSETS: {
3122 if (Record.size() % 2 != 0) {
3123 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003124 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003125 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003126 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3127 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3128 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3129
3130 // If we've already loaded the decl, perform the updates when we finish
3131 // loading this block.
3132 if (Decl *D = GetExistingDecl(ID))
3133 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3134 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003135 break;
3136 }
3137
3138 case DECL_REPLACEMENTS: {
3139 if (Record.size() % 3 != 0) {
3140 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003141 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003142 }
3143 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3144 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3145 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3146 break;
3147 }
3148
3149 case OBJC_CATEGORIES_MAP: {
3150 if (F.LocalNumObjCCategoriesInMap != 0) {
3151 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003152 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003153 }
3154
3155 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003156 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003157 break;
3158 }
3159
3160 case OBJC_CATEGORIES:
3161 F.ObjCCategories.swap(Record);
3162 break;
3163
3164 case CXX_BASE_SPECIFIER_OFFSETS: {
3165 if (F.LocalNumCXXBaseSpecifiers != 0) {
3166 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003167 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003168 }
3169
3170 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003171 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003172 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
3173 break;
3174 }
3175
3176 case DIAG_PRAGMA_MAPPINGS:
3177 if (F.PragmaDiagMappings.empty())
3178 F.PragmaDiagMappings.swap(Record);
3179 else
3180 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3181 Record.begin(), Record.end());
3182 break;
3183
3184 case CUDA_SPECIAL_DECL_REFS:
3185 // Later tables overwrite earlier ones.
3186 // FIXME: Modules will have trouble with this.
3187 CUDASpecialDeclRefs.clear();
3188 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3189 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3190 break;
3191
3192 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003193 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003194 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003195 if (Record[0]) {
3196 F.HeaderFileInfoTable
3197 = HeaderFileInfoLookupTable::Create(
3198 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3199 (const unsigned char *)F.HeaderFileInfoTableData,
3200 HeaderFileInfoTrait(*this, F,
3201 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003202 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003203
3204 PP.getHeaderSearchInfo().SetExternalSource(this);
3205 if (!PP.getHeaderSearchInfo().getExternalLookup())
3206 PP.getHeaderSearchInfo().SetExternalLookup(this);
3207 }
3208 break;
3209 }
3210
3211 case FP_PRAGMA_OPTIONS:
3212 // Later tables overwrite earlier ones.
3213 FPPragmaOptions.swap(Record);
3214 break;
3215
3216 case OPENCL_EXTENSIONS:
3217 // Later tables overwrite earlier ones.
3218 OpenCLExtensions.swap(Record);
3219 break;
3220
3221 case TENTATIVE_DEFINITIONS:
3222 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3223 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3224 break;
3225
3226 case KNOWN_NAMESPACES:
3227 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3228 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3229 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003230
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003231 case UNDEFINED_BUT_USED:
3232 if (UndefinedButUsed.size() % 2 != 0) {
3233 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003234 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003235 }
3236
3237 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003238 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003239 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003240 }
3241 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003242 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3243 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003244 ReadSourceLocation(F, Record, I).getRawEncoding());
3245 }
3246 break;
3247
Guy Benyei11169dd2012-12-18 14:30:41 +00003248 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003249 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003250 // If we aren't loading a module (which has its own exports), make
3251 // all of the imported modules visible.
3252 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003253 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3254 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3255 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3256 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003257 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003258 }
3259 }
3260 break;
3261 }
3262
3263 case LOCAL_REDECLARATIONS: {
3264 F.RedeclarationChains.swap(Record);
3265 break;
3266 }
3267
3268 case LOCAL_REDECLARATIONS_MAP: {
3269 if (F.LocalNumRedeclarationsInMap != 0) {
3270 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003271 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003272 }
3273
3274 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003275 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003276 break;
3277 }
3278
3279 case MERGED_DECLARATIONS: {
3280 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3281 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3282 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3283 for (unsigned N = Record[Idx++]; N > 0; --N)
3284 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3285 }
3286 break;
3287 }
3288
3289 case MACRO_OFFSET: {
3290 if (F.LocalNumMacros != 0) {
3291 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003292 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003293 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003294 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003295 F.LocalNumMacros = Record[0];
3296 unsigned LocalBaseMacroID = Record[1];
3297 F.BaseMacroID = getTotalNumMacros();
3298
3299 if (F.LocalNumMacros > 0) {
3300 // Introduce the global -> local mapping for macros within this module.
3301 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3302
3303 // Introduce the local -> global mapping for macros within this module.
3304 F.MacroRemap.insertOrReplace(
3305 std::make_pair(LocalBaseMacroID,
3306 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003307
3308 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003309 }
3310 break;
3311 }
3312
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003313 case MACRO_TABLE: {
3314 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00003315 break;
3316 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00003317
3318 case LATE_PARSED_TEMPLATE: {
3319 LateParsedTemplates.append(Record.begin(), Record.end());
3320 break;
3321 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003322
3323 case OPTIMIZE_PRAGMA_OPTIONS:
3324 if (Record.size() != 1) {
3325 Error("invalid pragma optimize record");
3326 return Failure;
3327 }
3328 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3329 break;
Nico Weber72889432014-09-06 01:25:55 +00003330
3331 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3332 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3333 UnusedLocalTypedefNameCandidates.push_back(
3334 getGlobalDeclID(F, Record[I]));
3335 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003336 }
3337 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003338}
3339
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003340ASTReader::ASTReadResult
3341ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3342 const ModuleFile *ImportedBy,
3343 unsigned ClientLoadCapabilities) {
3344 unsigned Idx = 0;
3345 F.ModuleMapPath = ReadString(Record, Idx);
3346
Richard Smithe842a472014-10-22 02:05:46 +00003347 if (F.Kind == MK_ExplicitModule) {
3348 // For an explicitly-loaded module, we don't care whether the original
3349 // module map file exists or matches.
3350 return Success;
3351 }
3352
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003353 // Try to resolve ModuleName in the current header search context and
3354 // verify that it is found in the same module map file as we saved. If the
3355 // top-level AST file is a main file, skip this check because there is no
3356 // usable header search context.
3357 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003358 "MODULE_NAME should come before MODULE_MAP_FILE");
3359 if (F.Kind == MK_ImplicitModule &&
3360 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3361 // An implicitly-loaded module file should have its module listed in some
3362 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003363 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003364 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3365 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3366 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003367 assert(ImportedBy && "top-level import should be verified");
3368 if ((ClientLoadCapabilities & ARR_Missing) == 0)
Richard Smithe842a472014-10-22 02:05:46 +00003369 Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3370 << ImportedBy->FileName
3371 << F.ModuleMapPath;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003372 return Missing;
3373 }
3374
Richard Smithe842a472014-10-22 02:05:46 +00003375 assert(M->Name == F.ModuleName && "found module with different name");
3376
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003377 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003378 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003379 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3380 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003381 assert(ImportedBy && "top-level import should be verified");
3382 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3383 Diag(diag::err_imported_module_modmap_changed)
3384 << F.ModuleName << ImportedBy->FileName
3385 << ModMap->getName() << F.ModuleMapPath;
3386 return OutOfDate;
3387 }
3388
3389 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3390 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3391 // FIXME: we should use input files rather than storing names.
3392 std::string Filename = ReadString(Record, Idx);
3393 const FileEntry *F =
3394 FileMgr.getFile(Filename, false, false);
3395 if (F == nullptr) {
3396 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3397 Error("could not find file '" + Filename +"' referenced by AST file");
3398 return OutOfDate;
3399 }
3400 AdditionalStoredMaps.insert(F);
3401 }
3402
3403 // Check any additional module map files (e.g. module.private.modulemap)
3404 // that are not in the pcm.
3405 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3406 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3407 // Remove files that match
3408 // Note: SmallPtrSet::erase is really remove
3409 if (!AdditionalStoredMaps.erase(ModMap)) {
3410 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3411 Diag(diag::err_module_different_modmap)
3412 << F.ModuleName << /*new*/0 << ModMap->getName();
3413 return OutOfDate;
3414 }
3415 }
3416 }
3417
3418 // Check any additional module map files that are in the pcm, but not
3419 // found in header search. Cases that match are already removed.
3420 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3421 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3422 Diag(diag::err_module_different_modmap)
3423 << F.ModuleName << /*not new*/1 << ModMap->getName();
3424 return OutOfDate;
3425 }
3426 }
3427
3428 if (Listener)
3429 Listener->ReadModuleMapFile(F.ModuleMapPath);
3430 return Success;
3431}
3432
3433
Douglas Gregorc1489562013-02-12 23:36:21 +00003434/// \brief Move the given method to the back of the global list of methods.
3435static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3436 // Find the entry for this selector in the method pool.
3437 Sema::GlobalMethodPool::iterator Known
3438 = S.MethodPool.find(Method->getSelector());
3439 if (Known == S.MethodPool.end())
3440 return;
3441
3442 // Retrieve the appropriate method list.
3443 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3444 : Known->second.second;
3445 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003446 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003447 if (!Found) {
3448 if (List->Method == Method) {
3449 Found = true;
3450 } else {
3451 // Keep searching.
3452 continue;
3453 }
3454 }
3455
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003456 if (List->getNext())
3457 List->Method = List->getNext()->Method;
Douglas Gregorc1489562013-02-12 23:36:21 +00003458 else
3459 List->Method = Method;
3460 }
3461}
3462
Richard Smithe657bbd2014-07-18 22:13:40 +00003463void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner,
3464 bool FromFinalization) {
3465 // FIXME: Only do this if Owner->NameVisibility == AllVisible.
Richard Smith57721ac2014-07-21 04:10:40 +00003466 for (Decl *D : Names.HiddenDecls) {
Richard Smith49f906a2014-03-01 00:08:04 +00003467 bool wasHidden = D->Hidden;
3468 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003469
Richard Smith49f906a2014-03-01 00:08:04 +00003470 if (wasHidden && SemaObj) {
3471 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3472 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003473 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003474 }
3475 }
Richard Smith49f906a2014-03-01 00:08:04 +00003476
Richard Smithe657bbd2014-07-18 22:13:40 +00003477 assert((FromFinalization || Owner->NameVisibility >= Module::MacrosVisible) &&
3478 "nothing to make visible?");
Richard Smithdaa69e02014-07-25 04:40:03 +00003479 for (const auto &Macro : Names.HiddenMacros) {
3480 if (FromFinalization)
3481 PP.appendMacroDirective(Macro.first,
3482 Macro.second->import(PP, SourceLocation()));
3483 else
3484 installImportedMacro(Macro.first, Macro.second, Owner);
3485 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003486}
3487
Richard Smith49f906a2014-03-01 00:08:04 +00003488void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003489 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003490 SourceLocation ImportLoc,
3491 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003492 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003493 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003494 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003495 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003496 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003497
3498 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003499 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003500 // there is nothing more to do.
3501 continue;
3502 }
Richard Smith49f906a2014-03-01 00:08:04 +00003503
Guy Benyei11169dd2012-12-18 14:30:41 +00003504 if (!Mod->isAvailable()) {
3505 // Modules that aren't available cannot be made visible.
3506 continue;
3507 }
3508
3509 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003510 if (NameVisibility >= Module::MacrosVisible &&
3511 Mod->NameVisibility < Module::MacrosVisible)
3512 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003513 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003514
Guy Benyei11169dd2012-12-18 14:30:41 +00003515 // If we've already deserialized any names from this module,
3516 // mark them as visible.
3517 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3518 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003519 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003520 HiddenNamesMap.erase(Hidden);
Richard Smith57721ac2014-07-21 04:10:40 +00003521 makeNamesVisible(HiddenNames.second, HiddenNames.first,
3522 /*FromFinalization*/false);
3523 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3524 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003525 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003526
Guy Benyei11169dd2012-12-18 14:30:41 +00003527 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003528 SmallVector<Module *, 16> Exports;
3529 Mod->getExportedModules(Exports);
3530 for (SmallVectorImpl<Module *>::iterator
3531 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3532 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003533 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003534 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003535 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003536
3537 // Detect any conflicts.
3538 if (Complain) {
3539 assert(ImportLoc.isValid() && "Missing import location");
3540 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3541 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3542 Diag(ImportLoc, diag::warn_module_conflict)
3543 << Mod->getFullModuleName()
3544 << Mod->Conflicts[I].Other->getFullModuleName()
3545 << Mod->Conflicts[I].Message;
3546 // FIXME: Need note where the other module was imported.
3547 }
3548 }
3549 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003550 }
3551}
3552
Douglas Gregore060e572013-01-25 01:03:03 +00003553bool ASTReader::loadGlobalIndex() {
3554 if (GlobalIndex)
3555 return false;
3556
3557 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3558 !Context.getLangOpts().Modules)
3559 return true;
3560
3561 // Try to load the global index.
3562 TriedLoadingGlobalIndex = true;
3563 StringRef ModuleCachePath
3564 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3565 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003566 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003567 if (!Result.first)
3568 return true;
3569
3570 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003571 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003572 return false;
3573}
3574
3575bool ASTReader::isGlobalIndexUnavailable() const {
3576 return Context.getLangOpts().Modules && UseGlobalIndex &&
3577 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3578}
3579
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003580static void updateModuleTimestamp(ModuleFile &MF) {
3581 // Overwrite the timestamp file contents so that file's mtime changes.
3582 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003583 std::error_code EC;
3584 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3585 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003586 return;
3587 OS << "Timestamp file\n";
3588}
3589
Guy Benyei11169dd2012-12-18 14:30:41 +00003590ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3591 ModuleKind Type,
3592 SourceLocation ImportLoc,
3593 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003594 llvm::SaveAndRestore<SourceLocation>
3595 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3596
Richard Smithd1c46742014-04-30 02:24:17 +00003597 // Defer any pending actions until we get to the end of reading the AST file.
3598 Deserializing AnASTFile(this);
3599
Guy Benyei11169dd2012-12-18 14:30:41 +00003600 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003601 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003602
3603 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003604 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003605 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003606 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003607 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003608 ClientLoadCapabilities)) {
3609 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003610 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003611 case OutOfDate:
3612 case VersionMismatch:
3613 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003614 case HadErrors: {
3615 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3616 for (const ImportedModule &IM : Loaded)
3617 LoadedSet.insert(IM.Mod);
3618
Douglas Gregor7029ce12013-03-19 00:28:20 +00003619 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003620 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003621 Context.getLangOpts().Modules
3622 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003623 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003624
3625 // If we find that any modules are unusable, the global index is going
3626 // to be out-of-date. Just remove it.
3627 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003628 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003629 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003630 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003631 case Success:
3632 break;
3633 }
3634
3635 // Here comes stuff that we only do once the entire chain is loaded.
3636
3637 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003638 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3639 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003640 M != MEnd; ++M) {
3641 ModuleFile &F = *M->Mod;
3642
3643 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003644 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3645 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003646
3647 // Once read, set the ModuleFile bit base offset and update the size in
3648 // bits of all files we've seen.
3649 F.GlobalBitOffset = TotalModulesSizeInBits;
3650 TotalModulesSizeInBits += F.SizeInBits;
3651 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3652
3653 // Preload SLocEntries.
3654 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3655 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3656 // Load it through the SourceManager and don't call ReadSLocEntry()
3657 // directly because the entry may have already been loaded in which case
3658 // calling ReadSLocEntry() directly would trigger an assertion in
3659 // SourceManager.
3660 SourceMgr.getLoadedSLocEntryByID(Index);
3661 }
3662 }
3663
Douglas Gregor603cd862013-03-22 18:50:14 +00003664 // Setup the import locations and notify the module manager that we've
3665 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003666 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3667 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003668 M != MEnd; ++M) {
3669 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003670
3671 ModuleMgr.moduleFileAccepted(&F);
3672
3673 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003674 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003675 if (!M->ImportedBy)
3676 F.ImportLoc = M->ImportLoc;
3677 else
3678 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3679 M->ImportLoc.getRawEncoding());
3680 }
3681
3682 // Mark all of the identifiers in the identifier table as being out of date,
3683 // so that various accessors know to check the loaded modules when the
3684 // identifier is used.
3685 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3686 IdEnd = PP.getIdentifierTable().end();
3687 Id != IdEnd; ++Id)
3688 Id->second->setOutOfDate(true);
3689
3690 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003691 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3692 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003693 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3694 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003695
3696 switch (Unresolved.Kind) {
3697 case UnresolvedModuleRef::Conflict:
3698 if (ResolvedMod) {
3699 Module::Conflict Conflict;
3700 Conflict.Other = ResolvedMod;
3701 Conflict.Message = Unresolved.String.str();
3702 Unresolved.Mod->Conflicts.push_back(Conflict);
3703 }
3704 continue;
3705
3706 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003707 if (ResolvedMod)
3708 Unresolved.Mod->Imports.push_back(ResolvedMod);
3709 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003710
Douglas Gregorfb912652013-03-20 21:10:35 +00003711 case UnresolvedModuleRef::Export:
3712 if (ResolvedMod || Unresolved.IsWildcard)
3713 Unresolved.Mod->Exports.push_back(
3714 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3715 continue;
3716 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003717 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003718 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003719
3720 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3721 // Might be unnecessary as use declarations are only used to build the
3722 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003723
3724 InitializeContext();
3725
Richard Smith3d8e97e2013-10-18 06:54:39 +00003726 if (SemaObj)
3727 UpdateSema();
3728
Guy Benyei11169dd2012-12-18 14:30:41 +00003729 if (DeserializationListener)
3730 DeserializationListener->ReaderInitialized(this);
3731
3732 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3733 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3734 PrimaryModule.OriginalSourceFileID
3735 = FileID::get(PrimaryModule.SLocEntryBaseID
3736 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3737
3738 // If this AST file is a precompiled preamble, then set the
3739 // preamble file ID of the source manager to the file source file
3740 // from which the preamble was built.
3741 if (Type == MK_Preamble) {
3742 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3743 } else if (Type == MK_MainFile) {
3744 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3745 }
3746 }
3747
3748 // For any Objective-C class definitions we have already loaded, make sure
3749 // that we load any additional categories.
3750 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3751 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3752 ObjCClassesLoaded[I],
3753 PreviousGeneration);
3754 }
Douglas Gregore060e572013-01-25 01:03:03 +00003755
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003756 if (PP.getHeaderSearchInfo()
3757 .getHeaderSearchOpts()
3758 .ModulesValidateOncePerBuildSession) {
3759 // Now we are certain that the module and all modules it depends on are
3760 // up to date. Create or update timestamp files for modules that are
3761 // located in the module cache (not for PCH files that could be anywhere
3762 // in the filesystem).
3763 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3764 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003765 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003766 updateModuleTimestamp(*M.Mod);
3767 }
3768 }
3769 }
3770
Guy Benyei11169dd2012-12-18 14:30:41 +00003771 return Success;
3772}
3773
Ben Langmuir487ea142014-10-23 18:05:36 +00003774static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3775
Guy Benyei11169dd2012-12-18 14:30:41 +00003776ASTReader::ASTReadResult
3777ASTReader::ReadASTCore(StringRef FileName,
3778 ModuleKind Type,
3779 SourceLocation ImportLoc,
3780 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003781 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003782 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003783 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003784 unsigned ClientLoadCapabilities) {
3785 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003786 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003787 ModuleManager::AddModuleResult AddResult
3788 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003789 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003790 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003791 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003792
Douglas Gregor7029ce12013-03-19 00:28:20 +00003793 switch (AddResult) {
3794 case ModuleManager::AlreadyLoaded:
3795 return Success;
3796
3797 case ModuleManager::NewlyLoaded:
3798 // Load module file below.
3799 break;
3800
3801 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003802 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003803 // it.
3804 if (ClientLoadCapabilities & ARR_Missing)
3805 return Missing;
3806
3807 // Otherwise, return an error.
3808 {
3809 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3810 + ErrorStr;
3811 Error(Msg);
3812 }
3813 return Failure;
3814
3815 case ModuleManager::OutOfDate:
3816 // We couldn't load the module file because it is out-of-date. If the
3817 // client can handle out-of-date, return it.
3818 if (ClientLoadCapabilities & ARR_OutOfDate)
3819 return OutOfDate;
3820
3821 // Otherwise, return an error.
3822 {
3823 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3824 + ErrorStr;
3825 Error(Msg);
3826 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003827 return Failure;
3828 }
3829
Douglas Gregor7029ce12013-03-19 00:28:20 +00003830 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003831
3832 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3833 // module?
3834 if (FileName != "-") {
3835 CurrentDir = llvm::sys::path::parent_path(FileName);
3836 if (CurrentDir.empty()) CurrentDir = ".";
3837 }
3838
3839 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003840 BitstreamCursor &Stream = F.Stream;
Rafael Espindolafd832392014-11-12 14:48:44 +00003841 Stream.init(&F.StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003842 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3843
3844 // Sniff for the signature.
3845 if (Stream.Read(8) != 'C' ||
3846 Stream.Read(8) != 'P' ||
3847 Stream.Read(8) != 'C' ||
3848 Stream.Read(8) != 'H') {
3849 Diag(diag::err_not_a_pch_file) << FileName;
3850 return Failure;
3851 }
3852
3853 // This is used for compatibility with older PCH formats.
3854 bool HaveReadControlBlock = false;
3855
Chris Lattnerefa77172013-01-20 00:00:22 +00003856 while (1) {
3857 llvm::BitstreamEntry Entry = Stream.advance();
3858
3859 switch (Entry.Kind) {
3860 case llvm::BitstreamEntry::Error:
3861 case llvm::BitstreamEntry::EndBlock:
3862 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003863 Error("invalid record at top-level of AST file");
3864 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003865
3866 case llvm::BitstreamEntry::SubBlock:
3867 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003868 }
3869
Guy Benyei11169dd2012-12-18 14:30:41 +00003870 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003871 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003872 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3873 if (Stream.ReadBlockInfoBlock()) {
3874 Error("malformed BlockInfoBlock in AST file");
3875 return Failure;
3876 }
3877 break;
3878 case CONTROL_BLOCK_ID:
3879 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003880 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003881 case Success:
3882 break;
3883
3884 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003885 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003886 case OutOfDate: return OutOfDate;
3887 case VersionMismatch: return VersionMismatch;
3888 case ConfigurationMismatch: return ConfigurationMismatch;
3889 case HadErrors: return HadErrors;
3890 }
3891 break;
3892 case AST_BLOCK_ID:
3893 if (!HaveReadControlBlock) {
3894 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003895 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003896 return VersionMismatch;
3897 }
3898
3899 // Record that we've loaded this module.
3900 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3901 return Success;
3902
3903 default:
3904 if (Stream.SkipBlock()) {
3905 Error("malformed block record in AST file");
3906 return Failure;
3907 }
3908 break;
3909 }
3910 }
3911
3912 return Success;
3913}
3914
3915void ASTReader::InitializeContext() {
3916 // If there's a listener, notify them that we "read" the translation unit.
3917 if (DeserializationListener)
3918 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3919 Context.getTranslationUnitDecl());
3920
Guy Benyei11169dd2012-12-18 14:30:41 +00003921 // FIXME: Find a better way to deal with collisions between these
3922 // built-in types. Right now, we just ignore the problem.
3923
3924 // Load the special types.
3925 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3926 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3927 if (!Context.CFConstantStringTypeDecl)
3928 Context.setCFConstantStringType(GetType(String));
3929 }
3930
3931 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3932 QualType FileType = GetType(File);
3933 if (FileType.isNull()) {
3934 Error("FILE type is NULL");
3935 return;
3936 }
3937
3938 if (!Context.FILEDecl) {
3939 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3940 Context.setFILEDecl(Typedef->getDecl());
3941 else {
3942 const TagType *Tag = FileType->getAs<TagType>();
3943 if (!Tag) {
3944 Error("Invalid FILE type in AST file");
3945 return;
3946 }
3947 Context.setFILEDecl(Tag->getDecl());
3948 }
3949 }
3950 }
3951
3952 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3953 QualType Jmp_bufType = GetType(Jmp_buf);
3954 if (Jmp_bufType.isNull()) {
3955 Error("jmp_buf type is NULL");
3956 return;
3957 }
3958
3959 if (!Context.jmp_bufDecl) {
3960 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3961 Context.setjmp_bufDecl(Typedef->getDecl());
3962 else {
3963 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3964 if (!Tag) {
3965 Error("Invalid jmp_buf type in AST file");
3966 return;
3967 }
3968 Context.setjmp_bufDecl(Tag->getDecl());
3969 }
3970 }
3971 }
3972
3973 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3974 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3975 if (Sigjmp_bufType.isNull()) {
3976 Error("sigjmp_buf type is NULL");
3977 return;
3978 }
3979
3980 if (!Context.sigjmp_bufDecl) {
3981 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3982 Context.setsigjmp_bufDecl(Typedef->getDecl());
3983 else {
3984 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3985 assert(Tag && "Invalid sigjmp_buf type in AST file");
3986 Context.setsigjmp_bufDecl(Tag->getDecl());
3987 }
3988 }
3989 }
3990
3991 if (unsigned ObjCIdRedef
3992 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3993 if (Context.ObjCIdRedefinitionType.isNull())
3994 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3995 }
3996
3997 if (unsigned ObjCClassRedef
3998 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3999 if (Context.ObjCClassRedefinitionType.isNull())
4000 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4001 }
4002
4003 if (unsigned ObjCSelRedef
4004 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4005 if (Context.ObjCSelRedefinitionType.isNull())
4006 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4007 }
4008
4009 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4010 QualType Ucontext_tType = GetType(Ucontext_t);
4011 if (Ucontext_tType.isNull()) {
4012 Error("ucontext_t type is NULL");
4013 return;
4014 }
4015
4016 if (!Context.ucontext_tDecl) {
4017 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4018 Context.setucontext_tDecl(Typedef->getDecl());
4019 else {
4020 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4021 assert(Tag && "Invalid ucontext_t type in AST file");
4022 Context.setucontext_tDecl(Tag->getDecl());
4023 }
4024 }
4025 }
4026 }
4027
4028 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4029
4030 // If there were any CUDA special declarations, deserialize them.
4031 if (!CUDASpecialDeclRefs.empty()) {
4032 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4033 Context.setcudaConfigureCallDecl(
4034 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4035 }
Richard Smith56be7542014-03-21 00:33:59 +00004036
Guy Benyei11169dd2012-12-18 14:30:41 +00004037 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00004038 // FIXME: This does not make macro-only imports visible again. It also doesn't
4039 // make #includes mapped to module imports visible.
4040 for (auto &Import : ImportedModules) {
4041 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004042 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00004043 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00004044 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00004045 }
4046 ImportedModules.clear();
4047}
4048
4049void ASTReader::finalizeForWriting() {
Richard Smith57721ac2014-07-21 04:10:40 +00004050 while (!HiddenNamesMap.empty()) {
4051 auto HiddenNames = std::move(*HiddenNamesMap.begin());
4052 HiddenNamesMap.erase(HiddenNamesMap.begin());
4053 makeNamesVisible(HiddenNames.second, HiddenNames.first,
4054 /*FromFinalization*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004055 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004056}
4057
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004058/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
4059/// cursor into the start of the given block ID, returning false on success and
4060/// true on failure.
4061static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004062 while (1) {
4063 llvm::BitstreamEntry Entry = Cursor.advance();
4064 switch (Entry.Kind) {
4065 case llvm::BitstreamEntry::Error:
4066 case llvm::BitstreamEntry::EndBlock:
4067 return true;
4068
4069 case llvm::BitstreamEntry::Record:
4070 // Ignore top-level records.
4071 Cursor.skipRecord(Entry.ID);
4072 break;
4073
4074 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004075 if (Entry.ID == BlockID) {
4076 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004077 return true;
4078 // Found it!
4079 return false;
4080 }
4081
4082 if (Cursor.SkipBlock())
4083 return true;
4084 }
4085 }
4086}
4087
Ben Langmuir487ea142014-10-23 18:05:36 +00004088static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
4089 BitstreamCursor Stream(StreamFile);
4090 if (Stream.Read(8) != 'C' ||
4091 Stream.Read(8) != 'P' ||
4092 Stream.Read(8) != 'C' ||
4093 Stream.Read(8) != 'H') {
4094 return 0;
4095 }
4096
4097 // Scan for the CONTROL_BLOCK_ID block.
4098 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4099 return 0;
4100
4101 // Scan for SIGNATURE inside the control block.
4102 ASTReader::RecordData Record;
4103 while (1) {
4104 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4105 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
4106 Entry.Kind != llvm::BitstreamEntry::Record)
4107 return 0;
4108
4109 Record.clear();
4110 StringRef Blob;
4111 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4112 return Record[0];
4113 }
4114}
4115
Guy Benyei11169dd2012-12-18 14:30:41 +00004116/// \brief Retrieve the name of the original source file name
4117/// directly from the AST file, without actually loading the AST
4118/// file.
4119std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
4120 FileManager &FileMgr,
4121 DiagnosticsEngine &Diags) {
4122 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004123 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004124 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004125 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4126 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004127 return std::string();
4128 }
4129
4130 // Initialize the stream
4131 llvm::BitstreamReader StreamFile;
Benjamin Kramera8857962014-10-26 22:44:13 +00004132 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
4133 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004134 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004135
4136 // Sniff for the signature.
4137 if (Stream.Read(8) != 'C' ||
4138 Stream.Read(8) != 'P' ||
4139 Stream.Read(8) != 'C' ||
4140 Stream.Read(8) != 'H') {
4141 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4142 return std::string();
4143 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004144
Chris Lattnere7b154b2013-01-19 21:39:22 +00004145 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004146 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004147 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4148 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004149 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004150
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004151 // Scan for ORIGINAL_FILE inside the control block.
4152 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004153 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004154 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004155 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4156 return std::string();
4157
4158 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4159 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4160 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004161 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004162
Guy Benyei11169dd2012-12-18 14:30:41 +00004163 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004164 StringRef Blob;
4165 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4166 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004167 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004168}
4169
4170namespace {
4171 class SimplePCHValidator : public ASTReaderListener {
4172 const LangOptions &ExistingLangOpts;
4173 const TargetOptions &ExistingTargetOpts;
4174 const PreprocessorOptions &ExistingPPOpts;
4175 FileManager &FileMgr;
4176
4177 public:
4178 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4179 const TargetOptions &ExistingTargetOpts,
4180 const PreprocessorOptions &ExistingPPOpts,
4181 FileManager &FileMgr)
4182 : ExistingLangOpts(ExistingLangOpts),
4183 ExistingTargetOpts(ExistingTargetOpts),
4184 ExistingPPOpts(ExistingPPOpts),
4185 FileMgr(FileMgr)
4186 {
4187 }
4188
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004189 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4190 bool AllowCompatibleDifferences) override {
4191 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4192 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004193 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004194 bool ReadTargetOptions(const TargetOptions &TargetOpts,
4195 bool Complain) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004196 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004197 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004198 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4199 bool Complain,
4200 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004201 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004202 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004203 }
4204 };
4205}
4206
4207bool ASTReader::readASTFileControlBlock(StringRef Filename,
4208 FileManager &FileMgr,
4209 ASTReaderListener &Listener) {
4210 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004211 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004212 if (!Buffer) {
4213 return true;
4214 }
4215
4216 // Initialize the stream
4217 llvm::BitstreamReader StreamFile;
Benjamin Kramera8857962014-10-26 22:44:13 +00004218 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
4219 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004220 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004221
4222 // Sniff for the signature.
4223 if (Stream.Read(8) != 'C' ||
4224 Stream.Read(8) != 'P' ||
4225 Stream.Read(8) != 'C' ||
4226 Stream.Read(8) != 'H') {
4227 return true;
4228 }
4229
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004230 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004231 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004232 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004233
4234 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004235 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004236 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004237 BitstreamCursor InputFilesCursor;
4238 if (NeedsInputFiles) {
4239 InputFilesCursor = Stream;
4240 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4241 return true;
4242
4243 // Read the abbreviations
4244 while (true) {
4245 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4246 unsigned Code = InputFilesCursor.ReadCode();
4247
4248 // We expect all abbrevs to be at the start of the block.
4249 if (Code != llvm::bitc::DEFINE_ABBREV) {
4250 InputFilesCursor.JumpToBit(Offset);
4251 break;
4252 }
4253 InputFilesCursor.ReadAbbrevRecord();
4254 }
4255 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004256
4257 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004258 RecordData Record;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004259 while (1) {
4260 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4261 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4262 return false;
4263
4264 if (Entry.Kind != llvm::BitstreamEntry::Record)
4265 return true;
4266
Guy Benyei11169dd2012-12-18 14:30:41 +00004267 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004268 StringRef Blob;
4269 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004270 switch ((ControlRecordTypes)RecCode) {
4271 case METADATA: {
4272 if (Record[0] != VERSION_MAJOR)
4273 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004274
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004275 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004276 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004277
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004278 break;
4279 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004280 case MODULE_NAME:
4281 Listener.ReadModuleName(Blob);
4282 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004283 case MODULE_MAP_FILE: {
4284 unsigned Idx = 0;
4285 Listener.ReadModuleMapFile(ReadString(Record, Idx));
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004286 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004287 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004288 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004289 if (ParseLanguageOptions(Record, false, Listener,
4290 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004291 return true;
4292 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004293
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004294 case TARGET_OPTIONS:
4295 if (ParseTargetOptions(Record, false, Listener))
4296 return true;
4297 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004298
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004299 case DIAGNOSTIC_OPTIONS:
4300 if (ParseDiagnosticOptions(Record, false, Listener))
4301 return true;
4302 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004303
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004304 case FILE_SYSTEM_OPTIONS:
4305 if (ParseFileSystemOptions(Record, false, Listener))
4306 return true;
4307 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004308
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004309 case HEADER_SEARCH_OPTIONS:
4310 if (ParseHeaderSearchOptions(Record, false, Listener))
4311 return true;
4312 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004313
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004314 case PREPROCESSOR_OPTIONS: {
4315 std::string IgnoredSuggestedPredefines;
4316 if (ParsePreprocessorOptions(Record, false, Listener,
4317 IgnoredSuggestedPredefines))
4318 return true;
4319 break;
4320 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004321
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004322 case INPUT_FILE_OFFSETS: {
4323 if (!NeedsInputFiles)
4324 break;
4325
4326 unsigned NumInputFiles = Record[0];
4327 unsigned NumUserFiles = Record[1];
4328 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
4329 for (unsigned I = 0; I != NumInputFiles; ++I) {
4330 // Go find this input file.
4331 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004332
4333 if (isSystemFile && !NeedsSystemInputFiles)
4334 break; // the rest are system input files
4335
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004336 BitstreamCursor &Cursor = InputFilesCursor;
4337 SavedStreamPosition SavedPosition(Cursor);
4338 Cursor.JumpToBit(InputFileOffs[I]);
4339
4340 unsigned Code = Cursor.ReadCode();
4341 RecordData Record;
4342 StringRef Blob;
4343 bool shouldContinue = false;
4344 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4345 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004346 bool Overridden = static_cast<bool>(Record[3]);
4347 shouldContinue = Listener.visitInputFile(Blob, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004348 break;
4349 }
4350 if (!shouldContinue)
4351 break;
4352 }
4353 break;
4354 }
4355
Richard Smithd4b230b2014-10-27 23:01:16 +00004356 case IMPORTS: {
4357 if (!NeedsImports)
4358 break;
4359
4360 unsigned Idx = 0, N = Record.size();
4361 while (Idx < N) {
4362 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004363 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smithd4b230b2014-10-27 23:01:16 +00004364 unsigned Length = Record[Idx++];
4365 SmallString<128> ImportedFile(Record.begin() + Idx,
4366 Record.begin() + Idx + Length);
4367 Idx += Length;
4368 Listener.visitImport(ImportedFile);
4369 }
4370 break;
4371 }
4372
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004373 default:
4374 // No other validation to perform.
4375 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004376 }
4377 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004378}
4379
4380
4381bool ASTReader::isAcceptableASTFile(StringRef Filename,
4382 FileManager &FileMgr,
4383 const LangOptions &LangOpts,
4384 const TargetOptions &TargetOpts,
4385 const PreprocessorOptions &PPOpts) {
4386 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
4387 return !readASTFileControlBlock(Filename, FileMgr, validator);
4388}
4389
Ben Langmuir2c9af442014-04-10 17:57:43 +00004390ASTReader::ASTReadResult
4391ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004392 // Enter the submodule block.
4393 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4394 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004395 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004396 }
4397
4398 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4399 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004400 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004401 RecordData Record;
4402 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004403 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4404
4405 switch (Entry.Kind) {
4406 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4407 case llvm::BitstreamEntry::Error:
4408 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004409 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004410 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004411 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004412 case llvm::BitstreamEntry::Record:
4413 // The interesting case.
4414 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004415 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004416
Guy Benyei11169dd2012-12-18 14:30:41 +00004417 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004418 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004419 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004420 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4421
4422 if ((Kind == SUBMODULE_METADATA) != First) {
4423 Error("submodule metadata record should be at beginning of block");
4424 return Failure;
4425 }
4426 First = false;
4427
4428 // Submodule information is only valid if we have a current module.
4429 // FIXME: Should we error on these cases?
4430 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4431 Kind != SUBMODULE_DEFINITION)
4432 continue;
4433
4434 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004435 default: // Default behavior: ignore.
4436 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004437
Richard Smith03478d92014-10-23 22:12:14 +00004438 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004439 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004440 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004441 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004442 }
Richard Smith03478d92014-10-23 22:12:14 +00004443
Chris Lattner0e6c9402013-01-20 02:38:54 +00004444 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004445 unsigned Idx = 0;
4446 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4447 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4448 bool IsFramework = Record[Idx++];
4449 bool IsExplicit = Record[Idx++];
4450 bool IsSystem = Record[Idx++];
4451 bool IsExternC = Record[Idx++];
4452 bool InferSubmodules = Record[Idx++];
4453 bool InferExplicitSubmodules = Record[Idx++];
4454 bool InferExportWildcard = Record[Idx++];
4455 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004456
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004457 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004458 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004459 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004460
Guy Benyei11169dd2012-12-18 14:30:41 +00004461 // Retrieve this (sub)module from the module map, creating it if
4462 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004463 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004464 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004465
4466 // FIXME: set the definition loc for CurrentModule, or call
4467 // ModMap.setInferredModuleAllowedBy()
4468
Guy Benyei11169dd2012-12-18 14:30:41 +00004469 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4470 if (GlobalIndex >= SubmodulesLoaded.size() ||
4471 SubmodulesLoaded[GlobalIndex]) {
4472 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004473 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004474 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004475
Douglas Gregor7029ce12013-03-19 00:28:20 +00004476 if (!ParentModule) {
4477 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4478 if (CurFile != F.File) {
4479 if (!Diags.isDiagnosticInFlight()) {
4480 Diag(diag::err_module_file_conflict)
4481 << CurrentModule->getTopLevelModuleName()
4482 << CurFile->getName()
4483 << F.File->getName();
4484 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004485 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004486 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004487 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004488
4489 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004490 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004491
Guy Benyei11169dd2012-12-18 14:30:41 +00004492 CurrentModule->IsFromModuleFile = true;
4493 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004494 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004495 CurrentModule->InferSubmodules = InferSubmodules;
4496 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4497 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004498 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004499 if (DeserializationListener)
4500 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4501
4502 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004503
Douglas Gregorfb912652013-03-20 21:10:35 +00004504 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004505 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004506 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004507 CurrentModule->UnresolvedConflicts.clear();
4508 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004509 break;
4510 }
4511
4512 case SUBMODULE_UMBRELLA_HEADER: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004513 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004514 if (!CurrentModule->getUmbrellaHeader())
4515 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4516 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004517 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4518 Error("mismatched umbrella headers in submodule");
4519 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004520 }
4521 }
4522 break;
4523 }
4524
Richard Smith202210b2014-10-24 20:23:01 +00004525 case SUBMODULE_HEADER:
4526 case SUBMODULE_EXCLUDED_HEADER:
4527 case SUBMODULE_PRIVATE_HEADER:
4528 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004529 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4530 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004531 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004532
Richard Smith202210b2014-10-24 20:23:01 +00004533 case SUBMODULE_TEXTUAL_HEADER:
4534 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4535 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4536 // them here.
4537 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004538
Guy Benyei11169dd2012-12-18 14:30:41 +00004539 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004540 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004541 break;
4542 }
4543
4544 case SUBMODULE_UMBRELLA_DIR: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004546 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004547 if (!CurrentModule->getUmbrellaDir())
4548 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4549 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004550 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4551 Error("mismatched umbrella directories in submodule");
4552 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004553 }
4554 }
4555 break;
4556 }
4557
4558 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004559 F.BaseSubmoduleID = getTotalNumSubmodules();
4560 F.LocalNumSubmodules = Record[0];
4561 unsigned LocalBaseSubmoduleID = Record[1];
4562 if (F.LocalNumSubmodules > 0) {
4563 // Introduce the global -> local mapping for submodules within this
4564 // module.
4565 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4566
4567 // Introduce the local -> global mapping for submodules within this
4568 // module.
4569 F.SubmoduleRemap.insertOrReplace(
4570 std::make_pair(LocalBaseSubmoduleID,
4571 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004572
Ben Langmuir52ca6782014-10-20 16:27:32 +00004573 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4574 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004575 break;
4576 }
4577
4578 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004579 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004580 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004581 Unresolved.File = &F;
4582 Unresolved.Mod = CurrentModule;
4583 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004584 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004585 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004586 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004587 }
4588 break;
4589 }
4590
4591 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004592 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004593 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004594 Unresolved.File = &F;
4595 Unresolved.Mod = CurrentModule;
4596 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004597 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004598 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004599 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004600 }
4601
4602 // Once we've loaded the set of exports, there's no reason to keep
4603 // the parsed, unresolved exports around.
4604 CurrentModule->UnresolvedExports.clear();
4605 break;
4606 }
4607 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004608 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004609 Context.getTargetInfo());
4610 break;
4611 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004612
4613 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004614 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004615 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004616 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004617
4618 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004619 CurrentModule->ConfigMacros.push_back(Blob.str());
4620 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004621
4622 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004623 UnresolvedModuleRef Unresolved;
4624 Unresolved.File = &F;
4625 Unresolved.Mod = CurrentModule;
4626 Unresolved.ID = Record[0];
4627 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4628 Unresolved.IsWildcard = false;
4629 Unresolved.String = Blob;
4630 UnresolvedModuleRefs.push_back(Unresolved);
4631 break;
4632 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004633 }
4634 }
4635}
4636
4637/// \brief Parse the record that corresponds to a LangOptions data
4638/// structure.
4639///
4640/// This routine parses the language options from the AST file and then gives
4641/// them to the AST listener if one is set.
4642///
4643/// \returns true if the listener deems the file unacceptable, false otherwise.
4644bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4645 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004646 ASTReaderListener &Listener,
4647 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004648 LangOptions LangOpts;
4649 unsigned Idx = 0;
4650#define LANGOPT(Name, Bits, Default, Description) \
4651 LangOpts.Name = Record[Idx++];
4652#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4653 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4654#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004655#define SANITIZER(NAME, ID) \
4656 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004657#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004658
4659 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4660 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4661 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4662
4663 unsigned Length = Record[Idx++];
4664 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4665 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004666
4667 Idx += Length;
4668
4669 // Comment options.
4670 for (unsigned N = Record[Idx++]; N; --N) {
4671 LangOpts.CommentOpts.BlockCommandNames.push_back(
4672 ReadString(Record, Idx));
4673 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004674 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004675
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004676 return Listener.ReadLanguageOptions(LangOpts, Complain,
4677 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004678}
4679
4680bool ASTReader::ParseTargetOptions(const RecordData &Record,
4681 bool Complain,
4682 ASTReaderListener &Listener) {
4683 unsigned Idx = 0;
4684 TargetOptions TargetOpts;
4685 TargetOpts.Triple = ReadString(Record, Idx);
4686 TargetOpts.CPU = ReadString(Record, Idx);
4687 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004688 for (unsigned N = Record[Idx++]; N; --N) {
4689 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4690 }
4691 for (unsigned N = Record[Idx++]; N; --N) {
4692 TargetOpts.Features.push_back(ReadString(Record, Idx));
4693 }
4694
4695 return Listener.ReadTargetOptions(TargetOpts, Complain);
4696}
4697
4698bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4699 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004700 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004701 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004702#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004703#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004704 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004705#include "clang/Basic/DiagnosticOptions.def"
4706
Richard Smith3be1cb22014-08-07 00:24:21 +00004707 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004708 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004709 for (unsigned N = Record[Idx++]; N; --N)
4710 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004711
4712 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4713}
4714
4715bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4716 ASTReaderListener &Listener) {
4717 FileSystemOptions FSOpts;
4718 unsigned Idx = 0;
4719 FSOpts.WorkingDir = ReadString(Record, Idx);
4720 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4721}
4722
4723bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4724 bool Complain,
4725 ASTReaderListener &Listener) {
4726 HeaderSearchOptions HSOpts;
4727 unsigned Idx = 0;
4728 HSOpts.Sysroot = ReadString(Record, Idx);
4729
4730 // Include entries.
4731 for (unsigned N = Record[Idx++]; N; --N) {
4732 std::string Path = ReadString(Record, Idx);
4733 frontend::IncludeDirGroup Group
4734 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004735 bool IsFramework = Record[Idx++];
4736 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004737 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004738 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004739 }
4740
4741 // System header prefixes.
4742 for (unsigned N = Record[Idx++]; N; --N) {
4743 std::string Prefix = ReadString(Record, Idx);
4744 bool IsSystemHeader = Record[Idx++];
4745 HSOpts.SystemHeaderPrefixes.push_back(
4746 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4747 }
4748
4749 HSOpts.ResourceDir = ReadString(Record, Idx);
4750 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004751 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004752 HSOpts.DisableModuleHash = Record[Idx++];
4753 HSOpts.UseBuiltinIncludes = Record[Idx++];
4754 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4755 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4756 HSOpts.UseLibcxx = Record[Idx++];
4757
4758 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4759}
4760
4761bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4762 bool Complain,
4763 ASTReaderListener &Listener,
4764 std::string &SuggestedPredefines) {
4765 PreprocessorOptions PPOpts;
4766 unsigned Idx = 0;
4767
4768 // Macro definitions/undefs
4769 for (unsigned N = Record[Idx++]; N; --N) {
4770 std::string Macro = ReadString(Record, Idx);
4771 bool IsUndef = Record[Idx++];
4772 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4773 }
4774
4775 // Includes
4776 for (unsigned N = Record[Idx++]; N; --N) {
4777 PPOpts.Includes.push_back(ReadString(Record, Idx));
4778 }
4779
4780 // Macro Includes
4781 for (unsigned N = Record[Idx++]; N; --N) {
4782 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4783 }
4784
4785 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004786 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004787 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4788 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4789 PPOpts.ObjCXXARCStandardLibrary =
4790 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4791 SuggestedPredefines.clear();
4792 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4793 SuggestedPredefines);
4794}
4795
4796std::pair<ModuleFile *, unsigned>
4797ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4798 GlobalPreprocessedEntityMapType::iterator
4799 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4800 assert(I != GlobalPreprocessedEntityMap.end() &&
4801 "Corrupted global preprocessed entity map");
4802 ModuleFile *M = I->second;
4803 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4804 return std::make_pair(M, LocalIndex);
4805}
4806
4807std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4808ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4809 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4810 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4811 Mod.NumPreprocessedEntities);
4812
4813 return std::make_pair(PreprocessingRecord::iterator(),
4814 PreprocessingRecord::iterator());
4815}
4816
4817std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4818ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4819 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4820 ModuleDeclIterator(this, &Mod,
4821 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4822}
4823
4824PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4825 PreprocessedEntityID PPID = Index+1;
4826 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4827 ModuleFile &M = *PPInfo.first;
4828 unsigned LocalIndex = PPInfo.second;
4829 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4830
Guy Benyei11169dd2012-12-18 14:30:41 +00004831 if (!PP.getPreprocessingRecord()) {
4832 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004833 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004834 }
4835
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004836 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4837 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4838
4839 llvm::BitstreamEntry Entry =
4840 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4841 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004842 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004843
Guy Benyei11169dd2012-12-18 14:30:41 +00004844 // Read the record.
4845 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4846 ReadSourceLocation(M, PPOffs.End));
4847 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004848 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004849 RecordData Record;
4850 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004851 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4852 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004853 switch (RecType) {
4854 case PPD_MACRO_EXPANSION: {
4855 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004856 IdentifierInfo *Name = nullptr;
4857 MacroDefinition *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004858 if (isBuiltin)
4859 Name = getLocalIdentifier(M, Record[1]);
4860 else {
4861 PreprocessedEntityID
4862 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4863 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4864 }
4865
4866 MacroExpansion *ME;
4867 if (isBuiltin)
4868 ME = new (PPRec) MacroExpansion(Name, Range);
4869 else
4870 ME = new (PPRec) MacroExpansion(Def, Range);
4871
4872 return ME;
4873 }
4874
4875 case PPD_MACRO_DEFINITION: {
4876 // Decode the identifier info and then check again; if the macro is
4877 // still defined and associated with the identifier,
4878 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4879 MacroDefinition *MD
4880 = new (PPRec) MacroDefinition(II, Range);
4881
4882 if (DeserializationListener)
4883 DeserializationListener->MacroDefinitionRead(PPID, MD);
4884
4885 return MD;
4886 }
4887
4888 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004889 const char *FullFileNameStart = Blob.data() + Record[0];
4890 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004891 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004892 if (!FullFileName.empty())
4893 File = PP.getFileManager().getFile(FullFileName);
4894
4895 // FIXME: Stable encoding
4896 InclusionDirective::InclusionKind Kind
4897 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4898 InclusionDirective *ID
4899 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004900 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004901 Record[1], Record[3],
4902 File,
4903 Range);
4904 return ID;
4905 }
4906 }
4907
4908 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4909}
4910
4911/// \brief \arg SLocMapI points at a chunk of a module that contains no
4912/// preprocessed entities or the entities it contains are not the ones we are
4913/// looking for. Find the next module that contains entities and return the ID
4914/// of the first entry.
4915PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4916 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4917 ++SLocMapI;
4918 for (GlobalSLocOffsetMapType::const_iterator
4919 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4920 ModuleFile &M = *SLocMapI->second;
4921 if (M.NumPreprocessedEntities)
4922 return M.BasePreprocessedEntityID;
4923 }
4924
4925 return getTotalNumPreprocessedEntities();
4926}
4927
4928namespace {
4929
4930template <unsigned PPEntityOffset::*PPLoc>
4931struct PPEntityComp {
4932 const ASTReader &Reader;
4933 ModuleFile &M;
4934
4935 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4936
4937 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4938 SourceLocation LHS = getLoc(L);
4939 SourceLocation RHS = getLoc(R);
4940 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4941 }
4942
4943 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4944 SourceLocation LHS = getLoc(L);
4945 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4946 }
4947
4948 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4949 SourceLocation RHS = getLoc(R);
4950 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4951 }
4952
4953 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4954 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4955 }
4956};
4957
4958}
4959
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004960PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4961 bool EndsAfter) const {
4962 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004963 return getTotalNumPreprocessedEntities();
4964
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004965 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4966 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004967 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4968 "Corrupted global sloc offset map");
4969
4970 if (SLocMapI->second->NumPreprocessedEntities == 0)
4971 return findNextPreprocessedEntity(SLocMapI);
4972
4973 ModuleFile &M = *SLocMapI->second;
4974 typedef const PPEntityOffset *pp_iterator;
4975 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4976 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4977
4978 size_t Count = M.NumPreprocessedEntities;
4979 size_t Half;
4980 pp_iterator First = pp_begin;
4981 pp_iterator PPI;
4982
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004983 if (EndsAfter) {
4984 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4985 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4986 } else {
4987 // Do a binary search manually instead of using std::lower_bound because
4988 // The end locations of entities may be unordered (when a macro expansion
4989 // is inside another macro argument), but for this case it is not important
4990 // whether we get the first macro expansion or its containing macro.
4991 while (Count > 0) {
4992 Half = Count / 2;
4993 PPI = First;
4994 std::advance(PPI, Half);
4995 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4996 Loc)) {
4997 First = PPI;
4998 ++First;
4999 Count = Count - Half - 1;
5000 } else
5001 Count = Half;
5002 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005003 }
5004
5005 if (PPI == pp_end)
5006 return findNextPreprocessedEntity(SLocMapI);
5007
5008 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5009}
5010
Guy Benyei11169dd2012-12-18 14:30:41 +00005011/// \brief Returns a pair of [Begin, End) indices of preallocated
5012/// preprocessed entities that \arg Range encompasses.
5013std::pair<unsigned, unsigned>
5014 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5015 if (Range.isInvalid())
5016 return std::make_pair(0,0);
5017 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5018
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005019 PreprocessedEntityID BeginID =
5020 findPreprocessedEntity(Range.getBegin(), false);
5021 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005022 return std::make_pair(BeginID, EndID);
5023}
5024
5025/// \brief Optionally returns true or false if the preallocated preprocessed
5026/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005027Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005028 FileID FID) {
5029 if (FID.isInvalid())
5030 return false;
5031
5032 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5033 ModuleFile &M = *PPInfo.first;
5034 unsigned LocalIndex = PPInfo.second;
5035 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5036
5037 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
5038 if (Loc.isInvalid())
5039 return false;
5040
5041 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5042 return true;
5043 else
5044 return false;
5045}
5046
5047namespace {
5048 /// \brief Visitor used to search for information about a header file.
5049 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005050 const FileEntry *FE;
5051
David Blaikie05785d12013-02-20 22:23:23 +00005052 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005053
5054 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005055 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5056 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00005057
5058 static bool visit(ModuleFile &M, void *UserData) {
5059 HeaderFileInfoVisitor *This
5060 = static_cast<HeaderFileInfoVisitor *>(UserData);
5061
Guy Benyei11169dd2012-12-18 14:30:41 +00005062 HeaderFileInfoLookupTable *Table
5063 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5064 if (!Table)
5065 return false;
5066
5067 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00005068 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005069 if (Pos == Table->end())
5070 return false;
5071
5072 This->HFI = *Pos;
5073 return true;
5074 }
5075
David Blaikie05785d12013-02-20 22:23:23 +00005076 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005077 };
5078}
5079
5080HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005081 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005082 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005083 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005084 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005085
5086 return HeaderFileInfo();
5087}
5088
5089void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5090 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005091 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005092 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5093 ModuleFile &F = *(*I);
5094 unsigned Idx = 0;
5095 DiagStates.clear();
5096 assert(!Diag.DiagStates.empty());
5097 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5098 while (Idx < F.PragmaDiagMappings.size()) {
5099 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5100 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5101 if (DiagStateID != 0) {
5102 Diag.DiagStatePoints.push_back(
5103 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5104 FullSourceLoc(Loc, SourceMgr)));
5105 continue;
5106 }
5107
5108 assert(DiagStateID == 0);
5109 // A new DiagState was created here.
5110 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5111 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5112 DiagStates.push_back(NewState);
5113 Diag.DiagStatePoints.push_back(
5114 DiagnosticsEngine::DiagStatePoint(NewState,
5115 FullSourceLoc(Loc, SourceMgr)));
5116 while (1) {
5117 assert(Idx < F.PragmaDiagMappings.size() &&
5118 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5119 if (Idx >= F.PragmaDiagMappings.size()) {
5120 break; // Something is messed up but at least avoid infinite loop in
5121 // release build.
5122 }
5123 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5124 if (DiagID == (unsigned)-1) {
5125 break; // no more diag/map pairs for this location.
5126 }
Alp Tokerc726c362014-06-10 09:31:37 +00005127 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5128 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5129 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005130 }
5131 }
5132 }
5133}
5134
5135/// \brief Get the correct cursor and offset for loading a type.
5136ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5137 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5138 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5139 ModuleFile *M = I->second;
5140 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5141}
5142
5143/// \brief Read and return the type with the given index..
5144///
5145/// The index is the type ID, shifted and minus the number of predefs. This
5146/// routine actually reads the record corresponding to the type at the given
5147/// location. It is a helper routine for GetType, which deals with reading type
5148/// IDs.
5149QualType ASTReader::readTypeRecord(unsigned Index) {
5150 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005151 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005152
5153 // Keep track of where we are in the stream, then jump back there
5154 // after reading this type.
5155 SavedStreamPosition SavedPosition(DeclsCursor);
5156
5157 ReadingKindTracker ReadingKind(Read_Type, *this);
5158
5159 // Note that we are loading a type record.
5160 Deserializing AType(this);
5161
5162 unsigned Idx = 0;
5163 DeclsCursor.JumpToBit(Loc.Offset);
5164 RecordData Record;
5165 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005166 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005167 case TYPE_EXT_QUAL: {
5168 if (Record.size() != 2) {
5169 Error("Incorrect encoding of extended qualifier type");
5170 return QualType();
5171 }
5172 QualType Base = readType(*Loc.F, Record, Idx);
5173 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5174 return Context.getQualifiedType(Base, Quals);
5175 }
5176
5177 case TYPE_COMPLEX: {
5178 if (Record.size() != 1) {
5179 Error("Incorrect encoding of complex type");
5180 return QualType();
5181 }
5182 QualType ElemType = readType(*Loc.F, Record, Idx);
5183 return Context.getComplexType(ElemType);
5184 }
5185
5186 case TYPE_POINTER: {
5187 if (Record.size() != 1) {
5188 Error("Incorrect encoding of pointer type");
5189 return QualType();
5190 }
5191 QualType PointeeType = readType(*Loc.F, Record, Idx);
5192 return Context.getPointerType(PointeeType);
5193 }
5194
Reid Kleckner8a365022013-06-24 17:51:48 +00005195 case TYPE_DECAYED: {
5196 if (Record.size() != 1) {
5197 Error("Incorrect encoding of decayed type");
5198 return QualType();
5199 }
5200 QualType OriginalType = readType(*Loc.F, Record, Idx);
5201 QualType DT = Context.getAdjustedParameterType(OriginalType);
5202 if (!isa<DecayedType>(DT))
5203 Error("Decayed type does not decay");
5204 return DT;
5205 }
5206
Reid Kleckner0503a872013-12-05 01:23:43 +00005207 case TYPE_ADJUSTED: {
5208 if (Record.size() != 2) {
5209 Error("Incorrect encoding of adjusted type");
5210 return QualType();
5211 }
5212 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5213 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5214 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5215 }
5216
Guy Benyei11169dd2012-12-18 14:30:41 +00005217 case TYPE_BLOCK_POINTER: {
5218 if (Record.size() != 1) {
5219 Error("Incorrect encoding of block pointer type");
5220 return QualType();
5221 }
5222 QualType PointeeType = readType(*Loc.F, Record, Idx);
5223 return Context.getBlockPointerType(PointeeType);
5224 }
5225
5226 case TYPE_LVALUE_REFERENCE: {
5227 if (Record.size() != 2) {
5228 Error("Incorrect encoding of lvalue reference type");
5229 return QualType();
5230 }
5231 QualType PointeeType = readType(*Loc.F, Record, Idx);
5232 return Context.getLValueReferenceType(PointeeType, Record[1]);
5233 }
5234
5235 case TYPE_RVALUE_REFERENCE: {
5236 if (Record.size() != 1) {
5237 Error("Incorrect encoding of rvalue reference type");
5238 return QualType();
5239 }
5240 QualType PointeeType = readType(*Loc.F, Record, Idx);
5241 return Context.getRValueReferenceType(PointeeType);
5242 }
5243
5244 case TYPE_MEMBER_POINTER: {
5245 if (Record.size() != 2) {
5246 Error("Incorrect encoding of member pointer type");
5247 return QualType();
5248 }
5249 QualType PointeeType = readType(*Loc.F, Record, Idx);
5250 QualType ClassType = readType(*Loc.F, Record, Idx);
5251 if (PointeeType.isNull() || ClassType.isNull())
5252 return QualType();
5253
5254 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5255 }
5256
5257 case TYPE_CONSTANT_ARRAY: {
5258 QualType ElementType = readType(*Loc.F, Record, Idx);
5259 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5260 unsigned IndexTypeQuals = Record[2];
5261 unsigned Idx = 3;
5262 llvm::APInt Size = ReadAPInt(Record, Idx);
5263 return Context.getConstantArrayType(ElementType, Size,
5264 ASM, IndexTypeQuals);
5265 }
5266
5267 case TYPE_INCOMPLETE_ARRAY: {
5268 QualType ElementType = readType(*Loc.F, Record, Idx);
5269 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5270 unsigned IndexTypeQuals = Record[2];
5271 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5272 }
5273
5274 case TYPE_VARIABLE_ARRAY: {
5275 QualType ElementType = readType(*Loc.F, Record, Idx);
5276 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5277 unsigned IndexTypeQuals = Record[2];
5278 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5279 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5280 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5281 ASM, IndexTypeQuals,
5282 SourceRange(LBLoc, RBLoc));
5283 }
5284
5285 case TYPE_VECTOR: {
5286 if (Record.size() != 3) {
5287 Error("incorrect encoding of vector type in AST file");
5288 return QualType();
5289 }
5290
5291 QualType ElementType = readType(*Loc.F, Record, Idx);
5292 unsigned NumElements = Record[1];
5293 unsigned VecKind = Record[2];
5294 return Context.getVectorType(ElementType, NumElements,
5295 (VectorType::VectorKind)VecKind);
5296 }
5297
5298 case TYPE_EXT_VECTOR: {
5299 if (Record.size() != 3) {
5300 Error("incorrect encoding of extended vector type in AST file");
5301 return QualType();
5302 }
5303
5304 QualType ElementType = readType(*Loc.F, Record, Idx);
5305 unsigned NumElements = Record[1];
5306 return Context.getExtVectorType(ElementType, NumElements);
5307 }
5308
5309 case TYPE_FUNCTION_NO_PROTO: {
5310 if (Record.size() != 6) {
5311 Error("incorrect encoding of no-proto function type");
5312 return QualType();
5313 }
5314 QualType ResultType = readType(*Loc.F, Record, Idx);
5315 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5316 (CallingConv)Record[4], Record[5]);
5317 return Context.getFunctionNoProtoType(ResultType, Info);
5318 }
5319
5320 case TYPE_FUNCTION_PROTO: {
5321 QualType ResultType = readType(*Loc.F, Record, Idx);
5322
5323 FunctionProtoType::ExtProtoInfo EPI;
5324 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5325 /*hasregparm*/ Record[2],
5326 /*regparm*/ Record[3],
5327 static_cast<CallingConv>(Record[4]),
5328 /*produces*/ Record[5]);
5329
5330 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005331
5332 EPI.Variadic = Record[Idx++];
5333 EPI.HasTrailingReturn = Record[Idx++];
5334 EPI.TypeQuals = Record[Idx++];
5335 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005336 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005337 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005338
5339 unsigned NumParams = Record[Idx++];
5340 SmallVector<QualType, 16> ParamTypes;
5341 for (unsigned I = 0; I != NumParams; ++I)
5342 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5343
Jordan Rose5c382722013-03-08 21:51:21 +00005344 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005345 }
5346
5347 case TYPE_UNRESOLVED_USING: {
5348 unsigned Idx = 0;
5349 return Context.getTypeDeclType(
5350 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5351 }
5352
5353 case TYPE_TYPEDEF: {
5354 if (Record.size() != 2) {
5355 Error("incorrect encoding of typedef type");
5356 return QualType();
5357 }
5358 unsigned Idx = 0;
5359 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5360 QualType Canonical = readType(*Loc.F, Record, Idx);
5361 if (!Canonical.isNull())
5362 Canonical = Context.getCanonicalType(Canonical);
5363 return Context.getTypedefType(Decl, Canonical);
5364 }
5365
5366 case TYPE_TYPEOF_EXPR:
5367 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5368
5369 case TYPE_TYPEOF: {
5370 if (Record.size() != 1) {
5371 Error("incorrect encoding of typeof(type) in AST file");
5372 return QualType();
5373 }
5374 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5375 return Context.getTypeOfType(UnderlyingType);
5376 }
5377
5378 case TYPE_DECLTYPE: {
5379 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5380 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5381 }
5382
5383 case TYPE_UNARY_TRANSFORM: {
5384 QualType BaseType = readType(*Loc.F, Record, Idx);
5385 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5386 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5387 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5388 }
5389
Richard Smith74aeef52013-04-26 16:15:35 +00005390 case TYPE_AUTO: {
5391 QualType Deduced = readType(*Loc.F, Record, Idx);
5392 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005393 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005394 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005395 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005396
5397 case TYPE_RECORD: {
5398 if (Record.size() != 2) {
5399 Error("incorrect encoding of record type");
5400 return QualType();
5401 }
5402 unsigned Idx = 0;
5403 bool IsDependent = Record[Idx++];
5404 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5405 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5406 QualType T = Context.getRecordType(RD);
5407 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5408 return T;
5409 }
5410
5411 case TYPE_ENUM: {
5412 if (Record.size() != 2) {
5413 Error("incorrect encoding of enum type");
5414 return QualType();
5415 }
5416 unsigned Idx = 0;
5417 bool IsDependent = Record[Idx++];
5418 QualType T
5419 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5420 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5421 return T;
5422 }
5423
5424 case TYPE_ATTRIBUTED: {
5425 if (Record.size() != 3) {
5426 Error("incorrect encoding of attributed type");
5427 return QualType();
5428 }
5429 QualType modifiedType = readType(*Loc.F, Record, Idx);
5430 QualType equivalentType = readType(*Loc.F, Record, Idx);
5431 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5432 return Context.getAttributedType(kind, modifiedType, equivalentType);
5433 }
5434
5435 case TYPE_PAREN: {
5436 if (Record.size() != 1) {
5437 Error("incorrect encoding of paren type");
5438 return QualType();
5439 }
5440 QualType InnerType = readType(*Loc.F, Record, Idx);
5441 return Context.getParenType(InnerType);
5442 }
5443
5444 case TYPE_PACK_EXPANSION: {
5445 if (Record.size() != 2) {
5446 Error("incorrect encoding of pack expansion type");
5447 return QualType();
5448 }
5449 QualType Pattern = readType(*Loc.F, Record, Idx);
5450 if (Pattern.isNull())
5451 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005452 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005453 if (Record[1])
5454 NumExpansions = Record[1] - 1;
5455 return Context.getPackExpansionType(Pattern, NumExpansions);
5456 }
5457
5458 case TYPE_ELABORATED: {
5459 unsigned Idx = 0;
5460 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5461 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5462 QualType NamedType = readType(*Loc.F, Record, Idx);
5463 return Context.getElaboratedType(Keyword, NNS, NamedType);
5464 }
5465
5466 case TYPE_OBJC_INTERFACE: {
5467 unsigned Idx = 0;
5468 ObjCInterfaceDecl *ItfD
5469 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5470 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5471 }
5472
5473 case TYPE_OBJC_OBJECT: {
5474 unsigned Idx = 0;
5475 QualType Base = readType(*Loc.F, Record, Idx);
5476 unsigned NumProtos = Record[Idx++];
5477 SmallVector<ObjCProtocolDecl*, 4> Protos;
5478 for (unsigned I = 0; I != NumProtos; ++I)
5479 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5480 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5481 }
5482
5483 case TYPE_OBJC_OBJECT_POINTER: {
5484 unsigned Idx = 0;
5485 QualType Pointee = readType(*Loc.F, Record, Idx);
5486 return Context.getObjCObjectPointerType(Pointee);
5487 }
5488
5489 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5490 unsigned Idx = 0;
5491 QualType Parm = readType(*Loc.F, Record, Idx);
5492 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005493 return Context.getSubstTemplateTypeParmType(
5494 cast<TemplateTypeParmType>(Parm),
5495 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005496 }
5497
5498 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5499 unsigned Idx = 0;
5500 QualType Parm = readType(*Loc.F, Record, Idx);
5501 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5502 return Context.getSubstTemplateTypeParmPackType(
5503 cast<TemplateTypeParmType>(Parm),
5504 ArgPack);
5505 }
5506
5507 case TYPE_INJECTED_CLASS_NAME: {
5508 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5509 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5510 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5511 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005512 const Type *T = nullptr;
5513 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5514 if (const Type *Existing = DI->getTypeForDecl()) {
5515 T = Existing;
5516 break;
5517 }
5518 }
5519 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005520 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005521 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5522 DI->setTypeForDecl(T);
5523 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005524 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005525 }
5526
5527 case TYPE_TEMPLATE_TYPE_PARM: {
5528 unsigned Idx = 0;
5529 unsigned Depth = Record[Idx++];
5530 unsigned Index = Record[Idx++];
5531 bool Pack = Record[Idx++];
5532 TemplateTypeParmDecl *D
5533 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5534 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5535 }
5536
5537 case TYPE_DEPENDENT_NAME: {
5538 unsigned Idx = 0;
5539 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5540 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5541 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5542 QualType Canon = readType(*Loc.F, Record, Idx);
5543 if (!Canon.isNull())
5544 Canon = Context.getCanonicalType(Canon);
5545 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5546 }
5547
5548 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5549 unsigned Idx = 0;
5550 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5551 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5552 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5553 unsigned NumArgs = Record[Idx++];
5554 SmallVector<TemplateArgument, 8> Args;
5555 Args.reserve(NumArgs);
5556 while (NumArgs--)
5557 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5558 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5559 Args.size(), Args.data());
5560 }
5561
5562 case TYPE_DEPENDENT_SIZED_ARRAY: {
5563 unsigned Idx = 0;
5564
5565 // ArrayType
5566 QualType ElementType = readType(*Loc.F, Record, Idx);
5567 ArrayType::ArraySizeModifier ASM
5568 = (ArrayType::ArraySizeModifier)Record[Idx++];
5569 unsigned IndexTypeQuals = Record[Idx++];
5570
5571 // DependentSizedArrayType
5572 Expr *NumElts = ReadExpr(*Loc.F);
5573 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5574
5575 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5576 IndexTypeQuals, Brackets);
5577 }
5578
5579 case TYPE_TEMPLATE_SPECIALIZATION: {
5580 unsigned Idx = 0;
5581 bool IsDependent = Record[Idx++];
5582 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5583 SmallVector<TemplateArgument, 8> Args;
5584 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5585 QualType Underlying = readType(*Loc.F, Record, Idx);
5586 QualType T;
5587 if (Underlying.isNull())
5588 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5589 Args.size());
5590 else
5591 T = Context.getTemplateSpecializationType(Name, Args.data(),
5592 Args.size(), Underlying);
5593 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5594 return T;
5595 }
5596
5597 case TYPE_ATOMIC: {
5598 if (Record.size() != 1) {
5599 Error("Incorrect encoding of atomic type");
5600 return QualType();
5601 }
5602 QualType ValueType = readType(*Loc.F, Record, Idx);
5603 return Context.getAtomicType(ValueType);
5604 }
5605 }
5606 llvm_unreachable("Invalid TypeCode!");
5607}
5608
Richard Smith564417a2014-03-20 21:47:22 +00005609void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5610 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005611 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005612 const RecordData &Record, unsigned &Idx) {
5613 ExceptionSpecificationType EST =
5614 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005615 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005616 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005617 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005618 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005619 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005620 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005621 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005622 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005623 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5624 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005625 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005626 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005627 }
5628}
5629
Guy Benyei11169dd2012-12-18 14:30:41 +00005630class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5631 ASTReader &Reader;
5632 ModuleFile &F;
5633 const ASTReader::RecordData &Record;
5634 unsigned &Idx;
5635
5636 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5637 unsigned &I) {
5638 return Reader.ReadSourceLocation(F, R, I);
5639 }
5640
5641 template<typename T>
5642 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5643 return Reader.ReadDeclAs<T>(F, Record, Idx);
5644 }
5645
5646public:
5647 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5648 const ASTReader::RecordData &Record, unsigned &Idx)
5649 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5650 { }
5651
5652 // We want compile-time assurance that we've enumerated all of
5653 // these, so unfortunately we have to declare them first, then
5654 // define them out-of-line.
5655#define ABSTRACT_TYPELOC(CLASS, PARENT)
5656#define TYPELOC(CLASS, PARENT) \
5657 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5658#include "clang/AST/TypeLocNodes.def"
5659
5660 void VisitFunctionTypeLoc(FunctionTypeLoc);
5661 void VisitArrayTypeLoc(ArrayTypeLoc);
5662};
5663
5664void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5665 // nothing to do
5666}
5667void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5668 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5669 if (TL.needsExtraLocalData()) {
5670 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5671 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5672 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5673 TL.setModeAttr(Record[Idx++]);
5674 }
5675}
5676void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5677 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5678}
5679void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5680 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5681}
Reid Kleckner8a365022013-06-24 17:51:48 +00005682void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5683 // nothing to do
5684}
Reid Kleckner0503a872013-12-05 01:23:43 +00005685void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5686 // nothing to do
5687}
Guy Benyei11169dd2012-12-18 14:30:41 +00005688void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5689 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5690}
5691void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5692 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5693}
5694void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5695 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5696}
5697void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5698 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5699 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5700}
5701void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5702 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5703 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5704 if (Record[Idx++])
5705 TL.setSizeExpr(Reader.ReadExpr(F));
5706 else
Craig Toppera13603a2014-05-22 05:54:18 +00005707 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005708}
5709void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5710 VisitArrayTypeLoc(TL);
5711}
5712void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5713 VisitArrayTypeLoc(TL);
5714}
5715void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5716 VisitArrayTypeLoc(TL);
5717}
5718void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5719 DependentSizedArrayTypeLoc TL) {
5720 VisitArrayTypeLoc(TL);
5721}
5722void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5723 DependentSizedExtVectorTypeLoc TL) {
5724 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5725}
5726void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5727 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5728}
5729void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5730 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5731}
5732void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5733 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5734 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5735 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5736 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005737 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5738 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005739 }
5740}
5741void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5742 VisitFunctionTypeLoc(TL);
5743}
5744void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5745 VisitFunctionTypeLoc(TL);
5746}
5747void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5748 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5749}
5750void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5751 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5752}
5753void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5754 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5755 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5756 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5757}
5758void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5759 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5760 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5761 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5762 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5763}
5764void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5765 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5766}
5767void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5768 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5769 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5770 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5771 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5772}
5773void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5774 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5775}
5776void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5777 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5778}
5779void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5780 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5781}
5782void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5783 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5784 if (TL.hasAttrOperand()) {
5785 SourceRange range;
5786 range.setBegin(ReadSourceLocation(Record, Idx));
5787 range.setEnd(ReadSourceLocation(Record, Idx));
5788 TL.setAttrOperandParensRange(range);
5789 }
5790 if (TL.hasAttrExprOperand()) {
5791 if (Record[Idx++])
5792 TL.setAttrExprOperand(Reader.ReadExpr(F));
5793 else
Craig Toppera13603a2014-05-22 05:54:18 +00005794 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005795 } else if (TL.hasAttrEnumOperand())
5796 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5797}
5798void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5799 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5800}
5801void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5802 SubstTemplateTypeParmTypeLoc TL) {
5803 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5804}
5805void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5806 SubstTemplateTypeParmPackTypeLoc TL) {
5807 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5808}
5809void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5810 TemplateSpecializationTypeLoc TL) {
5811 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5812 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5813 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5814 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5815 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5816 TL.setArgLocInfo(i,
5817 Reader.GetTemplateArgumentLocInfo(F,
5818 TL.getTypePtr()->getArg(i).getKind(),
5819 Record, Idx));
5820}
5821void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5822 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5823 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5824}
5825void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5826 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5827 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5828}
5829void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5830 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5831}
5832void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5833 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5834 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5835 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5836}
5837void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5838 DependentTemplateSpecializationTypeLoc TL) {
5839 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5840 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5841 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5842 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5843 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5844 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5845 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5846 TL.setArgLocInfo(I,
5847 Reader.GetTemplateArgumentLocInfo(F,
5848 TL.getTypePtr()->getArg(I).getKind(),
5849 Record, Idx));
5850}
5851void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5852 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5853}
5854void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5855 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5856}
5857void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5858 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5859 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5860 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5861 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5862 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5863}
5864void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5865 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5866}
5867void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5868 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5869 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5870 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5871}
5872
5873TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5874 const RecordData &Record,
5875 unsigned &Idx) {
5876 QualType InfoTy = readType(F, Record, Idx);
5877 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005878 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005879
5880 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5881 TypeLocReader TLR(*this, F, Record, Idx);
5882 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5883 TLR.Visit(TL);
5884 return TInfo;
5885}
5886
5887QualType ASTReader::GetType(TypeID ID) {
5888 unsigned FastQuals = ID & Qualifiers::FastMask;
5889 unsigned Index = ID >> Qualifiers::FastWidth;
5890
5891 if (Index < NUM_PREDEF_TYPE_IDS) {
5892 QualType T;
5893 switch ((PredefinedTypeIDs)Index) {
5894 case PREDEF_TYPE_NULL_ID: return QualType();
5895 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5896 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5897
5898 case PREDEF_TYPE_CHAR_U_ID:
5899 case PREDEF_TYPE_CHAR_S_ID:
5900 // FIXME: Check that the signedness of CharTy is correct!
5901 T = Context.CharTy;
5902 break;
5903
5904 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5905 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5906 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5907 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5908 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5909 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5910 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5911 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5912 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5913 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5914 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5915 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5916 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5917 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5918 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5919 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5920 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5921 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5922 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5923 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5924 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5925 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5926 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5927 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5928 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5929 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5930 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5931 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005932 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5933 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5934 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5935 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5936 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5937 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005938 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005939 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005940 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5941
5942 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5943 T = Context.getAutoRRefDeductType();
5944 break;
5945
5946 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5947 T = Context.ARCUnbridgedCastTy;
5948 break;
5949
5950 case PREDEF_TYPE_VA_LIST_TAG:
5951 T = Context.getVaListTagType();
5952 break;
5953
5954 case PREDEF_TYPE_BUILTIN_FN:
5955 T = Context.BuiltinFnTy;
5956 break;
5957 }
5958
5959 assert(!T.isNull() && "Unknown predefined type");
5960 return T.withFastQualifiers(FastQuals);
5961 }
5962
5963 Index -= NUM_PREDEF_TYPE_IDS;
5964 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5965 if (TypesLoaded[Index].isNull()) {
5966 TypesLoaded[Index] = readTypeRecord(Index);
5967 if (TypesLoaded[Index].isNull())
5968 return QualType();
5969
5970 TypesLoaded[Index]->setFromAST();
5971 if (DeserializationListener)
5972 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5973 TypesLoaded[Index]);
5974 }
5975
5976 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5977}
5978
5979QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5980 return GetType(getGlobalTypeID(F, LocalID));
5981}
5982
5983serialization::TypeID
5984ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5985 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5986 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5987
5988 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5989 return LocalID;
5990
5991 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5992 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5993 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5994
5995 unsigned GlobalIndex = LocalIndex + I->second;
5996 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5997}
5998
5999TemplateArgumentLocInfo
6000ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6001 TemplateArgument::ArgKind Kind,
6002 const RecordData &Record,
6003 unsigned &Index) {
6004 switch (Kind) {
6005 case TemplateArgument::Expression:
6006 return ReadExpr(F);
6007 case TemplateArgument::Type:
6008 return GetTypeSourceInfo(F, Record, Index);
6009 case TemplateArgument::Template: {
6010 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6011 Index);
6012 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6013 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6014 SourceLocation());
6015 }
6016 case TemplateArgument::TemplateExpansion: {
6017 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6018 Index);
6019 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6020 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6021 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6022 EllipsisLoc);
6023 }
6024 case TemplateArgument::Null:
6025 case TemplateArgument::Integral:
6026 case TemplateArgument::Declaration:
6027 case TemplateArgument::NullPtr:
6028 case TemplateArgument::Pack:
6029 // FIXME: Is this right?
6030 return TemplateArgumentLocInfo();
6031 }
6032 llvm_unreachable("unexpected template argument loc");
6033}
6034
6035TemplateArgumentLoc
6036ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6037 const RecordData &Record, unsigned &Index) {
6038 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6039
6040 if (Arg.getKind() == TemplateArgument::Expression) {
6041 if (Record[Index++]) // bool InfoHasSameExpr.
6042 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6043 }
6044 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6045 Record, Index));
6046}
6047
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006048const ASTTemplateArgumentListInfo*
6049ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6050 const RecordData &Record,
6051 unsigned &Index) {
6052 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6053 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6054 unsigned NumArgsAsWritten = Record[Index++];
6055 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6056 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6057 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6058 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6059}
6060
Guy Benyei11169dd2012-12-18 14:30:41 +00006061Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6062 return GetDecl(ID);
6063}
6064
Richard Smith053f6c62014-05-16 23:01:30 +00006065void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006066 if (NumCurrentElementsDeserializing) {
6067 // We arrange to not care about the complete redeclaration chain while we're
6068 // deserializing. Just remember that the AST has marked this one as complete
6069 // but that it's not actually complete yet, so we know we still need to
6070 // complete it later.
6071 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6072 return;
6073 }
6074
Richard Smith053f6c62014-05-16 23:01:30 +00006075 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6076
Richard Smith053f6c62014-05-16 23:01:30 +00006077 // If this is a named declaration, complete it by looking it up
6078 // within its context.
6079 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006080 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006081 // all mergeable entities within it.
6082 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6083 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6084 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
6085 auto *II = Name.getAsIdentifierInfo();
6086 if (isa<TranslationUnitDecl>(DC) && II) {
6087 // Outside of C++, we don't have a lookup table for the TU, so update
6088 // the identifier instead. In C++, either way should work fine.
6089 if (II->isOutOfDate())
6090 updateOutOfDateIdentifier(*II);
6091 } else
6092 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006093 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
6094 // FIXME: It'd be nice to do something a bit more targeted here.
6095 D->getDeclContext()->decls_begin();
Richard Smith053f6c62014-05-16 23:01:30 +00006096 }
6097 }
6098}
6099
Richard Smithcd45dbc2014-04-19 03:48:30 +00006100uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6101 const RecordData &Record,
6102 unsigned &Idx) {
6103 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6104 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006105 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006106 }
6107
Guy Benyei11169dd2012-12-18 14:30:41 +00006108 unsigned LocalID = Record[Idx++];
6109 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6110}
6111
6112CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6113 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006114 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006115 SavedStreamPosition SavedPosition(Cursor);
6116 Cursor.JumpToBit(Loc.Offset);
6117 ReadingKindTracker ReadingKind(Read_Decl, *this);
6118 RecordData Record;
6119 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006120 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006121 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006122 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006123 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006124 }
6125
6126 unsigned Idx = 0;
6127 unsigned NumBases = Record[Idx++];
6128 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6129 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6130 for (unsigned I = 0; I != NumBases; ++I)
6131 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6132 return Bases;
6133}
6134
6135serialization::DeclID
6136ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6137 if (LocalID < NUM_PREDEF_DECL_IDS)
6138 return LocalID;
6139
6140 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6141 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6142 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6143
6144 return LocalID + I->second;
6145}
6146
6147bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6148 ModuleFile &M) const {
6149 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6150 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6151 return &M == I->second;
6152}
6153
Douglas Gregor9f782892013-01-21 15:25:38 +00006154ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006155 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006156 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006157 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6158 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6159 return I->second;
6160}
6161
6162SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6163 if (ID < NUM_PREDEF_DECL_IDS)
6164 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006165
Guy Benyei11169dd2012-12-18 14:30:41 +00006166 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6167
6168 if (Index > DeclsLoaded.size()) {
6169 Error("declaration ID out-of-range for AST file");
6170 return SourceLocation();
6171 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006172
Guy Benyei11169dd2012-12-18 14:30:41 +00006173 if (Decl *D = DeclsLoaded[Index])
6174 return D->getLocation();
6175
6176 unsigned RawLocation = 0;
6177 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6178 return ReadSourceLocation(*Rec.F, RawLocation);
6179}
6180
Richard Smithcd45dbc2014-04-19 03:48:30 +00006181Decl *ASTReader::GetExistingDecl(DeclID ID) {
6182 if (ID < NUM_PREDEF_DECL_IDS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006183 switch ((PredefinedDeclIDs)ID) {
6184 case PREDEF_DECL_NULL_ID:
Craig Toppera13603a2014-05-22 05:54:18 +00006185 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006186
Guy Benyei11169dd2012-12-18 14:30:41 +00006187 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6188 return Context.getTranslationUnitDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006189
Guy Benyei11169dd2012-12-18 14:30:41 +00006190 case PREDEF_DECL_OBJC_ID_ID:
6191 return Context.getObjCIdDecl();
6192
6193 case PREDEF_DECL_OBJC_SEL_ID:
6194 return Context.getObjCSelDecl();
6195
6196 case PREDEF_DECL_OBJC_CLASS_ID:
6197 return Context.getObjCClassDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006198
Guy Benyei11169dd2012-12-18 14:30:41 +00006199 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6200 return Context.getObjCProtocolDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006201
Guy Benyei11169dd2012-12-18 14:30:41 +00006202 case PREDEF_DECL_INT_128_ID:
6203 return Context.getInt128Decl();
6204
6205 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6206 return Context.getUInt128Decl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006207
Guy Benyei11169dd2012-12-18 14:30:41 +00006208 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6209 return Context.getObjCInstanceTypeDecl();
6210
6211 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6212 return Context.getBuiltinVaListDecl();
6213 }
6214 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006215
Guy Benyei11169dd2012-12-18 14:30:41 +00006216 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6217
6218 if (Index >= DeclsLoaded.size()) {
6219 assert(0 && "declaration ID out-of-range for AST file");
6220 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006221 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006222 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006223
6224 return DeclsLoaded[Index];
6225}
6226
6227Decl *ASTReader::GetDecl(DeclID ID) {
6228 if (ID < NUM_PREDEF_DECL_IDS)
6229 return GetExistingDecl(ID);
6230
6231 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6232
6233 if (Index >= DeclsLoaded.size()) {
6234 assert(0 && "declaration ID out-of-range for AST file");
6235 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006236 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006237 }
6238
Guy Benyei11169dd2012-12-18 14:30:41 +00006239 if (!DeclsLoaded[Index]) {
6240 ReadDeclRecord(ID);
6241 if (DeserializationListener)
6242 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6243 }
6244
6245 return DeclsLoaded[Index];
6246}
6247
6248DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6249 DeclID GlobalID) {
6250 if (GlobalID < NUM_PREDEF_DECL_IDS)
6251 return GlobalID;
6252
6253 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6254 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6255 ModuleFile *Owner = I->second;
6256
6257 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6258 = M.GlobalToLocalDeclIDs.find(Owner);
6259 if (Pos == M.GlobalToLocalDeclIDs.end())
6260 return 0;
6261
6262 return GlobalID - Owner->BaseDeclID + Pos->second;
6263}
6264
6265serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6266 const RecordData &Record,
6267 unsigned &Idx) {
6268 if (Idx >= Record.size()) {
6269 Error("Corrupted AST file");
6270 return 0;
6271 }
6272
6273 return getGlobalDeclID(F, Record[Idx++]);
6274}
6275
6276/// \brief Resolve the offset of a statement into a statement.
6277///
6278/// This operation will read a new statement from the external
6279/// source each time it is called, and is meant to be used via a
6280/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6281Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6282 // Switch case IDs are per Decl.
6283 ClearSwitchCaseIDs();
6284
6285 // Offset here is a global offset across the entire chain.
6286 RecordLocation Loc = getLocalBitOffset(Offset);
6287 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6288 return ReadStmtFromStream(*Loc.F);
6289}
6290
6291namespace {
6292 class FindExternalLexicalDeclsVisitor {
6293 ASTReader &Reader;
6294 const DeclContext *DC;
6295 bool (*isKindWeWant)(Decl::Kind);
6296
6297 SmallVectorImpl<Decl*> &Decls;
6298 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6299
6300 public:
6301 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6302 bool (*isKindWeWant)(Decl::Kind),
6303 SmallVectorImpl<Decl*> &Decls)
6304 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6305 {
6306 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6307 PredefsVisited[I] = false;
6308 }
6309
6310 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6311 if (Preorder)
6312 return false;
6313
6314 FindExternalLexicalDeclsVisitor *This
6315 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6316
6317 ModuleFile::DeclContextInfosMap::iterator Info
6318 = M.DeclContextInfos.find(This->DC);
6319 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6320 return false;
6321
6322 // Load all of the declaration IDs
6323 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6324 *IDE = ID + Info->second.NumLexicalDecls;
6325 ID != IDE; ++ID) {
6326 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6327 continue;
6328
6329 // Don't add predefined declarations to the lexical context more
6330 // than once.
6331 if (ID->second < NUM_PREDEF_DECL_IDS) {
6332 if (This->PredefsVisited[ID->second])
6333 continue;
6334
6335 This->PredefsVisited[ID->second] = true;
6336 }
6337
6338 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6339 if (!This->DC->isDeclInLexicalTraversal(D))
6340 This->Decls.push_back(D);
6341 }
6342 }
6343
6344 return false;
6345 }
6346 };
6347}
6348
6349ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6350 bool (*isKindWeWant)(Decl::Kind),
6351 SmallVectorImpl<Decl*> &Decls) {
6352 // There might be lexical decls in multiple modules, for the TU at
6353 // least. Walk all of the modules in the order they were loaded.
6354 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6355 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6356 ++NumLexicalDeclContextsRead;
6357 return ELR_Success;
6358}
6359
6360namespace {
6361
6362class DeclIDComp {
6363 ASTReader &Reader;
6364 ModuleFile &Mod;
6365
6366public:
6367 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6368
6369 bool operator()(LocalDeclID L, LocalDeclID R) const {
6370 SourceLocation LHS = getLocation(L);
6371 SourceLocation RHS = getLocation(R);
6372 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6373 }
6374
6375 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6376 SourceLocation RHS = getLocation(R);
6377 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6378 }
6379
6380 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6381 SourceLocation LHS = getLocation(L);
6382 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6383 }
6384
6385 SourceLocation getLocation(LocalDeclID ID) const {
6386 return Reader.getSourceManager().getFileLoc(
6387 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6388 }
6389};
6390
6391}
6392
6393void ASTReader::FindFileRegionDecls(FileID File,
6394 unsigned Offset, unsigned Length,
6395 SmallVectorImpl<Decl *> &Decls) {
6396 SourceManager &SM = getSourceManager();
6397
6398 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6399 if (I == FileDeclIDs.end())
6400 return;
6401
6402 FileDeclsInfo &DInfo = I->second;
6403 if (DInfo.Decls.empty())
6404 return;
6405
6406 SourceLocation
6407 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6408 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6409
6410 DeclIDComp DIDComp(*this, *DInfo.Mod);
6411 ArrayRef<serialization::LocalDeclID>::iterator
6412 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6413 BeginLoc, DIDComp);
6414 if (BeginIt != DInfo.Decls.begin())
6415 --BeginIt;
6416
6417 // If we are pointing at a top-level decl inside an objc container, we need
6418 // to backtrack until we find it otherwise we will fail to report that the
6419 // region overlaps with an objc container.
6420 while (BeginIt != DInfo.Decls.begin() &&
6421 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6422 ->isTopLevelDeclInObjCContainer())
6423 --BeginIt;
6424
6425 ArrayRef<serialization::LocalDeclID>::iterator
6426 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6427 EndLoc, DIDComp);
6428 if (EndIt != DInfo.Decls.end())
6429 ++EndIt;
6430
6431 for (ArrayRef<serialization::LocalDeclID>::iterator
6432 DIt = BeginIt; DIt != EndIt; ++DIt)
6433 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6434}
6435
6436namespace {
6437 /// \brief ModuleFile visitor used to perform name lookup into a
6438 /// declaration context.
6439 class DeclContextNameLookupVisitor {
6440 ASTReader &Reader;
Richard Smith8c913ec2014-08-14 02:21:01 +00006441 ArrayRef<const DeclContext *> Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006442 DeclarationName Name;
6443 SmallVectorImpl<NamedDecl *> &Decls;
6444
6445 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006446 DeclContextNameLookupVisitor(ASTReader &Reader,
6447 ArrayRef<const DeclContext *> Contexts,
Guy Benyei11169dd2012-12-18 14:30:41 +00006448 DeclarationName Name,
6449 SmallVectorImpl<NamedDecl *> &Decls)
6450 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
6451
6452 static bool visit(ModuleFile &M, void *UserData) {
6453 DeclContextNameLookupVisitor *This
6454 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6455
6456 // Check whether we have any visible declaration information for
6457 // this context in this module.
6458 ModuleFile::DeclContextInfosMap::iterator Info;
6459 bool FoundInfo = false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006460 for (auto *DC : This->Contexts) {
6461 Info = M.DeclContextInfos.find(DC);
6462 if (Info != M.DeclContextInfos.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006463 Info->second.NameLookupTableData) {
6464 FoundInfo = true;
6465 break;
6466 }
6467 }
6468
6469 if (!FoundInfo)
6470 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006471
Guy Benyei11169dd2012-12-18 14:30:41 +00006472 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006473 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006474 Info->second.NameLookupTableData;
6475 ASTDeclContextNameLookupTable::iterator Pos
6476 = LookupTable->find(This->Name);
6477 if (Pos == LookupTable->end())
6478 return false;
6479
6480 bool FoundAnything = false;
6481 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6482 for (; Data.first != Data.second; ++Data.first) {
6483 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6484 if (!ND)
6485 continue;
6486
6487 if (ND->getDeclName() != This->Name) {
6488 // A name might be null because the decl's redeclarable part is
6489 // currently read before reading its name. The lookup is triggered by
6490 // building that decl (likely indirectly), and so it is later in the
6491 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006492 // FIXME: This should not happen; deserializing declarations should
6493 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006494 continue;
6495 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006496
Guy Benyei11169dd2012-12-18 14:30:41 +00006497 // Record this declaration.
6498 FoundAnything = true;
6499 This->Decls.push_back(ND);
6500 }
6501
6502 return FoundAnything;
6503 }
6504 };
6505}
6506
Douglas Gregor9f782892013-01-21 15:25:38 +00006507/// \brief Retrieve the "definitive" module file for the definition of the
6508/// given declaration context, if there is one.
6509///
6510/// The "definitive" module file is the only place where we need to look to
6511/// find information about the declarations within the given declaration
6512/// context. For example, C++ and Objective-C classes, C structs/unions, and
6513/// Objective-C protocols, categories, and extensions are all defined in a
6514/// single place in the source code, so they have definitive module files
6515/// associated with them. C++ namespaces, on the other hand, can have
6516/// definitions in multiple different module files.
6517///
6518/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6519/// NDEBUG checking.
6520static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6521 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006522 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6523 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006524
Craig Toppera13603a2014-05-22 05:54:18 +00006525 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006526}
6527
Richard Smith9ce12e32013-02-07 03:30:24 +00006528bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006529ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6530 DeclarationName Name) {
6531 assert(DC->hasExternalVisibleStorage() &&
6532 "DeclContext has no visible decls in storage");
6533 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006534 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006535
Richard Smith8c913ec2014-08-14 02:21:01 +00006536 Deserializing LookupResults(this);
6537
Guy Benyei11169dd2012-12-18 14:30:41 +00006538 SmallVector<NamedDecl *, 64> Decls;
Richard Smith8c913ec2014-08-14 02:21:01 +00006539
Guy Benyei11169dd2012-12-18 14:30:41 +00006540 // Compute the declaration contexts we need to look into. Multiple such
6541 // declaration contexts occur when two declaration contexts from disjoint
6542 // modules get merged, e.g., when two namespaces with the same name are
6543 // independently defined in separate modules.
6544 SmallVector<const DeclContext *, 2> Contexts;
6545 Contexts.push_back(DC);
Richard Smith8c913ec2014-08-14 02:21:01 +00006546
Guy Benyei11169dd2012-12-18 14:30:41 +00006547 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006548 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006549 if (Merged != MergedDecls.end()) {
6550 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6551 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6552 }
6553 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006554
6555 auto LookUpInContexts = [&](ArrayRef<const DeclContext*> Contexts) {
6556 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
6557
6558 // If we can definitively determine which module file to look into,
6559 // only look there. Otherwise, look in all module files.
6560 ModuleFile *Definitive;
6561 if (Contexts.size() == 1 &&
6562 (Definitive = getDefinitiveModuleFileFor(Contexts[0], *this))) {
6563 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6564 } else {
6565 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6566 }
6567 };
6568
6569 LookUpInContexts(Contexts);
6570
6571 // If this might be an implicit special member function, then also search
6572 // all merged definitions of the surrounding class. We need to search them
6573 // individually, because finding an entity in one of them doesn't imply that
6574 // we can't find a different entity in another one.
Richard Smithcd45dbc2014-04-19 03:48:30 +00006575 if (isa<CXXRecordDecl>(DC)) {
Richard Smith8c913ec2014-08-14 02:21:01 +00006576 auto Kind = Name.getNameKind();
6577 if (Kind == DeclarationName::CXXConstructorName ||
6578 Kind == DeclarationName::CXXDestructorName ||
6579 (Kind == DeclarationName::CXXOperatorName &&
6580 Name.getCXXOverloadedOperator() == OO_Equal)) {
6581 auto Merged = MergedLookups.find(DC);
Richard Smithe0612472014-11-21 05:16:13 +00006582 if (Merged != MergedLookups.end()) {
6583 for (unsigned I = 0; I != Merged->second.size(); ++I) {
6584 LookUpInContexts(Merged->second[I]);
6585 // We might have just added some more merged lookups. If so, our
6586 // iterator is now invalid, so grab a fresh one before continuing.
6587 Merged = MergedLookups.find(DC);
6588 }
6589 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006590 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006591 }
6592
Guy Benyei11169dd2012-12-18 14:30:41 +00006593 ++NumVisibleDeclContextsRead;
6594 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006595 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006596}
6597
6598namespace {
6599 /// \brief ModuleFile visitor used to retrieve all visible names in a
6600 /// declaration context.
6601 class DeclContextAllNamesVisitor {
6602 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006603 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006604 DeclsMap &Decls;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006605 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006606
6607 public:
6608 DeclContextAllNamesVisitor(ASTReader &Reader,
6609 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006610 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006611 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006612
6613 static bool visit(ModuleFile &M, void *UserData) {
6614 DeclContextAllNamesVisitor *This
6615 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6616
6617 // Check whether we have any visible declaration information for
6618 // this context in this module.
6619 ModuleFile::DeclContextInfosMap::iterator Info;
6620 bool FoundInfo = false;
6621 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6622 Info = M.DeclContextInfos.find(This->Contexts[I]);
6623 if (Info != M.DeclContextInfos.end() &&
6624 Info->second.NameLookupTableData) {
6625 FoundInfo = true;
6626 break;
6627 }
6628 }
6629
6630 if (!FoundInfo)
6631 return false;
6632
Richard Smith52e3fba2014-03-11 07:17:35 +00006633 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006634 Info->second.NameLookupTableData;
6635 bool FoundAnything = false;
6636 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006637 I = LookupTable->data_begin(), E = LookupTable->data_end();
6638 I != E;
6639 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006640 ASTDeclContextNameLookupTrait::data_type Data = *I;
6641 for (; Data.first != Data.second; ++Data.first) {
6642 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6643 *Data.first);
6644 if (!ND)
6645 continue;
6646
6647 // Record this declaration.
6648 FoundAnything = true;
6649 This->Decls[ND->getDeclName()].push_back(ND);
6650 }
6651 }
6652
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006653 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006654 }
6655 };
6656}
6657
6658void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6659 if (!DC->hasExternalVisibleStorage())
6660 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006661 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006662
6663 // Compute the declaration contexts we need to look into. Multiple such
6664 // declaration contexts occur when two declaration contexts from disjoint
6665 // modules get merged, e.g., when two namespaces with the same name are
6666 // independently defined in separate modules.
6667 SmallVector<const DeclContext *, 2> Contexts;
6668 Contexts.push_back(DC);
6669
6670 if (DC->isNamespace()) {
6671 MergedDeclsMap::iterator Merged
6672 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6673 if (Merged != MergedDecls.end()) {
6674 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6675 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6676 }
6677 }
6678
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006679 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6680 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006681 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6682 ++NumVisibleDeclContextsRead;
6683
Craig Topper79be4cd2013-07-05 04:33:53 +00006684 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006685 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6686 }
6687 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6688}
6689
6690/// \brief Under non-PCH compilation the consumer receives the objc methods
6691/// before receiving the implementation, and codegen depends on this.
6692/// We simulate this by deserializing and passing to consumer the methods of the
6693/// implementation before passing the deserialized implementation decl.
6694static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6695 ASTConsumer *Consumer) {
6696 assert(ImplD && Consumer);
6697
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006698 for (auto *I : ImplD->methods())
6699 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006700
6701 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6702}
6703
6704void ASTReader::PassInterestingDeclsToConsumer() {
6705 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006706
6707 if (PassingDeclsToConsumer)
6708 return;
6709
6710 // Guard variable to avoid recursively redoing the process of passing
6711 // decls to consumer.
6712 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6713 true);
6714
Guy Benyei11169dd2012-12-18 14:30:41 +00006715 while (!InterestingDecls.empty()) {
6716 Decl *D = InterestingDecls.front();
6717 InterestingDecls.pop_front();
6718
6719 PassInterestingDeclToConsumer(D);
6720 }
6721}
6722
6723void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6724 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6725 PassObjCImplDeclToConsumer(ImplD, Consumer);
6726 else
6727 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6728}
6729
6730void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6731 this->Consumer = Consumer;
6732
6733 if (!Consumer)
6734 return;
6735
Ben Langmuir332aafe2014-01-31 01:06:56 +00006736 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006737 // Force deserialization of this decl, which will cause it to be queued for
6738 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006739 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006740 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006741 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006742
6743 PassInterestingDeclsToConsumer();
6744}
6745
6746void ASTReader::PrintStats() {
6747 std::fprintf(stderr, "*** AST File Statistics:\n");
6748
6749 unsigned NumTypesLoaded
6750 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6751 QualType());
6752 unsigned NumDeclsLoaded
6753 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006754 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006755 unsigned NumIdentifiersLoaded
6756 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6757 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006758 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006759 unsigned NumMacrosLoaded
6760 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6761 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006762 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006763 unsigned NumSelectorsLoaded
6764 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6765 SelectorsLoaded.end(),
6766 Selector());
6767
6768 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6769 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6770 NumSLocEntriesRead, TotalNumSLocEntries,
6771 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6772 if (!TypesLoaded.empty())
6773 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6774 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6775 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6776 if (!DeclsLoaded.empty())
6777 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6778 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6779 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6780 if (!IdentifiersLoaded.empty())
6781 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6782 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6783 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6784 if (!MacrosLoaded.empty())
6785 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6786 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6787 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6788 if (!SelectorsLoaded.empty())
6789 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6790 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6791 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6792 if (TotalNumStatements)
6793 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6794 NumStatementsRead, TotalNumStatements,
6795 ((float)NumStatementsRead/TotalNumStatements * 100));
6796 if (TotalNumMacros)
6797 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6798 NumMacrosRead, TotalNumMacros,
6799 ((float)NumMacrosRead/TotalNumMacros * 100));
6800 if (TotalLexicalDeclContexts)
6801 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6802 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6803 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6804 * 100));
6805 if (TotalVisibleDeclContexts)
6806 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6807 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6808 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6809 * 100));
6810 if (TotalNumMethodPoolEntries) {
6811 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6812 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6813 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6814 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006815 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006816 if (NumMethodPoolLookups) {
6817 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6818 NumMethodPoolHits, NumMethodPoolLookups,
6819 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6820 }
6821 if (NumMethodPoolTableLookups) {
6822 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6823 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6824 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6825 * 100.0));
6826 }
6827
Douglas Gregor00a50f72013-01-25 00:38:33 +00006828 if (NumIdentifierLookupHits) {
6829 std::fprintf(stderr,
6830 " %u / %u identifier table lookups succeeded (%f%%)\n",
6831 NumIdentifierLookupHits, NumIdentifierLookups,
6832 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6833 }
6834
Douglas Gregore060e572013-01-25 01:03:03 +00006835 if (GlobalIndex) {
6836 std::fprintf(stderr, "\n");
6837 GlobalIndex->printStats();
6838 }
6839
Guy Benyei11169dd2012-12-18 14:30:41 +00006840 std::fprintf(stderr, "\n");
6841 dump();
6842 std::fprintf(stderr, "\n");
6843}
6844
6845template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6846static void
6847dumpModuleIDMap(StringRef Name,
6848 const ContinuousRangeMap<Key, ModuleFile *,
6849 InitialCapacity> &Map) {
6850 if (Map.begin() == Map.end())
6851 return;
6852
6853 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6854 llvm::errs() << Name << ":\n";
6855 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6856 I != IEnd; ++I) {
6857 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6858 << "\n";
6859 }
6860}
6861
6862void ASTReader::dump() {
6863 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6864 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6865 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6866 dumpModuleIDMap("Global type map", GlobalTypeMap);
6867 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6868 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6869 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6870 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6871 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6872 dumpModuleIDMap("Global preprocessed entity map",
6873 GlobalPreprocessedEntityMap);
6874
6875 llvm::errs() << "\n*** PCH/Modules Loaded:";
6876 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6877 MEnd = ModuleMgr.end();
6878 M != MEnd; ++M)
6879 (*M)->dump();
6880}
6881
6882/// Return the amount of memory used by memory buffers, breaking down
6883/// by heap-backed versus mmap'ed memory.
6884void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6885 for (ModuleConstIterator I = ModuleMgr.begin(),
6886 E = ModuleMgr.end(); I != E; ++I) {
6887 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6888 size_t bytes = buf->getBufferSize();
6889 switch (buf->getBufferKind()) {
6890 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6891 sizes.malloc_bytes += bytes;
6892 break;
6893 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6894 sizes.mmap_bytes += bytes;
6895 break;
6896 }
6897 }
6898 }
6899}
6900
6901void ASTReader::InitializeSema(Sema &S) {
6902 SemaObj = &S;
6903 S.addExternalSource(this);
6904
6905 // Makes sure any declarations that were deserialized "too early"
6906 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006907 for (uint64_t ID : PreloadedDeclIDs) {
6908 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6909 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006910 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006911 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006912
Richard Smith3d8e97e2013-10-18 06:54:39 +00006913 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006914 if (!FPPragmaOptions.empty()) {
6915 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6916 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6917 }
6918
Richard Smith3d8e97e2013-10-18 06:54:39 +00006919 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006920 if (!OpenCLExtensions.empty()) {
6921 unsigned I = 0;
6922#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6923#include "clang/Basic/OpenCLExtensions.def"
6924
6925 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6926 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006927
6928 UpdateSema();
6929}
6930
6931void ASTReader::UpdateSema() {
6932 assert(SemaObj && "no Sema to update");
6933
6934 // Load the offsets of the declarations that Sema references.
6935 // They will be lazily deserialized when needed.
6936 if (!SemaDeclRefs.empty()) {
6937 assert(SemaDeclRefs.size() % 2 == 0);
6938 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6939 if (!SemaObj->StdNamespace)
6940 SemaObj->StdNamespace = SemaDeclRefs[I];
6941 if (!SemaObj->StdBadAlloc)
6942 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6943 }
6944 SemaDeclRefs.clear();
6945 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006946
6947 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6948 // encountered the pragma in the source.
6949 if(OptimizeOffPragmaLocation.isValid())
6950 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006951}
6952
6953IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6954 // Note that we are loading an identifier.
6955 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006956 StringRef Name(NameStart, NameEnd - NameStart);
6957
6958 // If there is a global index, look there first to determine which modules
6959 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006960 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00006961 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00006962 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006963 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6964 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006965 }
6966 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006967 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006968 NumIdentifierLookups,
6969 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006970 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006971 IdentifierInfo *II = Visitor.getIdentifierInfo();
6972 markIdentifierUpToDate(II);
6973 return II;
6974}
6975
6976namespace clang {
6977 /// \brief An identifier-lookup iterator that enumerates all of the
6978 /// identifiers stored within a set of AST files.
6979 class ASTIdentifierIterator : public IdentifierIterator {
6980 /// \brief The AST reader whose identifiers are being enumerated.
6981 const ASTReader &Reader;
6982
6983 /// \brief The current index into the chain of AST files stored in
6984 /// the AST reader.
6985 unsigned Index;
6986
6987 /// \brief The current position within the identifier lookup table
6988 /// of the current AST file.
6989 ASTIdentifierLookupTable::key_iterator Current;
6990
6991 /// \brief The end position within the identifier lookup table of
6992 /// the current AST file.
6993 ASTIdentifierLookupTable::key_iterator End;
6994
6995 public:
6996 explicit ASTIdentifierIterator(const ASTReader &Reader);
6997
Craig Topper3e89dfe2014-03-13 02:13:41 +00006998 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006999 };
7000}
7001
7002ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
7003 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
7004 ASTIdentifierLookupTable *IdTable
7005 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
7006 Current = IdTable->key_begin();
7007 End = IdTable->key_end();
7008}
7009
7010StringRef ASTIdentifierIterator::Next() {
7011 while (Current == End) {
7012 // If we have exhausted all of our AST files, we're done.
7013 if (Index == 0)
7014 return StringRef();
7015
7016 --Index;
7017 ASTIdentifierLookupTable *IdTable
7018 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
7019 IdentifierLookupTable;
7020 Current = IdTable->key_begin();
7021 End = IdTable->key_end();
7022 }
7023
7024 // We have any identifiers remaining in the current AST file; return
7025 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007026 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007027 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007028 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007029}
7030
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007031IdentifierIterator *ASTReader::getIdentifiers() {
7032 if (!loadGlobalIndex())
7033 return GlobalIndex->createIdentifierIterator();
7034
Guy Benyei11169dd2012-12-18 14:30:41 +00007035 return new ASTIdentifierIterator(*this);
7036}
7037
7038namespace clang { namespace serialization {
7039 class ReadMethodPoolVisitor {
7040 ASTReader &Reader;
7041 Selector Sel;
7042 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007043 unsigned InstanceBits;
7044 unsigned FactoryBits;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007045 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7046 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007047
7048 public:
7049 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
7050 unsigned PriorGeneration)
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007051 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
7052 InstanceBits(0), FactoryBits(0) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00007053
7054 static bool visit(ModuleFile &M, void *UserData) {
7055 ReadMethodPoolVisitor *This
7056 = static_cast<ReadMethodPoolVisitor *>(UserData);
7057
7058 if (!M.SelectorLookupTable)
7059 return false;
7060
7061 // If we've already searched this module file, skip it now.
7062 if (M.Generation <= This->PriorGeneration)
7063 return true;
7064
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007065 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007066 ASTSelectorLookupTable *PoolTable
7067 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
7068 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
7069 if (Pos == PoolTable->end())
7070 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007071
7072 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00007073 ++This->Reader.NumSelectorsRead;
7074 // FIXME: Not quite happy with the statistics here. We probably should
7075 // disable this tracking when called via LoadSelector.
7076 // Also, should entries without methods count as misses?
7077 ++This->Reader.NumMethodPoolEntriesRead;
7078 ASTSelectorLookupTrait::data_type Data = *Pos;
7079 if (This->Reader.DeserializationListener)
7080 This->Reader.DeserializationListener->SelectorRead(Data.ID,
7081 This->Sel);
7082
7083 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7084 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007085 This->InstanceBits = Data.InstanceBits;
7086 This->FactoryBits = Data.FactoryBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00007087 return true;
7088 }
7089
7090 /// \brief Retrieve the instance methods found by this visitor.
7091 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7092 return InstanceMethods;
7093 }
7094
7095 /// \brief Retrieve the instance methods found by this visitor.
7096 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7097 return FactoryMethods;
7098 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007099
7100 unsigned getInstanceBits() const { return InstanceBits; }
7101 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007102 };
7103} } // end namespace clang::serialization
7104
7105/// \brief Add the given set of methods to the method list.
7106static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7107 ObjCMethodList &List) {
7108 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7109 S.addMethodToGlobalList(&List, Methods[I]);
7110 }
7111}
7112
7113void ASTReader::ReadMethodPool(Selector Sel) {
7114 // Get the selector generation and update it to the current generation.
7115 unsigned &Generation = SelectorGeneration[Sel];
7116 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007117 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007118
7119 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007120 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007121 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7122 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
7123
7124 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007125 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007126 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007127
7128 ++NumMethodPoolHits;
7129
Guy Benyei11169dd2012-12-18 14:30:41 +00007130 if (!getSema())
7131 return;
7132
7133 Sema &S = *getSema();
7134 Sema::GlobalMethodPool::iterator Pos
7135 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
7136
7137 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7138 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007139 Pos->second.first.setBits(Visitor.getInstanceBits());
7140 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei11169dd2012-12-18 14:30:41 +00007141}
7142
7143void ASTReader::ReadKnownNamespaces(
7144 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7145 Namespaces.clear();
7146
7147 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7148 if (NamespaceDecl *Namespace
7149 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7150 Namespaces.push_back(Namespace);
7151 }
7152}
7153
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007154void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007155 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007156 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7157 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007158 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007159 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007160 Undefined.insert(std::make_pair(D, Loc));
7161 }
7162}
Nick Lewycky8334af82013-01-26 00:35:08 +00007163
Guy Benyei11169dd2012-12-18 14:30:41 +00007164void ASTReader::ReadTentativeDefinitions(
7165 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7166 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7167 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7168 if (Var)
7169 TentativeDefs.push_back(Var);
7170 }
7171 TentativeDefinitions.clear();
7172}
7173
7174void ASTReader::ReadUnusedFileScopedDecls(
7175 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7176 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7177 DeclaratorDecl *D
7178 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7179 if (D)
7180 Decls.push_back(D);
7181 }
7182 UnusedFileScopedDecls.clear();
7183}
7184
7185void ASTReader::ReadDelegatingConstructors(
7186 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7187 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7188 CXXConstructorDecl *D
7189 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7190 if (D)
7191 Decls.push_back(D);
7192 }
7193 DelegatingCtorDecls.clear();
7194}
7195
7196void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7197 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7198 TypedefNameDecl *D
7199 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7200 if (D)
7201 Decls.push_back(D);
7202 }
7203 ExtVectorDecls.clear();
7204}
7205
7206void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
7207 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
7208 CXXRecordDecl *D
7209 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
7210 if (D)
7211 Decls.push_back(D);
7212 }
7213 DynamicClasses.clear();
7214}
7215
Nico Weber72889432014-09-06 01:25:55 +00007216void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7217 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7218 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7219 ++I) {
7220 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7221 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7222 if (D)
7223 Decls.insert(D);
7224 }
7225 UnusedLocalTypedefNameCandidates.clear();
7226}
7227
Guy Benyei11169dd2012-12-18 14:30:41 +00007228void
Richard Smith78165b52013-01-10 23:43:47 +00007229ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
7230 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
7231 NamedDecl *D
7232 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007233 if (D)
7234 Decls.push_back(D);
7235 }
Richard Smith78165b52013-01-10 23:43:47 +00007236 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007237}
7238
7239void ASTReader::ReadReferencedSelectors(
7240 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7241 if (ReferencedSelectorsData.empty())
7242 return;
7243
7244 // If there are @selector references added them to its pool. This is for
7245 // implementation of -Wselector.
7246 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7247 unsigned I = 0;
7248 while (I < DataSize) {
7249 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7250 SourceLocation SelLoc
7251 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7252 Sels.push_back(std::make_pair(Sel, SelLoc));
7253 }
7254 ReferencedSelectorsData.clear();
7255}
7256
7257void ASTReader::ReadWeakUndeclaredIdentifiers(
7258 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7259 if (WeakUndeclaredIdentifiers.empty())
7260 return;
7261
7262 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7263 IdentifierInfo *WeakId
7264 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7265 IdentifierInfo *AliasId
7266 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7267 SourceLocation Loc
7268 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7269 bool Used = WeakUndeclaredIdentifiers[I++];
7270 WeakInfo WI(AliasId, Loc);
7271 WI.setUsed(Used);
7272 WeakIDs.push_back(std::make_pair(WeakId, WI));
7273 }
7274 WeakUndeclaredIdentifiers.clear();
7275}
7276
7277void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7278 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7279 ExternalVTableUse VT;
7280 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7281 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7282 VT.DefinitionRequired = VTableUses[Idx++];
7283 VTables.push_back(VT);
7284 }
7285
7286 VTableUses.clear();
7287}
7288
7289void ASTReader::ReadPendingInstantiations(
7290 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7291 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7292 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7293 SourceLocation Loc
7294 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7295
7296 Pending.push_back(std::make_pair(D, Loc));
7297 }
7298 PendingInstantiations.clear();
7299}
7300
Richard Smithe40f2ba2013-08-07 21:41:30 +00007301void ASTReader::ReadLateParsedTemplates(
7302 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7303 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7304 /* In loop */) {
7305 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7306
7307 LateParsedTemplate *LT = new LateParsedTemplate;
7308 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7309
7310 ModuleFile *F = getOwningModuleFile(LT->D);
7311 assert(F && "No module");
7312
7313 unsigned TokN = LateParsedTemplates[Idx++];
7314 LT->Toks.reserve(TokN);
7315 for (unsigned T = 0; T < TokN; ++T)
7316 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7317
7318 LPTMap[FD] = LT;
7319 }
7320
7321 LateParsedTemplates.clear();
7322}
7323
Guy Benyei11169dd2012-12-18 14:30:41 +00007324void ASTReader::LoadSelector(Selector Sel) {
7325 // It would be complicated to avoid reading the methods anyway. So don't.
7326 ReadMethodPool(Sel);
7327}
7328
7329void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7330 assert(ID && "Non-zero identifier ID required");
7331 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7332 IdentifiersLoaded[ID - 1] = II;
7333 if (DeserializationListener)
7334 DeserializationListener->IdentifierRead(ID, II);
7335}
7336
7337/// \brief Set the globally-visible declarations associated with the given
7338/// identifier.
7339///
7340/// If the AST reader is currently in a state where the given declaration IDs
7341/// cannot safely be resolved, they are queued until it is safe to resolve
7342/// them.
7343///
7344/// \param II an IdentifierInfo that refers to one or more globally-visible
7345/// declarations.
7346///
7347/// \param DeclIDs the set of declaration IDs with the name @p II that are
7348/// visible at global scope.
7349///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007350/// \param Decls if non-null, this vector will be populated with the set of
7351/// deserialized declarations. These declarations will not be pushed into
7352/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007353void
7354ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7355 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007356 SmallVectorImpl<Decl *> *Decls) {
7357 if (NumCurrentElementsDeserializing && !Decls) {
7358 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007359 return;
7360 }
7361
7362 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007363 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007364 // Queue this declaration so that it will be added to the
7365 // translation unit scope and identifier's declaration chain
7366 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007367 PreloadedDeclIDs.push_back(DeclIDs[I]);
7368 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007369 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007370
7371 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7372
7373 // If we're simply supposed to record the declarations, do so now.
7374 if (Decls) {
7375 Decls->push_back(D);
7376 continue;
7377 }
7378
7379 // Introduce this declaration into the translation-unit scope
7380 // and add it to the declaration chain for this identifier, so
7381 // that (unqualified) name lookup will find it.
7382 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007383 }
7384}
7385
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007386IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007387 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007388 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007389
7390 if (IdentifiersLoaded.empty()) {
7391 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007392 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007393 }
7394
7395 ID -= 1;
7396 if (!IdentifiersLoaded[ID]) {
7397 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7398 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7399 ModuleFile *M = I->second;
7400 unsigned Index = ID - M->BaseIdentifierID;
7401 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7402
7403 // All of the strings in the AST file are preceded by a 16-bit length.
7404 // Extract that 16-bit length to avoid having to execute strlen().
7405 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7406 // unsigned integers. This is important to avoid integer overflow when
7407 // we cast them to 'unsigned'.
7408 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7409 unsigned StrLen = (((unsigned) StrLenPtr[0])
7410 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007411 IdentifiersLoaded[ID]
7412 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007413 if (DeserializationListener)
7414 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7415 }
7416
7417 return IdentifiersLoaded[ID];
7418}
7419
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007420IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7421 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007422}
7423
7424IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7425 if (LocalID < NUM_PREDEF_IDENT_IDS)
7426 return LocalID;
7427
7428 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7429 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7430 assert(I != M.IdentifierRemap.end()
7431 && "Invalid index into identifier index remap");
7432
7433 return LocalID + I->second;
7434}
7435
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007436MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007437 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007438 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007439
7440 if (MacrosLoaded.empty()) {
7441 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007442 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007443 }
7444
7445 ID -= NUM_PREDEF_MACRO_IDS;
7446 if (!MacrosLoaded[ID]) {
7447 GlobalMacroMapType::iterator I
7448 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7449 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7450 ModuleFile *M = I->second;
7451 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007452 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7453
7454 if (DeserializationListener)
7455 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7456 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007457 }
7458
7459 return MacrosLoaded[ID];
7460}
7461
7462MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7463 if (LocalID < NUM_PREDEF_MACRO_IDS)
7464 return LocalID;
7465
7466 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7467 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7468 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7469
7470 return LocalID + I->second;
7471}
7472
7473serialization::SubmoduleID
7474ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7475 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7476 return LocalID;
7477
7478 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7479 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7480 assert(I != M.SubmoduleRemap.end()
7481 && "Invalid index into submodule index remap");
7482
7483 return LocalID + I->second;
7484}
7485
7486Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7487 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7488 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007489 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007490 }
7491
7492 if (GlobalID > SubmodulesLoaded.size()) {
7493 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007494 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007495 }
7496
7497 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7498}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007499
7500Module *ASTReader::getModule(unsigned ID) {
7501 return getSubmodule(ID);
7502}
7503
Guy Benyei11169dd2012-12-18 14:30:41 +00007504Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7505 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7506}
7507
7508Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7509 if (ID == 0)
7510 return Selector();
7511
7512 if (ID > SelectorsLoaded.size()) {
7513 Error("selector ID out of range in AST file");
7514 return Selector();
7515 }
7516
Craig Toppera13603a2014-05-22 05:54:18 +00007517 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007518 // Load this selector from the selector table.
7519 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7520 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7521 ModuleFile &M = *I->second;
7522 ASTSelectorLookupTrait Trait(*this, M);
7523 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7524 SelectorsLoaded[ID - 1] =
7525 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7526 if (DeserializationListener)
7527 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7528 }
7529
7530 return SelectorsLoaded[ID - 1];
7531}
7532
7533Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7534 return DecodeSelector(ID);
7535}
7536
7537uint32_t ASTReader::GetNumExternalSelectors() {
7538 // ID 0 (the null selector) is considered an external selector.
7539 return getTotalNumSelectors() + 1;
7540}
7541
7542serialization::SelectorID
7543ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7544 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7545 return LocalID;
7546
7547 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7548 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7549 assert(I != M.SelectorRemap.end()
7550 && "Invalid index into selector index remap");
7551
7552 return LocalID + I->second;
7553}
7554
7555DeclarationName
7556ASTReader::ReadDeclarationName(ModuleFile &F,
7557 const RecordData &Record, unsigned &Idx) {
7558 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7559 switch (Kind) {
7560 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007561 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007562
7563 case DeclarationName::ObjCZeroArgSelector:
7564 case DeclarationName::ObjCOneArgSelector:
7565 case DeclarationName::ObjCMultiArgSelector:
7566 return DeclarationName(ReadSelector(F, Record, Idx));
7567
7568 case DeclarationName::CXXConstructorName:
7569 return Context.DeclarationNames.getCXXConstructorName(
7570 Context.getCanonicalType(readType(F, Record, Idx)));
7571
7572 case DeclarationName::CXXDestructorName:
7573 return Context.DeclarationNames.getCXXDestructorName(
7574 Context.getCanonicalType(readType(F, Record, Idx)));
7575
7576 case DeclarationName::CXXConversionFunctionName:
7577 return Context.DeclarationNames.getCXXConversionFunctionName(
7578 Context.getCanonicalType(readType(F, Record, Idx)));
7579
7580 case DeclarationName::CXXOperatorName:
7581 return Context.DeclarationNames.getCXXOperatorName(
7582 (OverloadedOperatorKind)Record[Idx++]);
7583
7584 case DeclarationName::CXXLiteralOperatorName:
7585 return Context.DeclarationNames.getCXXLiteralOperatorName(
7586 GetIdentifierInfo(F, Record, Idx));
7587
7588 case DeclarationName::CXXUsingDirective:
7589 return DeclarationName::getUsingDirectiveName();
7590 }
7591
7592 llvm_unreachable("Invalid NameKind!");
7593}
7594
7595void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7596 DeclarationNameLoc &DNLoc,
7597 DeclarationName Name,
7598 const RecordData &Record, unsigned &Idx) {
7599 switch (Name.getNameKind()) {
7600 case DeclarationName::CXXConstructorName:
7601 case DeclarationName::CXXDestructorName:
7602 case DeclarationName::CXXConversionFunctionName:
7603 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7604 break;
7605
7606 case DeclarationName::CXXOperatorName:
7607 DNLoc.CXXOperatorName.BeginOpNameLoc
7608 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7609 DNLoc.CXXOperatorName.EndOpNameLoc
7610 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7611 break;
7612
7613 case DeclarationName::CXXLiteralOperatorName:
7614 DNLoc.CXXLiteralOperatorName.OpNameLoc
7615 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7616 break;
7617
7618 case DeclarationName::Identifier:
7619 case DeclarationName::ObjCZeroArgSelector:
7620 case DeclarationName::ObjCOneArgSelector:
7621 case DeclarationName::ObjCMultiArgSelector:
7622 case DeclarationName::CXXUsingDirective:
7623 break;
7624 }
7625}
7626
7627void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7628 DeclarationNameInfo &NameInfo,
7629 const RecordData &Record, unsigned &Idx) {
7630 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7631 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7632 DeclarationNameLoc DNLoc;
7633 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7634 NameInfo.setInfo(DNLoc);
7635}
7636
7637void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7638 const RecordData &Record, unsigned &Idx) {
7639 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7640 unsigned NumTPLists = Record[Idx++];
7641 Info.NumTemplParamLists = NumTPLists;
7642 if (NumTPLists) {
7643 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7644 for (unsigned i=0; i != NumTPLists; ++i)
7645 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7646 }
7647}
7648
7649TemplateName
7650ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7651 unsigned &Idx) {
7652 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7653 switch (Kind) {
7654 case TemplateName::Template:
7655 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7656
7657 case TemplateName::OverloadedTemplate: {
7658 unsigned size = Record[Idx++];
7659 UnresolvedSet<8> Decls;
7660 while (size--)
7661 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7662
7663 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7664 }
7665
7666 case TemplateName::QualifiedTemplate: {
7667 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7668 bool hasTemplKeyword = Record[Idx++];
7669 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7670 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7671 }
7672
7673 case TemplateName::DependentTemplate: {
7674 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7675 if (Record[Idx++]) // isIdentifier
7676 return Context.getDependentTemplateName(NNS,
7677 GetIdentifierInfo(F, Record,
7678 Idx));
7679 return Context.getDependentTemplateName(NNS,
7680 (OverloadedOperatorKind)Record[Idx++]);
7681 }
7682
7683 case TemplateName::SubstTemplateTemplateParm: {
7684 TemplateTemplateParmDecl *param
7685 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7686 if (!param) return TemplateName();
7687 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7688 return Context.getSubstTemplateTemplateParm(param, replacement);
7689 }
7690
7691 case TemplateName::SubstTemplateTemplateParmPack: {
7692 TemplateTemplateParmDecl *Param
7693 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7694 if (!Param)
7695 return TemplateName();
7696
7697 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7698 if (ArgPack.getKind() != TemplateArgument::Pack)
7699 return TemplateName();
7700
7701 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7702 }
7703 }
7704
7705 llvm_unreachable("Unhandled template name kind!");
7706}
7707
7708TemplateArgument
7709ASTReader::ReadTemplateArgument(ModuleFile &F,
7710 const RecordData &Record, unsigned &Idx) {
7711 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7712 switch (Kind) {
7713 case TemplateArgument::Null:
7714 return TemplateArgument();
7715 case TemplateArgument::Type:
7716 return TemplateArgument(readType(F, Record, Idx));
7717 case TemplateArgument::Declaration: {
7718 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007719 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007720 }
7721 case TemplateArgument::NullPtr:
7722 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7723 case TemplateArgument::Integral: {
7724 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7725 QualType T = readType(F, Record, Idx);
7726 return TemplateArgument(Context, Value, T);
7727 }
7728 case TemplateArgument::Template:
7729 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7730 case TemplateArgument::TemplateExpansion: {
7731 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007732 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007733 if (unsigned NumExpansions = Record[Idx++])
7734 NumTemplateExpansions = NumExpansions - 1;
7735 return TemplateArgument(Name, NumTemplateExpansions);
7736 }
7737 case TemplateArgument::Expression:
7738 return TemplateArgument(ReadExpr(F));
7739 case TemplateArgument::Pack: {
7740 unsigned NumArgs = Record[Idx++];
7741 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7742 for (unsigned I = 0; I != NumArgs; ++I)
7743 Args[I] = ReadTemplateArgument(F, Record, Idx);
7744 return TemplateArgument(Args, NumArgs);
7745 }
7746 }
7747
7748 llvm_unreachable("Unhandled template argument kind!");
7749}
7750
7751TemplateParameterList *
7752ASTReader::ReadTemplateParameterList(ModuleFile &F,
7753 const RecordData &Record, unsigned &Idx) {
7754 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7755 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7756 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7757
7758 unsigned NumParams = Record[Idx++];
7759 SmallVector<NamedDecl *, 16> Params;
7760 Params.reserve(NumParams);
7761 while (NumParams--)
7762 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7763
7764 TemplateParameterList* TemplateParams =
7765 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7766 Params.data(), Params.size(), RAngleLoc);
7767 return TemplateParams;
7768}
7769
7770void
7771ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007772ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007773 ModuleFile &F, const RecordData &Record,
7774 unsigned &Idx) {
7775 unsigned NumTemplateArgs = Record[Idx++];
7776 TemplArgs.reserve(NumTemplateArgs);
7777 while (NumTemplateArgs--)
7778 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7779}
7780
7781/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007782void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007783 const RecordData &Record, unsigned &Idx) {
7784 unsigned NumDecls = Record[Idx++];
7785 Set.reserve(Context, NumDecls);
7786 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007787 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007788 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007789 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007790 }
7791}
7792
7793CXXBaseSpecifier
7794ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7795 const RecordData &Record, unsigned &Idx) {
7796 bool isVirtual = static_cast<bool>(Record[Idx++]);
7797 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7798 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7799 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7800 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7801 SourceRange Range = ReadSourceRange(F, Record, Idx);
7802 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7803 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7804 EllipsisLoc);
7805 Result.setInheritConstructors(inheritConstructors);
7806 return Result;
7807}
7808
7809std::pair<CXXCtorInitializer **, unsigned>
7810ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7811 unsigned &Idx) {
Craig Toppera13603a2014-05-22 05:54:18 +00007812 CXXCtorInitializer **CtorInitializers = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007813 unsigned NumInitializers = Record[Idx++];
7814 if (NumInitializers) {
7815 CtorInitializers
7816 = new (Context) CXXCtorInitializer*[NumInitializers];
7817 for (unsigned i=0; i != NumInitializers; ++i) {
Craig Toppera13603a2014-05-22 05:54:18 +00007818 TypeSourceInfo *TInfo = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007819 bool IsBaseVirtual = false;
Craig Toppera13603a2014-05-22 05:54:18 +00007820 FieldDecl *Member = nullptr;
7821 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007822
7823 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7824 switch (Type) {
7825 case CTOR_INITIALIZER_BASE:
7826 TInfo = GetTypeSourceInfo(F, Record, Idx);
7827 IsBaseVirtual = Record[Idx++];
7828 break;
7829
7830 case CTOR_INITIALIZER_DELEGATING:
7831 TInfo = GetTypeSourceInfo(F, Record, Idx);
7832 break;
7833
7834 case CTOR_INITIALIZER_MEMBER:
7835 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7836 break;
7837
7838 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7839 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7840 break;
7841 }
7842
7843 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7844 Expr *Init = ReadExpr(F);
7845 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7846 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7847 bool IsWritten = Record[Idx++];
7848 unsigned SourceOrderOrNumArrayIndices;
7849 SmallVector<VarDecl *, 8> Indices;
7850 if (IsWritten) {
7851 SourceOrderOrNumArrayIndices = Record[Idx++];
7852 } else {
7853 SourceOrderOrNumArrayIndices = Record[Idx++];
7854 Indices.reserve(SourceOrderOrNumArrayIndices);
7855 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7856 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7857 }
7858
7859 CXXCtorInitializer *BOMInit;
7860 if (Type == CTOR_INITIALIZER_BASE) {
7861 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7862 LParenLoc, Init, RParenLoc,
7863 MemberOrEllipsisLoc);
7864 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7865 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7866 Init, RParenLoc);
7867 } else if (IsWritten) {
7868 if (Member)
7869 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7870 LParenLoc, Init, RParenLoc);
7871 else
7872 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7873 MemberOrEllipsisLoc, LParenLoc,
7874 Init, RParenLoc);
7875 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007876 if (IndirectMember) {
7877 assert(Indices.empty() && "Indirect field improperly initialized");
7878 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7879 MemberOrEllipsisLoc, LParenLoc,
7880 Init, RParenLoc);
7881 } else {
7882 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7883 LParenLoc, Init, RParenLoc,
7884 Indices.data(), Indices.size());
7885 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007886 }
7887
7888 if (IsWritten)
7889 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7890 CtorInitializers[i] = BOMInit;
7891 }
7892 }
7893
7894 return std::make_pair(CtorInitializers, NumInitializers);
7895}
7896
7897NestedNameSpecifier *
7898ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7899 const RecordData &Record, unsigned &Idx) {
7900 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007901 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007902 for (unsigned I = 0; I != N; ++I) {
7903 NestedNameSpecifier::SpecifierKind Kind
7904 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7905 switch (Kind) {
7906 case NestedNameSpecifier::Identifier: {
7907 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7908 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7909 break;
7910 }
7911
7912 case NestedNameSpecifier::Namespace: {
7913 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7914 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7915 break;
7916 }
7917
7918 case NestedNameSpecifier::NamespaceAlias: {
7919 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7920 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7921 break;
7922 }
7923
7924 case NestedNameSpecifier::TypeSpec:
7925 case NestedNameSpecifier::TypeSpecWithTemplate: {
7926 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7927 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007928 return nullptr;
7929
Guy Benyei11169dd2012-12-18 14:30:41 +00007930 bool Template = Record[Idx++];
7931 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7932 break;
7933 }
7934
7935 case NestedNameSpecifier::Global: {
7936 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7937 // No associated value, and there can't be a prefix.
7938 break;
7939 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007940
7941 case NestedNameSpecifier::Super: {
7942 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7943 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7944 break;
7945 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007946 }
7947 Prev = NNS;
7948 }
7949 return NNS;
7950}
7951
7952NestedNameSpecifierLoc
7953ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7954 unsigned &Idx) {
7955 unsigned N = Record[Idx++];
7956 NestedNameSpecifierLocBuilder Builder;
7957 for (unsigned I = 0; I != N; ++I) {
7958 NestedNameSpecifier::SpecifierKind Kind
7959 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7960 switch (Kind) {
7961 case NestedNameSpecifier::Identifier: {
7962 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7963 SourceRange Range = ReadSourceRange(F, Record, Idx);
7964 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7965 break;
7966 }
7967
7968 case NestedNameSpecifier::Namespace: {
7969 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7970 SourceRange Range = ReadSourceRange(F, Record, Idx);
7971 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7972 break;
7973 }
7974
7975 case NestedNameSpecifier::NamespaceAlias: {
7976 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7977 SourceRange Range = ReadSourceRange(F, Record, Idx);
7978 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7979 break;
7980 }
7981
7982 case NestedNameSpecifier::TypeSpec:
7983 case NestedNameSpecifier::TypeSpecWithTemplate: {
7984 bool Template = Record[Idx++];
7985 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7986 if (!T)
7987 return NestedNameSpecifierLoc();
7988 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7989
7990 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7991 Builder.Extend(Context,
7992 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7993 T->getTypeLoc(), ColonColonLoc);
7994 break;
7995 }
7996
7997 case NestedNameSpecifier::Global: {
7998 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7999 Builder.MakeGlobal(Context, ColonColonLoc);
8000 break;
8001 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008002
8003 case NestedNameSpecifier::Super: {
8004 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8005 SourceRange Range = ReadSourceRange(F, Record, Idx);
8006 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8007 break;
8008 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008009 }
8010 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008011
Guy Benyei11169dd2012-12-18 14:30:41 +00008012 return Builder.getWithLocInContext(Context);
8013}
8014
8015SourceRange
8016ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8017 unsigned &Idx) {
8018 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8019 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8020 return SourceRange(beg, end);
8021}
8022
8023/// \brief Read an integral value
8024llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8025 unsigned BitWidth = Record[Idx++];
8026 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8027 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8028 Idx += NumWords;
8029 return Result;
8030}
8031
8032/// \brief Read a signed integral value
8033llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8034 bool isUnsigned = Record[Idx++];
8035 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8036}
8037
8038/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008039llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8040 const llvm::fltSemantics &Sem,
8041 unsigned &Idx) {
8042 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008043}
8044
8045// \brief Read a string
8046std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8047 unsigned Len = Record[Idx++];
8048 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8049 Idx += Len;
8050 return Result;
8051}
8052
8053VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8054 unsigned &Idx) {
8055 unsigned Major = Record[Idx++];
8056 unsigned Minor = Record[Idx++];
8057 unsigned Subminor = Record[Idx++];
8058 if (Minor == 0)
8059 return VersionTuple(Major);
8060 if (Subminor == 0)
8061 return VersionTuple(Major, Minor - 1);
8062 return VersionTuple(Major, Minor - 1, Subminor - 1);
8063}
8064
8065CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8066 const RecordData &Record,
8067 unsigned &Idx) {
8068 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8069 return CXXTemporary::Create(Context, Decl);
8070}
8071
8072DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008073 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008074}
8075
8076DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8077 return Diags.Report(Loc, DiagID);
8078}
8079
8080/// \brief Retrieve the identifier table associated with the
8081/// preprocessor.
8082IdentifierTable &ASTReader::getIdentifierTable() {
8083 return PP.getIdentifierTable();
8084}
8085
8086/// \brief Record that the given ID maps to the given switch-case
8087/// statement.
8088void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008089 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008090 "Already have a SwitchCase with this ID");
8091 (*CurrSwitchCaseStmts)[ID] = SC;
8092}
8093
8094/// \brief Retrieve the switch-case statement with the given ID.
8095SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008096 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008097 return (*CurrSwitchCaseStmts)[ID];
8098}
8099
8100void ASTReader::ClearSwitchCaseIDs() {
8101 CurrSwitchCaseStmts->clear();
8102}
8103
8104void ASTReader::ReadComments() {
8105 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008106 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008107 serialization::ModuleFile *> >::iterator
8108 I = CommentsCursors.begin(),
8109 E = CommentsCursors.end();
8110 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008111 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008112 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008113 serialization::ModuleFile &F = *I->second;
8114 SavedStreamPosition SavedPosition(Cursor);
8115
8116 RecordData Record;
8117 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008118 llvm::BitstreamEntry Entry =
8119 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008120
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008121 switch (Entry.Kind) {
8122 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8123 case llvm::BitstreamEntry::Error:
8124 Error("malformed block record in AST file");
8125 return;
8126 case llvm::BitstreamEntry::EndBlock:
8127 goto NextCursor;
8128 case llvm::BitstreamEntry::Record:
8129 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008130 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008131 }
8132
8133 // Read a record.
8134 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008135 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008136 case COMMENTS_RAW_COMMENT: {
8137 unsigned Idx = 0;
8138 SourceRange SR = ReadSourceRange(F, Record, Idx);
8139 RawComment::CommentKind Kind =
8140 (RawComment::CommentKind) Record[Idx++];
8141 bool IsTrailingComment = Record[Idx++];
8142 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008143 Comments.push_back(new (Context) RawComment(
8144 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8145 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008146 break;
8147 }
8148 }
8149 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008150 NextCursor:
8151 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008152 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008153}
8154
Argyrios Kyrtzidis1bde1172014-11-18 05:24:18 +00008155void ASTReader::getInputFiles(ModuleFile &F,
8156 SmallVectorImpl<serialization::InputFile> &Files) {
8157 for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
8158 unsigned ID = I+1;
8159 Files.push_back(getInputFile(F, ID));
8160 }
8161}
8162
Richard Smithcd45dbc2014-04-19 03:48:30 +00008163std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8164 // If we know the owning module, use it.
8165 if (Module *M = D->getOwningModule())
8166 return M->getFullModuleName();
8167
8168 // Otherwise, use the name of the top-level module the decl is within.
8169 if (ModuleFile *M = getOwningModuleFile(D))
8170 return M->ModuleName;
8171
8172 // Not from a module.
8173 return "";
8174}
8175
Guy Benyei11169dd2012-12-18 14:30:41 +00008176void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008177 while (!PendingIdentifierInfos.empty() ||
8178 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008179 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008180 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008181 // If any identifiers with corresponding top-level declarations have
8182 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008183 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8184 TopLevelDeclsMap;
8185 TopLevelDeclsMap TopLevelDecls;
8186
Guy Benyei11169dd2012-12-18 14:30:41 +00008187 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008188 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008189 SmallVector<uint32_t, 4> DeclIDs =
8190 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008191 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008192
8193 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008194 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008195
Richard Smith851072e2014-05-19 20:59:20 +00008196 // For each decl chain that we wanted to complete while deserializing, mark
8197 // it as "still needs to be completed".
8198 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8199 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8200 }
8201 PendingIncompleteDeclChains.clear();
8202
Guy Benyei11169dd2012-12-18 14:30:41 +00008203 // Load pending declaration chains.
8204 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
8205 loadPendingDeclChain(PendingDeclChains[I]);
8206 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
8207 }
8208 PendingDeclChains.clear();
8209
Douglas Gregor6168bd22013-02-18 15:53:43 +00008210 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008211 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8212 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008213 IdentifierInfo *II = TLD->first;
8214 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008215 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008216 }
8217 }
8218
Guy Benyei11169dd2012-12-18 14:30:41 +00008219 // Load any pending macro definitions.
8220 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008221 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8222 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8223 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8224 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008225 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008226 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008227 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008228 if (Info.M->Kind != MK_ImplicitModule &&
8229 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008230 resolvePendingMacro(II, Info);
8231 }
8232 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008233 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008234 ++IDIdx) {
8235 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008236 if (Info.M->Kind == MK_ImplicitModule ||
8237 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008238 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008239 }
8240 }
8241 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008242
8243 // Wire up the DeclContexts for Decls that we delayed setting until
8244 // recursive loading is completed.
8245 while (!PendingDeclContextInfos.empty()) {
8246 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8247 PendingDeclContextInfos.pop_front();
8248 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8249 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8250 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8251 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008252
Richard Smithd1c46742014-04-30 02:24:17 +00008253 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008254 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008255 auto Update = PendingUpdateRecords.pop_back_val();
8256 ReadingKindTracker ReadingKind(Read_Decl, *this);
8257 loadDeclUpdateRecords(Update.first, Update.second);
8258 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008259 }
8260
8261 // If we deserialized any C++ or Objective-C class definitions, any
8262 // Objective-C protocol definitions, or any redeclarable templates, make sure
8263 // that all redeclarations point to the definitions. Note that this can only
8264 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008265 for (Decl *D : PendingDefinitions) {
8266 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008267 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008268 // Make sure that the TagType points at the definition.
8269 const_cast<TagType*>(TagT)->decl = TD;
8270 }
8271
Craig Topperc6914d02014-08-25 04:15:02 +00008272 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith2c381642014-08-27 23:11:59 +00008273 for (auto R : RD->redecls()) {
8274 assert((R == D) == R->isThisDeclarationADefinition() &&
8275 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008276 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008277 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008278 }
8279
8280 continue;
8281 }
8282
Craig Topperc6914d02014-08-25 04:15:02 +00008283 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008284 // Make sure that the ObjCInterfaceType points at the definition.
8285 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8286 ->Decl = ID;
8287
Aaron Ballman86c93902014-03-06 23:45:36 +00008288 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008289 R->Data = ID->Data;
8290
8291 continue;
8292 }
8293
Craig Topperc6914d02014-08-25 04:15:02 +00008294 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Aaron Ballman86c93902014-03-06 23:45:36 +00008295 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008296 R->Data = PD->Data;
8297
8298 continue;
8299 }
8300
Craig Topperc6914d02014-08-25 04:15:02 +00008301 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00008302 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008303 R->Common = RTD->Common;
8304 }
8305 PendingDefinitions.clear();
8306
8307 // Load the bodies of any functions or methods we've encountered. We do
8308 // this now (delayed) so that we can be sure that the declaration chains
8309 // have been fully wired up.
8310 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8311 PBEnd = PendingBodies.end();
8312 PB != PBEnd; ++PB) {
8313 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8314 // FIXME: Check for =delete/=default?
8315 // FIXME: Complain about ODR violations here?
8316 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8317 FD->setLazyBody(PB->second);
8318 continue;
8319 }
8320
8321 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8322 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8323 MD->setLazyBody(PB->second);
8324 }
8325 PendingBodies.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008326}
8327
8328void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008329 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8330 return;
8331
Richard Smitha0ce9c42014-07-29 23:23:27 +00008332 // Trigger the import of the full definition of each class that had any
8333 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008334 // These updates may in turn find and diagnose some ODR failures, so take
8335 // ownership of the set first.
8336 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8337 PendingOdrMergeFailures.clear();
8338 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008339 Merge.first->buildLookup();
8340 Merge.first->decls_begin();
8341 Merge.first->bases_begin();
8342 Merge.first->vbases_begin();
8343 for (auto *RD : Merge.second) {
8344 RD->decls_begin();
8345 RD->bases_begin();
8346 RD->vbases_begin();
8347 }
8348 }
8349
8350 // For each declaration from a merged context, check that the canonical
8351 // definition of that context also contains a declaration of the same
8352 // entity.
8353 //
8354 // Caution: this loop does things that might invalidate iterators into
8355 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8356 while (!PendingOdrMergeChecks.empty()) {
8357 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8358
8359 // FIXME: Skip over implicit declarations for now. This matters for things
8360 // like implicitly-declared special member functions. This isn't entirely
8361 // correct; we can end up with multiple unmerged declarations of the same
8362 // implicit entity.
8363 if (D->isImplicit())
8364 continue;
8365
8366 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008367
8368 bool Found = false;
8369 const Decl *DCanon = D->getCanonicalDecl();
8370
Richard Smith01bdb7a2014-08-28 05:44:07 +00008371 for (auto RI : D->redecls()) {
8372 if (RI->getLexicalDeclContext() == CanonDef) {
8373 Found = true;
8374 break;
8375 }
8376 }
8377 if (Found)
8378 continue;
8379
Richard Smitha0ce9c42014-07-29 23:23:27 +00008380 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith01bdb7a2014-08-28 05:44:07 +00008381 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
Richard Smitha0ce9c42014-07-29 23:23:27 +00008382 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8383 !Found && I != E; ++I) {
8384 for (auto RI : (*I)->redecls()) {
8385 if (RI->getLexicalDeclContext() == CanonDef) {
8386 // This declaration is present in the canonical definition. If it's
8387 // in the same redecl chain, it's the one we're looking for.
8388 if (RI->getCanonicalDecl() == DCanon)
8389 Found = true;
8390 else
8391 Candidates.push_back(cast<NamedDecl>(RI));
8392 break;
8393 }
8394 }
8395 }
8396
8397 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008398 // The AST doesn't like TagDecls becoming invalid after they've been
8399 // completed. We only really need to mark FieldDecls as invalid here.
8400 if (!isa<TagDecl>(D))
8401 D->setInvalidDecl();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008402
8403 std::string CanonDefModule =
8404 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8405 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8406 << D << getOwningModuleNameForDiagnostic(D)
8407 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8408
8409 if (Candidates.empty())
8410 Diag(cast<Decl>(CanonDef)->getLocation(),
8411 diag::note_module_odr_violation_no_possible_decls) << D;
8412 else {
8413 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8414 Diag(Candidates[I]->getLocation(),
8415 diag::note_module_odr_violation_possible_decl)
8416 << Candidates[I];
8417 }
8418
8419 DiagnosedOdrMergeFailures.insert(CanonDef);
8420 }
8421 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008422
8423 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008424 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008425 // If we've already pointed out a specific problem with this class, don't
8426 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008427 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008428 continue;
8429
8430 bool Diagnosed = false;
8431 for (auto *RD : Merge.second) {
8432 // Multiple different declarations got merged together; tell the user
8433 // where they came from.
8434 if (Merge.first != RD) {
8435 // FIXME: Walk the definition, figure out what's different,
8436 // and diagnose that.
8437 if (!Diagnosed) {
8438 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8439 Diag(Merge.first->getLocation(),
8440 diag::err_module_odr_violation_different_definitions)
8441 << Merge.first << Module.empty() << Module;
8442 Diagnosed = true;
8443 }
8444
8445 Diag(RD->getLocation(),
8446 diag::note_module_odr_violation_different_definitions)
8447 << getOwningModuleNameForDiagnostic(RD);
8448 }
8449 }
8450
8451 if (!Diagnosed) {
8452 // All definitions are updates to the same declaration. This happens if a
8453 // module instantiates the declaration of a class template specialization
8454 // and two or more other modules instantiate its definition.
8455 //
8456 // FIXME: Indicate which modules had instantiations of this definition.
8457 // FIXME: How can this even happen?
8458 Diag(Merge.first->getLocation(),
8459 diag::err_module_odr_violation_different_instantiations)
8460 << Merge.first;
8461 }
8462 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008463}
8464
8465void ASTReader::FinishedDeserializing() {
8466 assert(NumCurrentElementsDeserializing &&
8467 "FinishedDeserializing not paired with StartedDeserializing");
8468 if (NumCurrentElementsDeserializing == 1) {
8469 // We decrease NumCurrentElementsDeserializing only after pending actions
8470 // are finished, to avoid recursively re-calling finishPendingActions().
8471 finishPendingActions();
8472 }
8473 --NumCurrentElementsDeserializing;
8474
Richard Smitha0ce9c42014-07-29 23:23:27 +00008475 if (NumCurrentElementsDeserializing == 0) {
8476 diagnoseOdrViolations();
8477
Richard Smith04d05b52014-03-23 00:27:18 +00008478 // We are not in recursive loading, so it's safe to pass the "interesting"
8479 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008480 if (Consumer)
8481 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008482 }
8483}
8484
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008485void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00008486 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008487
8488 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8489 SemaObj->TUScope->AddDecl(D);
8490 } else if (SemaObj->TUScope) {
8491 // Adding the decl to IdResolver may have failed because it was already in
8492 // (even though it was not added in scope). If it is already in, make sure
8493 // it gets in the scope as well.
8494 if (std::find(SemaObj->IdResolver.begin(Name),
8495 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8496 SemaObj->TUScope->AddDecl(D);
8497 }
8498}
8499
Nico Weber824285e2014-05-08 04:26:47 +00008500ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8501 bool DisableValidation, bool AllowASTWithCompilerErrors,
8502 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008503 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008504 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008505 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Craig Toppera13603a2014-05-22 05:54:18 +00008506 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
8507 SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
8508 ModuleMgr(PP.getFileManager()), isysroot(isysroot),
8509 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008510 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8511 AllowConfigurationMismatch(AllowConfigurationMismatch),
8512 ValidateSystemInputs(ValidateSystemInputs),
8513 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Richard Smith053f6c62014-05-16 23:01:30 +00008514 CurrSwitchCaseStmts(&SwitchCaseStmts),
Nico Weber824285e2014-05-08 04:26:47 +00008515 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8516 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8517 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8518 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8519 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8520 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8521 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8522 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8523 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8524 PassingDeclsToConsumer(false), NumCXXBaseSpecifiersLoaded(0),
8525 ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008526 SourceMgr.setExternalSLocEntrySource(this);
8527}
8528
8529ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008530 if (OwnsDeserializationListener)
8531 delete DeserializationListener;
8532
Guy Benyei11169dd2012-12-18 14:30:41 +00008533 for (DeclContextVisibleUpdatesPending::iterator
8534 I = PendingVisibleUpdates.begin(),
8535 E = PendingVisibleUpdates.end();
8536 I != E; ++I) {
8537 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8538 F = I->second.end();
8539 J != F; ++J)
8540 delete J->first;
8541 }
8542}