blob: e1c418b30c8fe6454ba07c2ae67486e9351deb2e [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,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001032 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001033 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
Richard Smith7ed1bc92014-12-05 22:42:13 +00001040 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001041 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1042 }
1043
1044 // Parse the line entries
1045 std::vector<LineEntry> Entries;
1046 while (Idx < Record.size()) {
1047 int FID = Record[Idx++];
1048 assert(FID >= 0 && "Serialized line entries for non-local file.");
1049 // Remap FileID from 1-based old view.
1050 FID += F.SLocEntryBaseID - 1;
1051
1052 // Extract the line entries
1053 unsigned NumEntries = Record[Idx++];
1054 assert(NumEntries && "Numentries is 00000");
1055 Entries.clear();
1056 Entries.reserve(NumEntries);
1057 for (unsigned I = 0; I != NumEntries; ++I) {
1058 unsigned FileOffset = Record[Idx++];
1059 unsigned LineNo = Record[Idx++];
1060 int FilenameID = FileIDs[Record[Idx++]];
1061 SrcMgr::CharacteristicKind FileKind
1062 = (SrcMgr::CharacteristicKind)Record[Idx++];
1063 unsigned IncludeOffset = Record[Idx++];
1064 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1065 FileKind, IncludeOffset));
1066 }
1067 LineTable.AddEntry(FileID::get(FID), Entries);
1068 }
1069
1070 return false;
1071}
1072
1073/// \brief Read a source manager block
1074bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1075 using namespace SrcMgr;
1076
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001077 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001078
1079 // Set the source-location entry cursor to the current position in
1080 // the stream. This cursor will be used to read the contents of the
1081 // source manager block initially, and then lazily read
1082 // source-location entries as needed.
1083 SLocEntryCursor = F.Stream;
1084
1085 // The stream itself is going to skip over the source manager block.
1086 if (F.Stream.SkipBlock()) {
1087 Error("malformed block record in AST file");
1088 return true;
1089 }
1090
1091 // Enter the source manager block.
1092 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1093 Error("malformed source manager block record in AST file");
1094 return true;
1095 }
1096
1097 RecordData Record;
1098 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001099 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1100
1101 switch (E.Kind) {
1102 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1103 case llvm::BitstreamEntry::Error:
1104 Error("malformed block record in AST file");
1105 return true;
1106 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001107 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001108 case llvm::BitstreamEntry::Record:
1109 // The interesting case.
1110 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001111 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001112
Guy Benyei11169dd2012-12-18 14:30:41 +00001113 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001114 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001115 StringRef Blob;
1116 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001117 default: // Default behavior: ignore.
1118 break;
1119
1120 case SM_SLOC_FILE_ENTRY:
1121 case SM_SLOC_BUFFER_ENTRY:
1122 case SM_SLOC_EXPANSION_ENTRY:
1123 // Once we hit one of the source location entries, we're done.
1124 return false;
1125 }
1126 }
1127}
1128
1129/// \brief If a header file is not found at the path that we expect it to be
1130/// and the PCH file was moved from its original location, try to resolve the
1131/// file by assuming that header+PCH were moved together and the header is in
1132/// the same place relative to the PCH.
1133static std::string
1134resolveFileRelativeToOriginalDir(const std::string &Filename,
1135 const std::string &OriginalDir,
1136 const std::string &CurrDir) {
1137 assert(OriginalDir != CurrDir &&
1138 "No point trying to resolve the file if the PCH dir didn't change");
1139 using namespace llvm::sys;
1140 SmallString<128> filePath(Filename);
1141 fs::make_absolute(filePath);
1142 assert(path::is_absolute(OriginalDir));
1143 SmallString<128> currPCHPath(CurrDir);
1144
1145 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1146 fileDirE = path::end(path::parent_path(filePath));
1147 path::const_iterator origDirI = path::begin(OriginalDir),
1148 origDirE = path::end(OriginalDir);
1149 // Skip the common path components from filePath and OriginalDir.
1150 while (fileDirI != fileDirE && origDirI != origDirE &&
1151 *fileDirI == *origDirI) {
1152 ++fileDirI;
1153 ++origDirI;
1154 }
1155 for (; origDirI != origDirE; ++origDirI)
1156 path::append(currPCHPath, "..");
1157 path::append(currPCHPath, fileDirI, fileDirE);
1158 path::append(currPCHPath, path::filename(Filename));
1159 return currPCHPath.str();
1160}
1161
1162bool ASTReader::ReadSLocEntry(int ID) {
1163 if (ID == 0)
1164 return false;
1165
1166 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1167 Error("source location entry ID out-of-range for AST file");
1168 return true;
1169 }
1170
1171 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1172 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001173 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001174 unsigned BaseOffset = F->SLocEntryBaseOffset;
1175
1176 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001177 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1178 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001179 Error("incorrectly-formatted source location entry in AST file");
1180 return true;
1181 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001182
Guy Benyei11169dd2012-12-18 14:30:41 +00001183 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001184 StringRef Blob;
1185 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001186 default:
1187 Error("incorrectly-formatted source location entry in AST file");
1188 return true;
1189
1190 case SM_SLOC_FILE_ENTRY: {
1191 // We will detect whether a file changed and return 'Failure' for it, but
1192 // we will also try to fail gracefully by setting up the SLocEntry.
1193 unsigned InputID = Record[4];
1194 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001195 const FileEntry *File = IF.getFile();
1196 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001197
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001198 // Note that we only check if a File was returned. If it was out-of-date
1199 // we have complained but we will continue creating a FileID to recover
1200 // gracefully.
1201 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001202 return true;
1203
1204 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1205 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1206 // This is the module's main file.
1207 IncludeLoc = getImportLocation(F);
1208 }
1209 SrcMgr::CharacteristicKind
1210 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1211 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1212 ID, BaseOffset + Record[0]);
1213 SrcMgr::FileInfo &FileInfo =
1214 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1215 FileInfo.NumCreatedFIDs = Record[5];
1216 if (Record[3])
1217 FileInfo.setHasLineDirectives();
1218
1219 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1220 unsigned NumFileDecls = Record[7];
1221 if (NumFileDecls) {
1222 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1223 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1224 NumFileDecls));
1225 }
1226
1227 const SrcMgr::ContentCache *ContentCache
1228 = SourceMgr.getOrCreateContentCache(File,
1229 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1230 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1231 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1232 unsigned Code = SLocEntryCursor.ReadCode();
1233 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001234 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001235
1236 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1237 Error("AST record has invalid code");
1238 return true;
1239 }
1240
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001241 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001242 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001243 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001244 }
1245
1246 break;
1247 }
1248
1249 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001250 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001251 unsigned Offset = Record[0];
1252 SrcMgr::CharacteristicKind
1253 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1254 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001255 if (IncludeLoc.isInvalid() &&
1256 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001257 IncludeLoc = getImportLocation(F);
1258 }
1259 unsigned Code = SLocEntryCursor.ReadCode();
1260 Record.clear();
1261 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001262 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001263
1264 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1265 Error("AST record has invalid code");
1266 return true;
1267 }
1268
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001269 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1270 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001271 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001272 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001273 break;
1274 }
1275
1276 case SM_SLOC_EXPANSION_ENTRY: {
1277 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1278 SourceMgr.createExpansionLoc(SpellingLoc,
1279 ReadSourceLocation(*F, Record[2]),
1280 ReadSourceLocation(*F, Record[3]),
1281 Record[4],
1282 ID,
1283 BaseOffset + Record[0]);
1284 break;
1285 }
1286 }
1287
1288 return false;
1289}
1290
1291std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1292 if (ID == 0)
1293 return std::make_pair(SourceLocation(), "");
1294
1295 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1296 Error("source location entry ID out-of-range for AST file");
1297 return std::make_pair(SourceLocation(), "");
1298 }
1299
1300 // Find which module file this entry lands in.
1301 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001302 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001303 return std::make_pair(SourceLocation(), "");
1304
1305 // FIXME: Can we map this down to a particular submodule? That would be
1306 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001307 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001308}
1309
1310/// \brief Find the location where the module F is imported.
1311SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1312 if (F->ImportLoc.isValid())
1313 return F->ImportLoc;
1314
1315 // Otherwise we have a PCH. It's considered to be "imported" at the first
1316 // location of its includer.
1317 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001318 // Main file is the importer.
1319 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1320 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001321 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001322 return F->ImportedBy[0]->FirstLoc;
1323}
1324
1325/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1326/// specified cursor. Read the abbreviations that are at the top of the block
1327/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001328bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001329 if (Cursor.EnterSubBlock(BlockID)) {
1330 Error("malformed block record in AST file");
1331 return Failure;
1332 }
1333
1334 while (true) {
1335 uint64_t Offset = Cursor.GetCurrentBitNo();
1336 unsigned Code = Cursor.ReadCode();
1337
1338 // We expect all abbrevs to be at the start of the block.
1339 if (Code != llvm::bitc::DEFINE_ABBREV) {
1340 Cursor.JumpToBit(Offset);
1341 return false;
1342 }
1343 Cursor.ReadAbbrevRecord();
1344 }
1345}
1346
Richard Smithe40f2ba2013-08-07 21:41:30 +00001347Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001348 unsigned &Idx) {
1349 Token Tok;
1350 Tok.startToken();
1351 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1352 Tok.setLength(Record[Idx++]);
1353 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1354 Tok.setIdentifierInfo(II);
1355 Tok.setKind((tok::TokenKind)Record[Idx++]);
1356 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1357 return Tok;
1358}
1359
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001360MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001361 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001362
1363 // Keep track of where we are in the stream, then jump back there
1364 // after reading this macro.
1365 SavedStreamPosition SavedPosition(Stream);
1366
1367 Stream.JumpToBit(Offset);
1368 RecordData Record;
1369 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001370 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001371
Guy Benyei11169dd2012-12-18 14:30:41 +00001372 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001373 // Advance to the next record, but if we get to the end of the block, don't
1374 // pop it (removing all the abbreviations from the cursor) since we want to
1375 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001376 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001377 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1378
1379 switch (Entry.Kind) {
1380 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1381 case llvm::BitstreamEntry::Error:
1382 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001383 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001384 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001385 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001386 case llvm::BitstreamEntry::Record:
1387 // The interesting case.
1388 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001389 }
1390
1391 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001392 Record.clear();
1393 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001394 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001395 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001396 case PP_MACRO_DIRECTIVE_HISTORY:
1397 return Macro;
1398
Guy Benyei11169dd2012-12-18 14:30:41 +00001399 case PP_MACRO_OBJECT_LIKE:
1400 case PP_MACRO_FUNCTION_LIKE: {
1401 // If we already have a macro, that means that we've hit the end
1402 // of the definition of the macro we were looking for. We're
1403 // done.
1404 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001405 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001406
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001407 unsigned NextIndex = 1; // Skip identifier ID.
1408 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001409 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001410 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001411 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001412 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001413 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001414
Guy Benyei11169dd2012-12-18 14:30:41 +00001415 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1416 // Decode function-like macro info.
1417 bool isC99VarArgs = Record[NextIndex++];
1418 bool isGNUVarArgs = Record[NextIndex++];
1419 bool hasCommaPasting = Record[NextIndex++];
1420 MacroArgs.clear();
1421 unsigned NumArgs = Record[NextIndex++];
1422 for (unsigned i = 0; i != NumArgs; ++i)
1423 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1424
1425 // Install function-like macro info.
1426 MI->setIsFunctionLike();
1427 if (isC99VarArgs) MI->setIsC99Varargs();
1428 if (isGNUVarArgs) MI->setIsGNUVarargs();
1429 if (hasCommaPasting) MI->setHasCommaPasting();
1430 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1431 PP.getPreprocessorAllocator());
1432 }
1433
Guy Benyei11169dd2012-12-18 14:30:41 +00001434 // Remember that we saw this macro last so that we add the tokens that
1435 // form its body to it.
1436 Macro = MI;
1437
1438 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1439 Record[NextIndex]) {
1440 // We have a macro definition. Register the association
1441 PreprocessedEntityID
1442 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1443 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001444 PreprocessingRecord::PPEntityID
1445 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1446 MacroDefinition *PPDef =
1447 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1448 if (PPDef)
1449 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001450 }
1451
1452 ++NumMacrosRead;
1453 break;
1454 }
1455
1456 case PP_TOKEN: {
1457 // If we see a TOKEN before a PP_MACRO_*, then the file is
1458 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001459 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001460
John McCallf413f5e2013-05-03 00:10:13 +00001461 unsigned Idx = 0;
1462 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001463 Macro->AddTokenToBody(Tok);
1464 break;
1465 }
1466 }
1467 }
1468}
1469
1470PreprocessedEntityID
1471ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1472 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1473 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1474 assert(I != M.PreprocessedEntityRemap.end()
1475 && "Invalid index into preprocessed entity index remap");
1476
1477 return LocalID + I->second;
1478}
1479
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001480unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1481 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001482}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001483
Guy Benyei11169dd2012-12-18 14:30:41 +00001484HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001485HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1486 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
Richard Smith7ed1bc92014-12-05 22:42:13 +00001487 FE->getName(), /*Imported*/false };
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001488 return ikey;
1489}
Guy Benyei11169dd2012-12-18 14:30:41 +00001490
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001491bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1492 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001493 return false;
1494
Richard Smith7ed1bc92014-12-05 22:42:13 +00001495 if (llvm::sys::path::is_absolute(a.Filename) &&
1496 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001497 return true;
1498
Guy Benyei11169dd2012-12-18 14:30:41 +00001499 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001500 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001501 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1502 if (!Key.Imported)
1503 return FileMgr.getFile(Key.Filename);
1504
1505 std::string Resolved = Key.Filename;
1506 Reader.ResolveImportedPath(M, Resolved);
1507 return FileMgr.getFile(Resolved);
1508 };
1509
1510 const FileEntry *FEA = GetFile(a);
1511 const FileEntry *FEB = GetFile(b);
1512 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001513}
1514
1515std::pair<unsigned, unsigned>
1516HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001517 using namespace llvm::support;
1518 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001519 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001520 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001521}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001522
1523HeaderFileInfoTrait::internal_key_type
1524HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001525 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001526 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001527 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1528 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001529 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001530 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001531 return ikey;
1532}
1533
Guy Benyei11169dd2012-12-18 14:30:41 +00001534HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001535HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001536 unsigned DataLen) {
1537 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001538 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001539 HeaderFileInfo HFI;
1540 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001541 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1542 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001543 HFI.isImport = (Flags >> 5) & 0x01;
1544 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1545 HFI.DirInfo = (Flags >> 2) & 0x03;
1546 HFI.Resolved = (Flags >> 1) & 0x01;
1547 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001548 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1549 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1550 M, endian::readNext<uint32_t, little, unaligned>(d));
1551 if (unsigned FrameworkOffset =
1552 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001553 // The framework offset is 1 greater than the actual offset,
1554 // since 0 is used as an indicator for "no framework name".
1555 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1556 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1557 }
1558
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001559 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001560 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001561 if (LocalSMID) {
1562 // This header is part of a module. Associate it with the module to enable
1563 // implicit module import.
1564 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1565 Module *Mod = Reader.getSubmodule(GlobalSMID);
1566 HFI.isModuleHeader = true;
1567 FileManager &FileMgr = Reader.getFileManager();
1568 ModuleMap &ModMap =
1569 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001570 // FIXME: This information should be propagated through the
1571 // SUBMODULE_HEADER etc records rather than from here.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001572 // FIXME: We don't ever mark excluded headers.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001573 std::string Filename = key.Filename;
1574 if (key.Imported)
1575 Reader.ResolveImportedPath(M, Filename);
1576 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Hans Wennborg0101b542014-12-02 02:13:09 +00001577 ModMap.addHeader(Mod, H, HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001578 }
1579 }
1580
Guy Benyei11169dd2012-12-18 14:30:41 +00001581 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1582 (void)End;
1583
1584 // This HeaderFileInfo was externally loaded.
1585 HFI.External = true;
1586 return HFI;
1587}
1588
Richard Smith49f906a2014-03-01 00:08:04 +00001589void
1590ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1591 GlobalMacroID GMacID,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001592 ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001593 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Craig Toppera13603a2014-05-22 05:54:18 +00001594 SubmoduleID *OverrideData = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001595 if (!Overrides.empty()) {
1596 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1597 OverrideData[0] = Overrides.size();
1598 for (unsigned I = 0; I != Overrides.size(); ++I)
1599 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1600 }
1601 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001602}
1603
1604void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1605 ModuleFile *M,
1606 uint64_t MacroDirectivesOffset) {
1607 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1608 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001609}
1610
1611void ASTReader::ReadDefinedMacros() {
1612 // Note that we are loading defined macros.
1613 Deserializing Macros(this);
1614
1615 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1616 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001617 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001618
1619 // If there was no preprocessor block, skip this file.
1620 if (!MacroCursor.getBitStreamReader())
1621 continue;
1622
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001623 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001624 Cursor.JumpToBit((*I)->MacroStartOffset);
1625
1626 RecordData Record;
1627 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001628 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1629
1630 switch (E.Kind) {
1631 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1632 case llvm::BitstreamEntry::Error:
1633 Error("malformed block record in AST file");
1634 return;
1635 case llvm::BitstreamEntry::EndBlock:
1636 goto NextCursor;
1637
1638 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001639 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001640 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001641 default: // Default behavior: ignore.
1642 break;
1643
1644 case PP_MACRO_OBJECT_LIKE:
1645 case PP_MACRO_FUNCTION_LIKE:
1646 getLocalIdentifier(**I, Record[0]);
1647 break;
1648
1649 case PP_TOKEN:
1650 // Ignore tokens.
1651 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001652 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001653 break;
1654 }
1655 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001656 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001657 }
1658}
1659
1660namespace {
1661 /// \brief Visitor class used to look up identifirs in an AST file.
1662 class IdentifierLookupVisitor {
1663 StringRef Name;
1664 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001665 unsigned &NumIdentifierLookups;
1666 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001667 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001668
Guy Benyei11169dd2012-12-18 14:30:41 +00001669 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001670 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1671 unsigned &NumIdentifierLookups,
1672 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001673 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001674 NumIdentifierLookups(NumIdentifierLookups),
1675 NumIdentifierLookupHits(NumIdentifierLookupHits),
1676 Found()
1677 {
1678 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001679
1680 static bool visit(ModuleFile &M, void *UserData) {
1681 IdentifierLookupVisitor *This
1682 = static_cast<IdentifierLookupVisitor *>(UserData);
1683
1684 // If we've already searched this module file, skip it now.
1685 if (M.Generation <= This->PriorGeneration)
1686 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001687
Guy Benyei11169dd2012-12-18 14:30:41 +00001688 ASTIdentifierLookupTable *IdTable
1689 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1690 if (!IdTable)
1691 return false;
1692
1693 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1694 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001695 ++This->NumIdentifierLookups;
1696 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001697 if (Pos == IdTable->end())
1698 return false;
1699
1700 // Dereferencing the iterator has the effect of building the
1701 // IdentifierInfo node and populating it with the various
1702 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001703 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001704 This->Found = *Pos;
1705 return true;
1706 }
1707
1708 // \brief Retrieve the identifier info found within the module
1709 // files.
1710 IdentifierInfo *getIdentifierInfo() const { return Found; }
1711 };
1712}
1713
1714void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1715 // Note that we are loading an identifier.
1716 Deserializing AnIdentifier(this);
1717
1718 unsigned PriorGeneration = 0;
1719 if (getContext().getLangOpts().Modules)
1720 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001721
1722 // If there is a global index, look there first to determine which modules
1723 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001724 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001725 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001726 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001727 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1728 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001729 }
1730 }
1731
Douglas Gregor7211ac12013-01-25 23:32:03 +00001732 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001733 NumIdentifierLookups,
1734 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001735 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001736 markIdentifierUpToDate(&II);
1737}
1738
1739void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1740 if (!II)
1741 return;
1742
1743 II->setOutOfDate(false);
1744
1745 // Update the generation for this identifier.
1746 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001747 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001748}
1749
Richard Smith49f906a2014-03-01 00:08:04 +00001750struct ASTReader::ModuleMacroInfo {
1751 SubmoduleID SubModID;
1752 MacroInfo *MI;
1753 SubmoduleID *Overrides;
1754 // FIXME: Remove this.
1755 ModuleFile *F;
1756
1757 bool isDefine() const { return MI; }
1758
1759 SubmoduleID getSubmoduleID() const { return SubModID; }
1760
Craig Topper00bbdcf2014-06-28 23:22:23 +00001761 ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
Richard Smith49f906a2014-03-01 00:08:04 +00001762 if (!Overrides)
Craig Topper00bbdcf2014-06-28 23:22:23 +00001763 return None;
Richard Smith49f906a2014-03-01 00:08:04 +00001764 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1765 }
1766
Richard Smithdaa69e02014-07-25 04:40:03 +00001767 MacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
Richard Smith49f906a2014-03-01 00:08:04 +00001768 if (!MI)
Richard Smithdaa69e02014-07-25 04:40:03 +00001769 return PP.AllocateUndefMacroDirective(ImportLoc, SubModID,
1770 getOverriddenSubmodules());
1771 return PP.AllocateDefMacroDirective(MI, ImportLoc, SubModID,
1772 getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00001773 }
1774};
1775
1776ASTReader::ModuleMacroInfo *
1777ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1778 ModuleMacroInfo Info;
1779
1780 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1781 if (ID & 1) {
1782 // Macro undefinition.
1783 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
Craig Toppera13603a2014-05-22 05:54:18 +00001784 Info.MI = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001785 } else {
1786 // Macro definition.
1787 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1788 assert(GMacID);
1789
1790 // If this macro has already been loaded, don't do so again.
1791 // FIXME: This is highly dubious. Multiple macro definitions can have the
1792 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1793 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
Craig Toppera13603a2014-05-22 05:54:18 +00001794 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001795
1796 Info.MI = getMacro(GMacID);
1797 Info.SubModID = Info.MI->getOwningModuleID();
1798 }
1799 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1800 Info.F = PMInfo.M;
1801
1802 return new (Context) ModuleMacroInfo(Info);
1803}
1804
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001805void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1806 const PendingMacroInfo &PMInfo) {
1807 assert(II);
1808
Richard Smithe842a472014-10-22 02:05:46 +00001809 if (PMInfo.M->Kind != MK_ImplicitModule &&
1810 PMInfo.M->Kind != MK_ExplicitModule) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001811 installPCHMacroDirectives(II, *PMInfo.M,
1812 PMInfo.PCHMacroData.MacroDirectivesOffset);
1813 return;
1814 }
Richard Smith49f906a2014-03-01 00:08:04 +00001815
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001816 // Module Macro.
1817
Richard Smith49f906a2014-03-01 00:08:04 +00001818 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1819 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001820 return;
1821
Richard Smith49f906a2014-03-01 00:08:04 +00001822 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1823 if (Owner && Owner->NameVisibility == Module::Hidden) {
1824 // Macros in the owning module are hidden. Just remember this macro to
1825 // install if we make this module visible.
1826 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1827 } else {
Richard Smithdaa69e02014-07-25 04:40:03 +00001828 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001829 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001830}
1831
1832void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1833 ModuleFile &M, uint64_t Offset) {
Richard Smithe842a472014-10-22 02:05:46 +00001834 assert(M.Kind != MK_ImplicitModule && M.Kind != MK_ExplicitModule);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001835
1836 BitstreamCursor &Cursor = M.MacroCursor;
1837 SavedStreamPosition SavedPosition(Cursor);
1838 Cursor.JumpToBit(Offset);
1839
1840 llvm::BitstreamEntry Entry =
1841 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1842 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1843 Error("malformed block record in AST file");
1844 return;
1845 }
1846
1847 RecordData Record;
1848 PreprocessorRecordTypes RecType =
1849 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1850 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1851 Error("malformed block record in AST file");
1852 return;
1853 }
1854
1855 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001856 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001857 unsigned Idx = 0, N = Record.size();
1858 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001859 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001860 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001861 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1862 switch (K) {
1863 case MacroDirective::MD_Define: {
1864 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1865 MacroInfo *MI = getMacro(GMacID);
Richard Smithdaa69e02014-07-25 04:40:03 +00001866 SubmoduleID ImportedFrom = Record[Idx++];
1867 bool IsAmbiguous = Record[Idx++];
1868 llvm::SmallVector<unsigned, 4> Overrides;
1869 if (ImportedFrom) {
1870 Overrides.insert(Overrides.end(),
1871 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1872 Idx += Overrides.size() + 1;
1873 }
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001874 DefMacroDirective *DefMD =
Richard Smithdaa69e02014-07-25 04:40:03 +00001875 PP.AllocateDefMacroDirective(MI, Loc, ImportedFrom, Overrides);
1876 DefMD->setAmbiguous(IsAmbiguous);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001877 MD = DefMD;
1878 break;
1879 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001880 case MacroDirective::MD_Undefine: {
1881 SubmoduleID ImportedFrom = Record[Idx++];
1882 llvm::SmallVector<unsigned, 4> Overrides;
1883 if (ImportedFrom) {
1884 Overrides.insert(Overrides.end(),
1885 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1886 Idx += Overrides.size() + 1;
1887 }
1888 MD = PP.AllocateUndefMacroDirective(Loc, ImportedFrom, Overrides);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001889 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001890 }
1891 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001892 bool isPublic = Record[Idx++];
1893 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1894 break;
1895 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001896
1897 if (!Latest)
1898 Latest = MD;
1899 if (Earliest)
1900 Earliest->setPrevious(MD);
1901 Earliest = MD;
1902 }
1903
1904 PP.setLoadedMacroDirective(II, Latest);
1905}
1906
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001907/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001908/// modules.
1909static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001910 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001911 assert(PrevMI && NewMI);
Craig Toppera13603a2014-05-22 05:54:18 +00001912 Module *PrevOwner = nullptr;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001913 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1914 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001915 SourceManager &SrcMgr = Reader.getSourceManager();
1916 bool PrevInSystem
1917 = PrevOwner? PrevOwner->IsSystem
1918 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1919 bool NewInSystem
1920 = NewOwner? NewOwner->IsSystem
1921 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1922 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001923 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001924 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001925}
1926
Richard Smith49f906a2014-03-01 00:08:04 +00001927void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001928 SourceLocation ImportLoc,
Richard Smith49f906a2014-03-01 00:08:04 +00001929 AmbiguousMacros &Ambig,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001930 ArrayRef<SubmoduleID> Overrides) {
Richard Smith49f906a2014-03-01 00:08:04 +00001931 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1932 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001933
Richard Smith49f906a2014-03-01 00:08:04 +00001934 // If this macro is not yet visible, remove it from the hidden names list.
Richard Smithbb853c72014-08-13 01:23:33 +00001935 // It won't be there if we're in the middle of making the owner visible.
Richard Smith49f906a2014-03-01 00:08:04 +00001936 Module *Owner = getSubmodule(OwnerID);
Richard Smithbb853c72014-08-13 01:23:33 +00001937 auto HiddenIt = HiddenNamesMap.find(Owner);
1938 if (HiddenIt != HiddenNamesMap.end()) {
1939 HiddenNames &Hidden = HiddenIt->second;
1940 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1941 if (HI != Hidden.HiddenMacros.end()) {
1942 // Register the macro now so we don't lose it when we re-export.
1943 PP.appendMacroDirective(II, HI->second->import(PP, ImportLoc));
Richard Smithdaa69e02014-07-25 04:40:03 +00001944
Richard Smithbb853c72014-08-13 01:23:33 +00001945 auto SubOverrides = HI->second->getOverriddenSubmodules();
1946 Hidden.HiddenMacros.erase(HI);
1947 removeOverriddenMacros(II, ImportLoc, Ambig, SubOverrides);
1948 }
Richard Smith49f906a2014-03-01 00:08:04 +00001949 }
1950
1951 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001952 Ambig.erase(
1953 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1954 return MD->getInfo()->getOwningModuleID() == OwnerID;
1955 }),
1956 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001957 }
1958}
1959
1960ASTReader::AmbiguousMacros *
1961ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001962 SourceLocation ImportLoc,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001963 ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001964 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001965 if (!Prev && Overrides.empty())
Craig Toppera13603a2014-05-22 05:54:18 +00001966 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001967
Craig Toppera13603a2014-05-22 05:54:18 +00001968 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective()
1969 : nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001970 if (PrevDef && PrevDef->isAmbiguous()) {
1971 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1972 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1973 Ambig.push_back(PrevDef);
1974
Richard Smithdaa69e02014-07-25 04:40:03 +00001975 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001976
1977 if (!Ambig.empty())
1978 return &Ambig;
1979
1980 AmbiguousMacroDefs.erase(II);
1981 } else {
1982 // There's no ambiguity yet. Maybe we're introducing one.
Benjamin Kramer834652a2014-05-03 18:44:26 +00001983 AmbiguousMacros Ambig;
Richard Smith49f906a2014-03-01 00:08:04 +00001984 if (PrevDef)
1985 Ambig.push_back(PrevDef);
1986
Richard Smithdaa69e02014-07-25 04:40:03 +00001987 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001988
1989 if (!Ambig.empty()) {
1990 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
Benjamin Kramer834652a2014-05-03 18:44:26 +00001991 std::swap(Result, Ambig);
Richard Smith49f906a2014-03-01 00:08:04 +00001992 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001993 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001994 }
Richard Smith49f906a2014-03-01 00:08:04 +00001995
1996 // We ended up with no ambiguity.
Craig Toppera13603a2014-05-22 05:54:18 +00001997 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001998}
1999
2000void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
Richard Smithdaa69e02014-07-25 04:40:03 +00002001 Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00002002 assert(II && Owner);
2003
2004 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
Richard Smithdaa69e02014-07-25 04:40:03 +00002005 if (ImportLoc.isInvalid()) {
Richard Smith49f906a2014-03-01 00:08:04 +00002006 // FIXME: If we made macros from this module visible but didn't provide a
2007 // source location for the import, we don't have a location for the macro.
2008 // Use the location at which the containing module file was first imported
2009 // for now.
2010 ImportLoc = MMI->F->DirectImportLoc;
Richard Smith56be7542014-03-21 00:33:59 +00002011 assert(ImportLoc.isValid() && "no import location for a visible macro?");
Richard Smith49f906a2014-03-01 00:08:04 +00002012 }
2013
Benjamin Kramer834652a2014-05-03 18:44:26 +00002014 AmbiguousMacros *Prev =
Richard Smithdaa69e02014-07-25 04:40:03 +00002015 removeOverriddenMacros(II, ImportLoc, MMI->getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00002016
Richard Smith49f906a2014-03-01 00:08:04 +00002017 // Create a synthetic macro definition corresponding to the import (or null
2018 // if this was an undefinition of the macro).
Richard Smithdaa69e02014-07-25 04:40:03 +00002019 MacroDirective *Imported = MMI->import(PP, ImportLoc);
2020 DefMacroDirective *MD = dyn_cast<DefMacroDirective>(Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002021
2022 // If there's no ambiguity, just install the macro.
2023 if (!Prev) {
Richard Smithdaa69e02014-07-25 04:40:03 +00002024 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002025 return;
2026 }
2027 assert(!Prev->empty());
2028
2029 if (!MD) {
2030 // We imported a #undef that didn't remove all prior definitions. The most
2031 // recent prior definition remains, and we install it in the place of the
Richard Smithdaa69e02014-07-25 04:40:03 +00002032 // imported directive, as if by a local #pragma pop_macro.
Richard Smith49f906a2014-03-01 00:08:04 +00002033 MacroInfo *NewMI = Prev->back()->getInfo();
2034 Prev->pop_back();
Richard Smithdaa69e02014-07-25 04:40:03 +00002035 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc);
2036
2037 // Install our #undef first so that we don't lose track of it. We'll replace
2038 // this with whichever macro definition ends up winning.
2039 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002040 }
2041
2042 // We're introducing a macro definition that creates or adds to an ambiguity.
2043 // We can resolve that ambiguity if this macro is token-for-token identical to
2044 // all of the existing definitions.
2045 MacroInfo *NewMI = MD->getInfo();
2046 assert(NewMI && "macro definition with no MacroInfo?");
2047 while (!Prev->empty()) {
2048 MacroInfo *PrevMI = Prev->back()->getInfo();
2049 assert(PrevMI && "macro definition with no MacroInfo?");
2050
2051 // Before marking the macros as ambiguous, check if this is a case where
2052 // both macros are in system headers. If so, we trust that the system
2053 // did not get it wrong. This also handles cases where Clang's own
2054 // headers have a different spelling of certain system macros:
2055 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
2056 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
2057 //
2058 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
2059 // overrides the system limits.h's macros, so there's no conflict here.
2060 if (NewMI != PrevMI &&
2061 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
2062 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
2063 break;
2064
2065 // The previous definition is the same as this one (or both are defined in
2066 // system modules so we can assume they're equivalent); we don't need to
2067 // track it any more.
2068 Prev->pop_back();
2069 }
2070
2071 if (!Prev->empty())
2072 MD->setAmbiguous(true);
2073
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002074 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002075}
2076
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002077ASTReader::InputFileInfo
2078ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002079 // Go find this input file.
2080 BitstreamCursor &Cursor = F.InputFilesCursor;
2081 SavedStreamPosition SavedPosition(Cursor);
2082 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2083
2084 unsigned Code = Cursor.ReadCode();
2085 RecordData Record;
2086 StringRef Blob;
2087
2088 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2089 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2090 "invalid record type for input file");
2091 (void)Result;
2092
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002093 std::string Filename;
2094 off_t StoredSize;
2095 time_t StoredTime;
2096 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002097
Ben Langmuir198c1682014-03-07 07:27:49 +00002098 assert(Record[0] == ID && "Bogus stored ID or offset");
2099 StoredSize = static_cast<off_t>(Record[1]);
2100 StoredTime = static_cast<time_t>(Record[2]);
2101 Overridden = static_cast<bool>(Record[3]);
2102 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002103 ResolveImportedPath(F, Filename);
2104
Hans Wennborg73945142014-03-14 17:45:06 +00002105 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
2106 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002107}
2108
2109std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002110 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00002111}
2112
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002113InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002114 // If this ID is bogus, just return an empty input file.
2115 if (ID == 0 || ID > F.InputFilesLoaded.size())
2116 return InputFile();
2117
2118 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002119 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002120 return F.InputFilesLoaded[ID-1];
2121
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002122 if (F.InputFilesLoaded[ID-1].isNotFound())
2123 return InputFile();
2124
Guy Benyei11169dd2012-12-18 14:30:41 +00002125 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002126 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002127 SavedStreamPosition SavedPosition(Cursor);
2128 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2129
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002130 InputFileInfo FI = readInputFileInfo(F, ID);
2131 off_t StoredSize = FI.StoredSize;
2132 time_t StoredTime = FI.StoredTime;
2133 bool Overridden = FI.Overridden;
2134 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002135
Ben Langmuir198c1682014-03-07 07:27:49 +00002136 const FileEntry *File
2137 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
2138 : FileMgr.getFile(Filename, /*OpenFile=*/false);
2139
2140 // If we didn't find the file, resolve it relative to the
2141 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002142 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002143 F.OriginalDir != CurrentDir) {
2144 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2145 F.OriginalDir,
2146 CurrentDir);
2147 if (!Resolved.empty())
2148 File = FileMgr.getFile(Resolved);
2149 }
2150
2151 // For an overridden file, create a virtual file with the stored
2152 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00002153 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002154 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2155 }
2156
Craig Toppera13603a2014-05-22 05:54:18 +00002157 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002158 if (Complain) {
2159 std::string ErrorStr = "could not find file '";
2160 ErrorStr += Filename;
2161 ErrorStr += "' referenced by AST file";
2162 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00002163 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002164 // Record that we didn't find the file.
2165 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2166 return InputFile();
2167 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002168
Ben Langmuir198c1682014-03-07 07:27:49 +00002169 // Check if there was a request to override the contents of the file
2170 // that was part of the precompiled header. Overridding such a file
2171 // can lead to problems when lexing using the source locations from the
2172 // PCH.
2173 SourceManager &SM = getSourceManager();
2174 if (!Overridden && SM.isFileOverridden(File)) {
2175 if (Complain)
2176 Error(diag::err_fe_pch_file_overridden, Filename);
2177 // After emitting the diagnostic, recover by disabling the override so
2178 // that the original file will be used.
2179 SM.disableFileContentsOverride(File);
2180 // The FileEntry is a virtual file entry with the size of the contents
2181 // that would override the original contents. Set it to the original's
2182 // size/time.
2183 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2184 StoredSize, StoredTime);
2185 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002186
Ben Langmuir198c1682014-03-07 07:27:49 +00002187 bool IsOutOfDate = false;
2188
2189 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002190 if (!Overridden && //
2191 (StoredSize != File->getSize() ||
2192#if defined(LLVM_ON_WIN32)
2193 false
2194#else
Ben Langmuir198c1682014-03-07 07:27:49 +00002195 // In our regression testing, the Windows file system seems to
2196 // have inconsistent modification times that sometimes
2197 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00002198 //
2199 // This also happens in networked file systems, so disable this
2200 // check if validation is disabled or if we have an explicitly
2201 // built PCM file.
2202 //
2203 // FIXME: Should we also do this for PCH files? They could also
2204 // reasonably get shared across a network during a distributed build.
2205 (StoredTime != File->getModificationTime() && !DisableValidation &&
2206 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00002207#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002208 )) {
2209 if (Complain) {
2210 // Build a list of the PCH imports that got us here (in reverse).
2211 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2212 while (ImportStack.back()->ImportedBy.size() > 0)
2213 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002214
Ben Langmuir198c1682014-03-07 07:27:49 +00002215 // The top-level PCH is stale.
2216 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2217 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002218
Ben Langmuir198c1682014-03-07 07:27:49 +00002219 // Print the import stack.
2220 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2221 Diag(diag::note_pch_required_by)
2222 << Filename << ImportStack[0]->FileName;
2223 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002224 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002225 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002226 }
2227
Ben Langmuir198c1682014-03-07 07:27:49 +00002228 if (!Diags.isDiagnosticInFlight())
2229 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002230 }
2231
Ben Langmuir198c1682014-03-07 07:27:49 +00002232 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002233 }
2234
Ben Langmuir198c1682014-03-07 07:27:49 +00002235 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2236
2237 // Note that we've loaded this input file.
2238 F.InputFilesLoaded[ID-1] = IF;
2239 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002240}
2241
Richard Smith7ed1bc92014-12-05 22:42:13 +00002242/// \brief If we are loading a relocatable PCH or module file, and the filename
2243/// is not an absolute path, add the system or module root to the beginning of
2244/// the file name.
2245void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2246 // Resolve relative to the base directory, if we have one.
2247 if (!M.BaseDirectory.empty())
2248 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002249}
2250
Richard Smith7ed1bc92014-12-05 22:42:13 +00002251void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002252 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2253 return;
2254
Richard Smith7ed1bc92014-12-05 22:42:13 +00002255 SmallString<128> Buffer;
2256 llvm::sys::path::append(Buffer, Prefix, Filename);
2257 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002258}
2259
2260ASTReader::ASTReadResult
2261ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002262 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002263 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002264 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002265 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002266
2267 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2268 Error("malformed block record in AST file");
2269 return Failure;
2270 }
2271
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002272 // Should we allow the configuration of the module file to differ from the
2273 // configuration of the current translation unit in a compatible way?
2274 //
2275 // FIXME: Allow this for files explicitly specified with -include-pch too.
2276 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2277
Guy Benyei11169dd2012-12-18 14:30:41 +00002278 // Read all of the records and blocks in the control block.
2279 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002280 unsigned NumInputs = 0;
2281 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002282 while (1) {
2283 llvm::BitstreamEntry Entry = Stream.advance();
2284
2285 switch (Entry.Kind) {
2286 case llvm::BitstreamEntry::Error:
2287 Error("malformed block record in AST file");
2288 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002289 case llvm::BitstreamEntry::EndBlock: {
2290 // Validate input files.
2291 const HeaderSearchOptions &HSOpts =
2292 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002293
Richard Smitha1825302014-10-23 22:18:29 +00002294 // All user input files reside at the index range [0, NumUserInputs), and
2295 // system input files reside at [NumUserInputs, NumInputs).
Ben Langmuiracb803e2014-11-10 22:13:10 +00002296 if (!DisableValidation) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002297 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002298
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002299 // If we are reading a module, we will create a verification timestamp,
2300 // so we verify all input files. Otherwise, verify only user input
2301 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002302
2303 unsigned N = NumUserInputs;
2304 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002305 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002306 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002307 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002308 N = NumInputs;
2309
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002310 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002311 InputFile IF = getInputFile(F, I+1, Complain);
2312 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002313 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002314 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002315 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002316
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002317 if (Listener)
2318 Listener->visitModuleFile(F.FileName);
2319
Ben Langmuircb69b572014-03-07 06:40:32 +00002320 if (Listener && Listener->needsInputFileVisitation()) {
2321 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2322 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002323 for (unsigned I = 0; I < N; ++I) {
2324 bool IsSystem = I >= NumUserInputs;
2325 InputFileInfo FI = readInputFileInfo(F, I+1);
2326 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2327 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002328 }
2329
Guy Benyei11169dd2012-12-18 14:30:41 +00002330 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002331 }
2332
Chris Lattnere7b154b2013-01-19 21:39:22 +00002333 case llvm::BitstreamEntry::SubBlock:
2334 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002335 case INPUT_FILES_BLOCK_ID:
2336 F.InputFilesCursor = Stream;
2337 if (Stream.SkipBlock() || // Skip with the main cursor
2338 // Read the abbreviations
2339 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2340 Error("malformed block record in AST file");
2341 return Failure;
2342 }
2343 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002344
Guy Benyei11169dd2012-12-18 14:30:41 +00002345 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002346 if (Stream.SkipBlock()) {
2347 Error("malformed block record in AST file");
2348 return Failure;
2349 }
2350 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002351 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002352
2353 case llvm::BitstreamEntry::Record:
2354 // The interesting case.
2355 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002356 }
2357
2358 // Read and process a record.
2359 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002360 StringRef Blob;
2361 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002362 case METADATA: {
2363 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2364 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002365 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2366 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002367 return VersionMismatch;
2368 }
2369
2370 bool hasErrors = Record[5];
2371 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2372 Diag(diag::err_pch_with_compiler_errors);
2373 return HadErrors;
2374 }
2375
2376 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002377 // Relative paths in a relocatable PCH are relative to our sysroot.
2378 if (F.RelocatablePCH)
2379 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002380
2381 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002382 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002383 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2384 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002385 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002386 return VersionMismatch;
2387 }
2388 break;
2389 }
2390
Ben Langmuir487ea142014-10-23 18:05:36 +00002391 case SIGNATURE:
2392 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2393 F.Signature = Record[0];
2394 break;
2395
Guy Benyei11169dd2012-12-18 14:30:41 +00002396 case IMPORTS: {
2397 // Load each of the imported PCH files.
2398 unsigned Idx = 0, N = Record.size();
2399 while (Idx < N) {
2400 // Read information about the AST file.
2401 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2402 // The import location will be the local one for now; we will adjust
2403 // all import locations of module imports after the global source
2404 // location info are setup.
2405 SourceLocation ImportLoc =
2406 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002407 off_t StoredSize = (off_t)Record[Idx++];
2408 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002409 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002410 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002411
2412 // Load the AST file.
2413 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00002414 StoredSize, StoredModTime, StoredSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00002415 ClientLoadCapabilities)) {
2416 case Failure: return Failure;
2417 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002418 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002419 case OutOfDate: return OutOfDate;
2420 case VersionMismatch: return VersionMismatch;
2421 case ConfigurationMismatch: return ConfigurationMismatch;
2422 case HadErrors: return HadErrors;
2423 case Success: break;
2424 }
2425 }
2426 break;
2427 }
2428
2429 case LANGUAGE_OPTIONS: {
2430 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002431 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002432 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002433 ParseLanguageOptions(Record, Complain, *Listener,
2434 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002435 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002436 return ConfigurationMismatch;
2437 break;
2438 }
2439
2440 case TARGET_OPTIONS: {
2441 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2442 if (Listener && &F == *ModuleMgr.begin() &&
2443 ParseTargetOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002444 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002445 return ConfigurationMismatch;
2446 break;
2447 }
2448
2449 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002450 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002451 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002452 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002453 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002454 !DisableValidation)
2455 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002456 break;
2457 }
2458
2459 case FILE_SYSTEM_OPTIONS: {
2460 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2461 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002462 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002463 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002464 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002465 return ConfigurationMismatch;
2466 break;
2467 }
2468
2469 case HEADER_SEARCH_OPTIONS: {
2470 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2471 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002472 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002473 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002474 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002475 return ConfigurationMismatch;
2476 break;
2477 }
2478
2479 case PREPROCESSOR_OPTIONS: {
2480 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2481 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002482 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002483 ParsePreprocessorOptions(Record, Complain, *Listener,
2484 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002485 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 return ConfigurationMismatch;
2487 break;
2488 }
2489
2490 case ORIGINAL_FILE:
2491 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002492 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002493 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002494 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002495 break;
2496
2497 case ORIGINAL_FILE_ID:
2498 F.OriginalSourceFileID = FileID::get(Record[0]);
2499 break;
2500
2501 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002502 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002503 break;
2504
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002505 case MODULE_NAME:
2506 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002507 if (Listener)
2508 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002509 break;
2510
Richard Smith7ed1bc92014-12-05 22:42:13 +00002511 case MODULE_DIRECTORY:
2512 F.BaseDirectory = Blob;
2513 break;
2514
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002515 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002516 if (ASTReadResult Result =
2517 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2518 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002519 break;
2520
Guy Benyei11169dd2012-12-18 14:30:41 +00002521 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002522 NumInputs = Record[0];
2523 NumUserInputs = Record[1];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002524 F.InputFileOffsets = (const uint32_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002525 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002526 break;
2527 }
2528 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002529}
2530
Ben Langmuir2c9af442014-04-10 17:57:43 +00002531ASTReader::ASTReadResult
2532ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002533 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002534
2535 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2536 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002537 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002538 }
2539
2540 // Read all of the records and blocks for the AST file.
2541 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002542 while (1) {
2543 llvm::BitstreamEntry Entry = Stream.advance();
2544
2545 switch (Entry.Kind) {
2546 case llvm::BitstreamEntry::Error:
2547 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002548 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002549 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002550 // Outside of C++, we do not store a lookup map for the translation unit.
2551 // Instead, mark it as needing a lookup map to be built if this module
2552 // contains any declarations lexically within it (which it always does!).
2553 // This usually has no cost, since we very rarely need the lookup map for
2554 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002555 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002556 if (DC->hasExternalLexicalStorage() &&
2557 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002558 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002559
Ben Langmuir2c9af442014-04-10 17:57:43 +00002560 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002561 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002562 case llvm::BitstreamEntry::SubBlock:
2563 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002564 case DECLTYPES_BLOCK_ID:
2565 // We lazily load the decls block, but we want to set up the
2566 // DeclsCursor cursor to point into it. Clone our current bitcode
2567 // cursor to it, enter the block and read the abbrevs in that block.
2568 // With the main cursor, we just skip over it.
2569 F.DeclsCursor = Stream;
2570 if (Stream.SkipBlock() || // Skip with the main cursor.
2571 // Read the abbrevs.
2572 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2573 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002574 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002575 }
2576 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002577
Guy Benyei11169dd2012-12-18 14:30:41 +00002578 case PREPROCESSOR_BLOCK_ID:
2579 F.MacroCursor = Stream;
2580 if (!PP.getExternalSource())
2581 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002582
Guy Benyei11169dd2012-12-18 14:30:41 +00002583 if (Stream.SkipBlock() ||
2584 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2585 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002586 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002587 }
2588 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2589 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002590
Guy Benyei11169dd2012-12-18 14:30:41 +00002591 case PREPROCESSOR_DETAIL_BLOCK_ID:
2592 F.PreprocessorDetailCursor = Stream;
2593 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002594 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002596 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002597 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002598 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002599 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002600 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2601
Guy Benyei11169dd2012-12-18 14:30:41 +00002602 if (!PP.getPreprocessingRecord())
2603 PP.createPreprocessingRecord();
2604 if (!PP.getPreprocessingRecord()->getExternalSource())
2605 PP.getPreprocessingRecord()->SetExternalSource(*this);
2606 break;
2607
2608 case SOURCE_MANAGER_BLOCK_ID:
2609 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002610 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002611 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002612
Guy Benyei11169dd2012-12-18 14:30:41 +00002613 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002614 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2615 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002616 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002617
Guy Benyei11169dd2012-12-18 14:30:41 +00002618 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002619 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002620 if (Stream.SkipBlock() ||
2621 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2622 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002623 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002624 }
2625 CommentsCursors.push_back(std::make_pair(C, &F));
2626 break;
2627 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002628
Guy Benyei11169dd2012-12-18 14:30:41 +00002629 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002630 if (Stream.SkipBlock()) {
2631 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002632 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002633 }
2634 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 }
2636 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002637
2638 case llvm::BitstreamEntry::Record:
2639 // The interesting case.
2640 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002641 }
2642
2643 // Read and process a record.
2644 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002645 StringRef Blob;
2646 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002647 default: // Default behavior: ignore.
2648 break;
2649
2650 case TYPE_OFFSET: {
2651 if (F.LocalNumTypes != 0) {
2652 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002653 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002654 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002655 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002656 F.LocalNumTypes = Record[0];
2657 unsigned LocalBaseTypeIndex = Record[1];
2658 F.BaseTypeIndex = getTotalNumTypes();
2659
2660 if (F.LocalNumTypes > 0) {
2661 // Introduce the global -> local mapping for types within this module.
2662 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2663
2664 // Introduce the local -> global mapping for types within this module.
2665 F.TypeRemap.insertOrReplace(
2666 std::make_pair(LocalBaseTypeIndex,
2667 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002668
2669 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002670 }
2671 break;
2672 }
2673
2674 case DECL_OFFSET: {
2675 if (F.LocalNumDecls != 0) {
2676 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002677 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002678 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002679 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002680 F.LocalNumDecls = Record[0];
2681 unsigned LocalBaseDeclID = Record[1];
2682 F.BaseDeclID = getTotalNumDecls();
2683
2684 if (F.LocalNumDecls > 0) {
2685 // Introduce the global -> local mapping for declarations within this
2686 // module.
2687 GlobalDeclMap.insert(
2688 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2689
2690 // Introduce the local -> global mapping for declarations within this
2691 // module.
2692 F.DeclRemap.insertOrReplace(
2693 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2694
2695 // Introduce the global -> local mapping for declarations within this
2696 // module.
2697 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002698
Ben Langmuir52ca6782014-10-20 16:27:32 +00002699 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2700 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002701 break;
2702 }
2703
2704 case TU_UPDATE_LEXICAL: {
2705 DeclContext *TU = Context.getTranslationUnitDecl();
2706 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002707 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002708 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002709 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002710 TU->setHasExternalLexicalStorage(true);
2711 break;
2712 }
2713
2714 case UPDATE_VISIBLE: {
2715 unsigned Idx = 0;
2716 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2717 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002718 ASTDeclContextNameLookupTable::Create(
2719 (const unsigned char *)Blob.data() + Record[Idx++],
2720 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2721 (const unsigned char *)Blob.data(),
2722 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002723 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002724 auto *DC = cast<DeclContext>(D);
2725 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002726 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2727 delete LookupTable;
2728 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002729 } else
2730 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2731 break;
2732 }
2733
2734 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002735 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002736 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002737 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2738 (const unsigned char *)F.IdentifierTableData + Record[0],
2739 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2740 (const unsigned char *)F.IdentifierTableData,
2741 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002742
2743 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2744 }
2745 break;
2746
2747 case IDENTIFIER_OFFSET: {
2748 if (F.LocalNumIdentifiers != 0) {
2749 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002750 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002751 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002752 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002753 F.LocalNumIdentifiers = Record[0];
2754 unsigned LocalBaseIdentifierID = Record[1];
2755 F.BaseIdentifierID = getTotalNumIdentifiers();
2756
2757 if (F.LocalNumIdentifiers > 0) {
2758 // Introduce the global -> local mapping for identifiers within this
2759 // module.
2760 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2761 &F));
2762
2763 // Introduce the local -> global mapping for identifiers within this
2764 // module.
2765 F.IdentifierRemap.insertOrReplace(
2766 std::make_pair(LocalBaseIdentifierID,
2767 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002768
Ben Langmuir52ca6782014-10-20 16:27:32 +00002769 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2770 + F.LocalNumIdentifiers);
2771 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002772 break;
2773 }
2774
Ben Langmuir332aafe2014-01-31 01:06:56 +00002775 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002776 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002777 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002778 break;
2779
2780 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002781 if (SpecialTypes.empty()) {
2782 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2783 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2784 break;
2785 }
2786
2787 if (SpecialTypes.size() != Record.size()) {
2788 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002789 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002790 }
2791
2792 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2793 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2794 if (!SpecialTypes[I])
2795 SpecialTypes[I] = ID;
2796 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2797 // merge step?
2798 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002799 break;
2800
2801 case STATISTICS:
2802 TotalNumStatements += Record[0];
2803 TotalNumMacros += Record[1];
2804 TotalLexicalDeclContexts += Record[2];
2805 TotalVisibleDeclContexts += Record[3];
2806 break;
2807
2808 case UNUSED_FILESCOPED_DECLS:
2809 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2810 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2811 break;
2812
2813 case DELEGATING_CTORS:
2814 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2815 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2816 break;
2817
2818 case WEAK_UNDECLARED_IDENTIFIERS:
2819 if (Record.size() % 4 != 0) {
2820 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002821 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002822 }
2823
2824 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2825 // files. This isn't the way to do it :)
2826 WeakUndeclaredIdentifiers.clear();
2827
2828 // Translate the weak, undeclared identifiers into global IDs.
2829 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2830 WeakUndeclaredIdentifiers.push_back(
2831 getGlobalIdentifierID(F, Record[I++]));
2832 WeakUndeclaredIdentifiers.push_back(
2833 getGlobalIdentifierID(F, Record[I++]));
2834 WeakUndeclaredIdentifiers.push_back(
2835 ReadSourceLocation(F, Record, I).getRawEncoding());
2836 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2837 }
2838 break;
2839
Richard Smith78165b52013-01-10 23:43:47 +00002840 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002841 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith78165b52013-01-10 23:43:47 +00002842 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002843 break;
2844
2845 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002846 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002847 F.LocalNumSelectors = Record[0];
2848 unsigned LocalBaseSelectorID = Record[1];
2849 F.BaseSelectorID = getTotalNumSelectors();
2850
2851 if (F.LocalNumSelectors > 0) {
2852 // Introduce the global -> local mapping for selectors within this
2853 // module.
2854 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2855
2856 // Introduce the local -> global mapping for selectors within this
2857 // module.
2858 F.SelectorRemap.insertOrReplace(
2859 std::make_pair(LocalBaseSelectorID,
2860 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002861
2862 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002863 }
2864 break;
2865 }
2866
2867 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002868 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002869 if (Record[0])
2870 F.SelectorLookupTable
2871 = ASTSelectorLookupTable::Create(
2872 F.SelectorLookupTableData + Record[0],
2873 F.SelectorLookupTableData,
2874 ASTSelectorLookupTrait(*this, F));
2875 TotalNumMethodPoolEntries += Record[1];
2876 break;
2877
2878 case REFERENCED_SELECTOR_POOL:
2879 if (!Record.empty()) {
2880 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2881 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2882 Record[Idx++]));
2883 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2884 getRawEncoding());
2885 }
2886 }
2887 break;
2888
2889 case PP_COUNTER_VALUE:
2890 if (!Record.empty() && Listener)
2891 Listener->ReadCounter(F, Record[0]);
2892 break;
2893
2894 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002895 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002896 F.NumFileSortedDecls = Record[0];
2897 break;
2898
2899 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002900 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002901 F.LocalNumSLocEntries = Record[0];
2902 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002903 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002904 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002905 SLocSpaceSize);
2906 // Make our entry in the range map. BaseID is negative and growing, so
2907 // we invert it. Because we invert it, though, we need the other end of
2908 // the range.
2909 unsigned RangeStart =
2910 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2911 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2912 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2913
2914 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2915 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2916 GlobalSLocOffsetMap.insert(
2917 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2918 - SLocSpaceSize,&F));
2919
2920 // Initialize the remapping table.
2921 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002922 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002923 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002924 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002925 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2926
2927 TotalNumSLocEntries += F.LocalNumSLocEntries;
2928 break;
2929 }
2930
2931 case MODULE_OFFSET_MAP: {
2932 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002933 const unsigned char *Data = (const unsigned char*)Blob.data();
2934 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002935
2936 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2937 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2938 F.SLocRemap.insert(std::make_pair(0U, 0));
2939 F.SLocRemap.insert(std::make_pair(2U, 1));
2940 }
2941
Guy Benyei11169dd2012-12-18 14:30:41 +00002942 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002943 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2944 RemapBuilder;
2945 RemapBuilder SLocRemap(F.SLocRemap);
2946 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2947 RemapBuilder MacroRemap(F.MacroRemap);
2948 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2949 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2950 RemapBuilder SelectorRemap(F.SelectorRemap);
2951 RemapBuilder DeclRemap(F.DeclRemap);
2952 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002953
2954 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002955 using namespace llvm::support;
2956 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002957 StringRef Name = StringRef((const char*)Data, Len);
2958 Data += Len;
2959 ModuleFile *OM = ModuleMgr.lookup(Name);
2960 if (!OM) {
2961 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002962 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002963 }
2964
Justin Bogner57ba0b22014-03-28 22:03:24 +00002965 uint32_t SLocOffset =
2966 endian::readNext<uint32_t, little, unaligned>(Data);
2967 uint32_t IdentifierIDOffset =
2968 endian::readNext<uint32_t, little, unaligned>(Data);
2969 uint32_t MacroIDOffset =
2970 endian::readNext<uint32_t, little, unaligned>(Data);
2971 uint32_t PreprocessedEntityIDOffset =
2972 endian::readNext<uint32_t, little, unaligned>(Data);
2973 uint32_t SubmoduleIDOffset =
2974 endian::readNext<uint32_t, little, unaligned>(Data);
2975 uint32_t SelectorIDOffset =
2976 endian::readNext<uint32_t, little, unaligned>(Data);
2977 uint32_t DeclIDOffset =
2978 endian::readNext<uint32_t, little, unaligned>(Data);
2979 uint32_t TypeIndexOffset =
2980 endian::readNext<uint32_t, little, unaligned>(Data);
2981
Ben Langmuir785180e2014-10-20 16:27:30 +00002982 uint32_t None = std::numeric_limits<uint32_t>::max();
2983
2984 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2985 RemapBuilder &Remap) {
2986 if (Offset != None)
2987 Remap.insert(std::make_pair(Offset,
2988 static_cast<int>(BaseOffset - Offset)));
2989 };
2990 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2991 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2992 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2993 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2994 PreprocessedEntityRemap);
2995 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2996 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2997 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2998 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002999
3000 // Global -> local mappings.
3001 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3002 }
3003 break;
3004 }
3005
3006 case SOURCE_MANAGER_LINE_TABLE:
3007 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003008 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003009 break;
3010
3011 case SOURCE_LOCATION_PRELOADS: {
3012 // Need to transform from the local view (1-based IDs) to the global view,
3013 // which is based off F.SLocEntryBaseID.
3014 if (!F.PreloadSLocEntries.empty()) {
3015 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003016 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003017 }
3018
3019 F.PreloadSLocEntries.swap(Record);
3020 break;
3021 }
3022
3023 case EXT_VECTOR_DECLS:
3024 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3025 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3026 break;
3027
3028 case VTABLE_USES:
3029 if (Record.size() % 3 != 0) {
3030 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003031 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003032 }
3033
3034 // Later tables overwrite earlier ones.
3035 // FIXME: Modules will have some trouble with this. This is clearly not
3036 // the right way to do this.
3037 VTableUses.clear();
3038
3039 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3040 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3041 VTableUses.push_back(
3042 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3043 VTableUses.push_back(Record[Idx++]);
3044 }
3045 break;
3046
3047 case DYNAMIC_CLASSES:
3048 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3049 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
3050 break;
3051
3052 case PENDING_IMPLICIT_INSTANTIATIONS:
3053 if (PendingInstantiations.size() % 2 != 0) {
3054 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003055 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003056 }
3057
3058 if (Record.size() % 2 != 0) {
3059 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003060 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003061 }
3062
3063 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3064 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3065 PendingInstantiations.push_back(
3066 ReadSourceLocation(F, Record, I).getRawEncoding());
3067 }
3068 break;
3069
3070 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00003071 if (Record.size() != 2) {
3072 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003073 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003074 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003075 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3076 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3077 break;
3078
3079 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003080 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3081 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3082 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003083
3084 unsigned LocalBasePreprocessedEntityID = Record[0];
3085
3086 unsigned StartingID;
3087 if (!PP.getPreprocessingRecord())
3088 PP.createPreprocessingRecord();
3089 if (!PP.getPreprocessingRecord()->getExternalSource())
3090 PP.getPreprocessingRecord()->SetExternalSource(*this);
3091 StartingID
3092 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003093 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003094 F.BasePreprocessedEntityID = StartingID;
3095
3096 if (F.NumPreprocessedEntities > 0) {
3097 // Introduce the global -> local mapping for preprocessed entities in
3098 // this module.
3099 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3100
3101 // Introduce the local -> global mapping for preprocessed entities in
3102 // this module.
3103 F.PreprocessedEntityRemap.insertOrReplace(
3104 std::make_pair(LocalBasePreprocessedEntityID,
3105 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3106 }
3107
3108 break;
3109 }
3110
3111 case DECL_UPDATE_OFFSETS: {
3112 if (Record.size() % 2 != 0) {
3113 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003114 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003115 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003116 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3117 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3118 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3119
3120 // If we've already loaded the decl, perform the updates when we finish
3121 // loading this block.
3122 if (Decl *D = GetExistingDecl(ID))
3123 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3124 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003125 break;
3126 }
3127
3128 case DECL_REPLACEMENTS: {
3129 if (Record.size() % 3 != 0) {
3130 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003131 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003132 }
3133 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3134 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3135 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3136 break;
3137 }
3138
3139 case OBJC_CATEGORIES_MAP: {
3140 if (F.LocalNumObjCCategoriesInMap != 0) {
3141 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003142 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003143 }
3144
3145 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003146 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003147 break;
3148 }
3149
3150 case OBJC_CATEGORIES:
3151 F.ObjCCategories.swap(Record);
3152 break;
3153
3154 case CXX_BASE_SPECIFIER_OFFSETS: {
3155 if (F.LocalNumCXXBaseSpecifiers != 0) {
3156 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003157 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003158 }
3159
3160 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003161 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003162 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
3163 break;
3164 }
3165
3166 case DIAG_PRAGMA_MAPPINGS:
3167 if (F.PragmaDiagMappings.empty())
3168 F.PragmaDiagMappings.swap(Record);
3169 else
3170 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3171 Record.begin(), Record.end());
3172 break;
3173
3174 case CUDA_SPECIAL_DECL_REFS:
3175 // Later tables overwrite earlier ones.
3176 // FIXME: Modules will have trouble with this.
3177 CUDASpecialDeclRefs.clear();
3178 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3179 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3180 break;
3181
3182 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003183 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003184 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003185 if (Record[0]) {
3186 F.HeaderFileInfoTable
3187 = HeaderFileInfoLookupTable::Create(
3188 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3189 (const unsigned char *)F.HeaderFileInfoTableData,
3190 HeaderFileInfoTrait(*this, F,
3191 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003192 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003193
3194 PP.getHeaderSearchInfo().SetExternalSource(this);
3195 if (!PP.getHeaderSearchInfo().getExternalLookup())
3196 PP.getHeaderSearchInfo().SetExternalLookup(this);
3197 }
3198 break;
3199 }
3200
3201 case FP_PRAGMA_OPTIONS:
3202 // Later tables overwrite earlier ones.
3203 FPPragmaOptions.swap(Record);
3204 break;
3205
3206 case OPENCL_EXTENSIONS:
3207 // Later tables overwrite earlier ones.
3208 OpenCLExtensions.swap(Record);
3209 break;
3210
3211 case TENTATIVE_DEFINITIONS:
3212 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3213 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3214 break;
3215
3216 case KNOWN_NAMESPACES:
3217 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3218 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3219 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003220
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003221 case UNDEFINED_BUT_USED:
3222 if (UndefinedButUsed.size() % 2 != 0) {
3223 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003224 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003225 }
3226
3227 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003228 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003229 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003230 }
3231 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003232 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3233 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003234 ReadSourceLocation(F, Record, I).getRawEncoding());
3235 }
3236 break;
3237
Guy Benyei11169dd2012-12-18 14:30:41 +00003238 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003239 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003240 // If we aren't loading a module (which has its own exports), make
3241 // all of the imported modules visible.
3242 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003243 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3244 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3245 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3246 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003247 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003248 }
3249 }
3250 break;
3251 }
3252
3253 case LOCAL_REDECLARATIONS: {
3254 F.RedeclarationChains.swap(Record);
3255 break;
3256 }
3257
3258 case LOCAL_REDECLARATIONS_MAP: {
3259 if (F.LocalNumRedeclarationsInMap != 0) {
3260 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003261 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003262 }
3263
3264 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003265 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003266 break;
3267 }
3268
3269 case MERGED_DECLARATIONS: {
3270 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3271 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3272 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3273 for (unsigned N = Record[Idx++]; N > 0; --N)
3274 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3275 }
3276 break;
3277 }
3278
3279 case MACRO_OFFSET: {
3280 if (F.LocalNumMacros != 0) {
3281 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003282 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003283 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003284 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003285 F.LocalNumMacros = Record[0];
3286 unsigned LocalBaseMacroID = Record[1];
3287 F.BaseMacroID = getTotalNumMacros();
3288
3289 if (F.LocalNumMacros > 0) {
3290 // Introduce the global -> local mapping for macros within this module.
3291 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3292
3293 // Introduce the local -> global mapping for macros within this module.
3294 F.MacroRemap.insertOrReplace(
3295 std::make_pair(LocalBaseMacroID,
3296 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003297
3298 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003299 }
3300 break;
3301 }
3302
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003303 case MACRO_TABLE: {
3304 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00003305 break;
3306 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00003307
3308 case LATE_PARSED_TEMPLATE: {
3309 LateParsedTemplates.append(Record.begin(), Record.end());
3310 break;
3311 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003312
3313 case OPTIMIZE_PRAGMA_OPTIONS:
3314 if (Record.size() != 1) {
3315 Error("invalid pragma optimize record");
3316 return Failure;
3317 }
3318 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3319 break;
Nico Weber72889432014-09-06 01:25:55 +00003320
3321 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3322 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3323 UnusedLocalTypedefNameCandidates.push_back(
3324 getGlobalDeclID(F, Record[I]));
3325 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003326 }
3327 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003328}
3329
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003330ASTReader::ASTReadResult
3331ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3332 const ModuleFile *ImportedBy,
3333 unsigned ClientLoadCapabilities) {
3334 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003335 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003336
Richard Smithe842a472014-10-22 02:05:46 +00003337 if (F.Kind == MK_ExplicitModule) {
3338 // For an explicitly-loaded module, we don't care whether the original
3339 // module map file exists or matches.
3340 return Success;
3341 }
3342
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003343 // Try to resolve ModuleName in the current header search context and
3344 // verify that it is found in the same module map file as we saved. If the
3345 // top-level AST file is a main file, skip this check because there is no
3346 // usable header search context.
3347 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003348 "MODULE_NAME should come before MODULE_MAP_FILE");
3349 if (F.Kind == MK_ImplicitModule &&
3350 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3351 // An implicitly-loaded module file should have its module listed in some
3352 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003353 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003354 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3355 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3356 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003357 assert(ImportedBy && "top-level import should be verified");
3358 if ((ClientLoadCapabilities & ARR_Missing) == 0)
Richard Smithe842a472014-10-22 02:05:46 +00003359 Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3360 << ImportedBy->FileName
3361 << F.ModuleMapPath;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003362 return Missing;
3363 }
3364
Richard Smithe842a472014-10-22 02:05:46 +00003365 assert(M->Name == F.ModuleName && "found module with different name");
3366
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003367 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003368 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003369 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3370 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003371 assert(ImportedBy && "top-level import should be verified");
3372 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3373 Diag(diag::err_imported_module_modmap_changed)
3374 << F.ModuleName << ImportedBy->FileName
3375 << ModMap->getName() << F.ModuleMapPath;
3376 return OutOfDate;
3377 }
3378
3379 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3380 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3381 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003382 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003383 const FileEntry *F =
3384 FileMgr.getFile(Filename, false, false);
3385 if (F == nullptr) {
3386 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3387 Error("could not find file '" + Filename +"' referenced by AST file");
3388 return OutOfDate;
3389 }
3390 AdditionalStoredMaps.insert(F);
3391 }
3392
3393 // Check any additional module map files (e.g. module.private.modulemap)
3394 // that are not in the pcm.
3395 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3396 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3397 // Remove files that match
3398 // Note: SmallPtrSet::erase is really remove
3399 if (!AdditionalStoredMaps.erase(ModMap)) {
3400 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3401 Diag(diag::err_module_different_modmap)
3402 << F.ModuleName << /*new*/0 << ModMap->getName();
3403 return OutOfDate;
3404 }
3405 }
3406 }
3407
3408 // Check any additional module map files that are in the pcm, but not
3409 // found in header search. Cases that match are already removed.
3410 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3411 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3412 Diag(diag::err_module_different_modmap)
3413 << F.ModuleName << /*not new*/1 << ModMap->getName();
3414 return OutOfDate;
3415 }
3416 }
3417
3418 if (Listener)
3419 Listener->ReadModuleMapFile(F.ModuleMapPath);
3420 return Success;
3421}
3422
3423
Douglas Gregorc1489562013-02-12 23:36:21 +00003424/// \brief Move the given method to the back of the global list of methods.
3425static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3426 // Find the entry for this selector in the method pool.
3427 Sema::GlobalMethodPool::iterator Known
3428 = S.MethodPool.find(Method->getSelector());
3429 if (Known == S.MethodPool.end())
3430 return;
3431
3432 // Retrieve the appropriate method list.
3433 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3434 : Known->second.second;
3435 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003436 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003437 if (!Found) {
3438 if (List->Method == Method) {
3439 Found = true;
3440 } else {
3441 // Keep searching.
3442 continue;
3443 }
3444 }
3445
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003446 if (List->getNext())
3447 List->Method = List->getNext()->Method;
Douglas Gregorc1489562013-02-12 23:36:21 +00003448 else
3449 List->Method = Method;
3450 }
3451}
3452
Richard Smithe657bbd2014-07-18 22:13:40 +00003453void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner,
3454 bool FromFinalization) {
3455 // FIXME: Only do this if Owner->NameVisibility == AllVisible.
Richard Smith57721ac2014-07-21 04:10:40 +00003456 for (Decl *D : Names.HiddenDecls) {
Richard Smith49f906a2014-03-01 00:08:04 +00003457 bool wasHidden = D->Hidden;
3458 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003459
Richard Smith49f906a2014-03-01 00:08:04 +00003460 if (wasHidden && SemaObj) {
3461 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3462 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003463 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003464 }
3465 }
Richard Smith49f906a2014-03-01 00:08:04 +00003466
Richard Smithe657bbd2014-07-18 22:13:40 +00003467 assert((FromFinalization || Owner->NameVisibility >= Module::MacrosVisible) &&
3468 "nothing to make visible?");
Richard Smithdaa69e02014-07-25 04:40:03 +00003469 for (const auto &Macro : Names.HiddenMacros) {
3470 if (FromFinalization)
3471 PP.appendMacroDirective(Macro.first,
3472 Macro.second->import(PP, SourceLocation()));
3473 else
3474 installImportedMacro(Macro.first, Macro.second, Owner);
3475 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003476}
3477
Richard Smith49f906a2014-03-01 00:08:04 +00003478void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003479 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003480 SourceLocation ImportLoc,
3481 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003482 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003483 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003484 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003485 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003486 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003487
3488 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003489 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003490 // there is nothing more to do.
3491 continue;
3492 }
Richard Smith49f906a2014-03-01 00:08:04 +00003493
Guy Benyei11169dd2012-12-18 14:30:41 +00003494 if (!Mod->isAvailable()) {
3495 // Modules that aren't available cannot be made visible.
3496 continue;
3497 }
3498
3499 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003500 if (NameVisibility >= Module::MacrosVisible &&
3501 Mod->NameVisibility < Module::MacrosVisible)
3502 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003503 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003504
Guy Benyei11169dd2012-12-18 14:30:41 +00003505 // If we've already deserialized any names from this module,
3506 // mark them as visible.
3507 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3508 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003509 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003510 HiddenNamesMap.erase(Hidden);
Richard Smith57721ac2014-07-21 04:10:40 +00003511 makeNamesVisible(HiddenNames.second, HiddenNames.first,
3512 /*FromFinalization*/false);
3513 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3514 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003515 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003516
Guy Benyei11169dd2012-12-18 14:30:41 +00003517 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003518 SmallVector<Module *, 16> Exports;
3519 Mod->getExportedModules(Exports);
3520 for (SmallVectorImpl<Module *>::iterator
3521 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3522 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003523 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003524 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003525 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003526
3527 // Detect any conflicts.
3528 if (Complain) {
3529 assert(ImportLoc.isValid() && "Missing import location");
3530 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3531 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3532 Diag(ImportLoc, diag::warn_module_conflict)
3533 << Mod->getFullModuleName()
3534 << Mod->Conflicts[I].Other->getFullModuleName()
3535 << Mod->Conflicts[I].Message;
3536 // FIXME: Need note where the other module was imported.
3537 }
3538 }
3539 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003540 }
3541}
3542
Douglas Gregore060e572013-01-25 01:03:03 +00003543bool ASTReader::loadGlobalIndex() {
3544 if (GlobalIndex)
3545 return false;
3546
3547 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3548 !Context.getLangOpts().Modules)
3549 return true;
3550
3551 // Try to load the global index.
3552 TriedLoadingGlobalIndex = true;
3553 StringRef ModuleCachePath
3554 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3555 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003556 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003557 if (!Result.first)
3558 return true;
3559
3560 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003561 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003562 return false;
3563}
3564
3565bool ASTReader::isGlobalIndexUnavailable() const {
3566 return Context.getLangOpts().Modules && UseGlobalIndex &&
3567 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3568}
3569
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003570static void updateModuleTimestamp(ModuleFile &MF) {
3571 // Overwrite the timestamp file contents so that file's mtime changes.
3572 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003573 std::error_code EC;
3574 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3575 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003576 return;
3577 OS << "Timestamp file\n";
3578}
3579
Guy Benyei11169dd2012-12-18 14:30:41 +00003580ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3581 ModuleKind Type,
3582 SourceLocation ImportLoc,
3583 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003584 llvm::SaveAndRestore<SourceLocation>
3585 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3586
Richard Smithd1c46742014-04-30 02:24:17 +00003587 // Defer any pending actions until we get to the end of reading the AST file.
3588 Deserializing AnASTFile(this);
3589
Guy Benyei11169dd2012-12-18 14:30:41 +00003590 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003591 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003592
3593 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003594 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003595 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003596 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003597 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003598 ClientLoadCapabilities)) {
3599 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003600 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003601 case OutOfDate:
3602 case VersionMismatch:
3603 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003604 case HadErrors: {
3605 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3606 for (const ImportedModule &IM : Loaded)
3607 LoadedSet.insert(IM.Mod);
3608
Douglas Gregor7029ce12013-03-19 00:28:20 +00003609 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003610 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003611 Context.getLangOpts().Modules
3612 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003613 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003614
3615 // If we find that any modules are unusable, the global index is going
3616 // to be out-of-date. Just remove it.
3617 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003618 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003619 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003620 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003621 case Success:
3622 break;
3623 }
3624
3625 // Here comes stuff that we only do once the entire chain is loaded.
3626
3627 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003628 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3629 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003630 M != MEnd; ++M) {
3631 ModuleFile &F = *M->Mod;
3632
3633 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003634 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3635 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003636
3637 // Once read, set the ModuleFile bit base offset and update the size in
3638 // bits of all files we've seen.
3639 F.GlobalBitOffset = TotalModulesSizeInBits;
3640 TotalModulesSizeInBits += F.SizeInBits;
3641 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3642
3643 // Preload SLocEntries.
3644 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3645 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3646 // Load it through the SourceManager and don't call ReadSLocEntry()
3647 // directly because the entry may have already been loaded in which case
3648 // calling ReadSLocEntry() directly would trigger an assertion in
3649 // SourceManager.
3650 SourceMgr.getLoadedSLocEntryByID(Index);
3651 }
3652 }
3653
Douglas Gregor603cd862013-03-22 18:50:14 +00003654 // Setup the import locations and notify the module manager that we've
3655 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003656 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3657 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003658 M != MEnd; ++M) {
3659 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003660
3661 ModuleMgr.moduleFileAccepted(&F);
3662
3663 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003664 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003665 if (!M->ImportedBy)
3666 F.ImportLoc = M->ImportLoc;
3667 else
3668 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3669 M->ImportLoc.getRawEncoding());
3670 }
3671
3672 // Mark all of the identifiers in the identifier table as being out of date,
3673 // so that various accessors know to check the loaded modules when the
3674 // identifier is used.
3675 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3676 IdEnd = PP.getIdentifierTable().end();
3677 Id != IdEnd; ++Id)
3678 Id->second->setOutOfDate(true);
3679
3680 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003681 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3682 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003683 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3684 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003685
3686 switch (Unresolved.Kind) {
3687 case UnresolvedModuleRef::Conflict:
3688 if (ResolvedMod) {
3689 Module::Conflict Conflict;
3690 Conflict.Other = ResolvedMod;
3691 Conflict.Message = Unresolved.String.str();
3692 Unresolved.Mod->Conflicts.push_back(Conflict);
3693 }
3694 continue;
3695
3696 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003697 if (ResolvedMod)
3698 Unresolved.Mod->Imports.push_back(ResolvedMod);
3699 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003700
Douglas Gregorfb912652013-03-20 21:10:35 +00003701 case UnresolvedModuleRef::Export:
3702 if (ResolvedMod || Unresolved.IsWildcard)
3703 Unresolved.Mod->Exports.push_back(
3704 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3705 continue;
3706 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003707 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003708 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003709
3710 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3711 // Might be unnecessary as use declarations are only used to build the
3712 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003713
3714 InitializeContext();
3715
Richard Smith3d8e97e2013-10-18 06:54:39 +00003716 if (SemaObj)
3717 UpdateSema();
3718
Guy Benyei11169dd2012-12-18 14:30:41 +00003719 if (DeserializationListener)
3720 DeserializationListener->ReaderInitialized(this);
3721
3722 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3723 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3724 PrimaryModule.OriginalSourceFileID
3725 = FileID::get(PrimaryModule.SLocEntryBaseID
3726 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3727
3728 // If this AST file is a precompiled preamble, then set the
3729 // preamble file ID of the source manager to the file source file
3730 // from which the preamble was built.
3731 if (Type == MK_Preamble) {
3732 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3733 } else if (Type == MK_MainFile) {
3734 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3735 }
3736 }
3737
3738 // For any Objective-C class definitions we have already loaded, make sure
3739 // that we load any additional categories.
3740 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3741 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3742 ObjCClassesLoaded[I],
3743 PreviousGeneration);
3744 }
Douglas Gregore060e572013-01-25 01:03:03 +00003745
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003746 if (PP.getHeaderSearchInfo()
3747 .getHeaderSearchOpts()
3748 .ModulesValidateOncePerBuildSession) {
3749 // Now we are certain that the module and all modules it depends on are
3750 // up to date. Create or update timestamp files for modules that are
3751 // located in the module cache (not for PCH files that could be anywhere
3752 // in the filesystem).
3753 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3754 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003755 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003756 updateModuleTimestamp(*M.Mod);
3757 }
3758 }
3759 }
3760
Guy Benyei11169dd2012-12-18 14:30:41 +00003761 return Success;
3762}
3763
Ben Langmuir487ea142014-10-23 18:05:36 +00003764static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3765
Guy Benyei11169dd2012-12-18 14:30:41 +00003766ASTReader::ASTReadResult
3767ASTReader::ReadASTCore(StringRef FileName,
3768 ModuleKind Type,
3769 SourceLocation ImportLoc,
3770 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003771 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003772 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003773 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003774 unsigned ClientLoadCapabilities) {
3775 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003776 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003777 ModuleManager::AddModuleResult AddResult
3778 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003779 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003780 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003781 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003782
Douglas Gregor7029ce12013-03-19 00:28:20 +00003783 switch (AddResult) {
3784 case ModuleManager::AlreadyLoaded:
3785 return Success;
3786
3787 case ModuleManager::NewlyLoaded:
3788 // Load module file below.
3789 break;
3790
3791 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003792 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003793 // it.
3794 if (ClientLoadCapabilities & ARR_Missing)
3795 return Missing;
3796
3797 // Otherwise, return an error.
3798 {
3799 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3800 + ErrorStr;
3801 Error(Msg);
3802 }
3803 return Failure;
3804
3805 case ModuleManager::OutOfDate:
3806 // We couldn't load the module file because it is out-of-date. If the
3807 // client can handle out-of-date, return it.
3808 if (ClientLoadCapabilities & ARR_OutOfDate)
3809 return OutOfDate;
3810
3811 // Otherwise, return an error.
3812 {
3813 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3814 + ErrorStr;
3815 Error(Msg);
3816 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003817 return Failure;
3818 }
3819
Douglas Gregor7029ce12013-03-19 00:28:20 +00003820 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003821
3822 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3823 // module?
3824 if (FileName != "-") {
3825 CurrentDir = llvm::sys::path::parent_path(FileName);
3826 if (CurrentDir.empty()) CurrentDir = ".";
3827 }
3828
3829 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003830 BitstreamCursor &Stream = F.Stream;
Rafael Espindolafd832392014-11-12 14:48:44 +00003831 Stream.init(&F.StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003832 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3833
3834 // Sniff for the signature.
3835 if (Stream.Read(8) != 'C' ||
3836 Stream.Read(8) != 'P' ||
3837 Stream.Read(8) != 'C' ||
3838 Stream.Read(8) != 'H') {
3839 Diag(diag::err_not_a_pch_file) << FileName;
3840 return Failure;
3841 }
3842
3843 // This is used for compatibility with older PCH formats.
3844 bool HaveReadControlBlock = false;
3845
Chris Lattnerefa77172013-01-20 00:00:22 +00003846 while (1) {
3847 llvm::BitstreamEntry Entry = Stream.advance();
3848
3849 switch (Entry.Kind) {
3850 case llvm::BitstreamEntry::Error:
3851 case llvm::BitstreamEntry::EndBlock:
3852 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003853 Error("invalid record at top-level of AST file");
3854 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003855
3856 case llvm::BitstreamEntry::SubBlock:
3857 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003858 }
3859
Guy Benyei11169dd2012-12-18 14:30:41 +00003860 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003861 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003862 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3863 if (Stream.ReadBlockInfoBlock()) {
3864 Error("malformed BlockInfoBlock in AST file");
3865 return Failure;
3866 }
3867 break;
3868 case CONTROL_BLOCK_ID:
3869 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003870 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003871 case Success:
3872 break;
3873
3874 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003875 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003876 case OutOfDate: return OutOfDate;
3877 case VersionMismatch: return VersionMismatch;
3878 case ConfigurationMismatch: return ConfigurationMismatch;
3879 case HadErrors: return HadErrors;
3880 }
3881 break;
3882 case AST_BLOCK_ID:
3883 if (!HaveReadControlBlock) {
3884 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003885 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003886 return VersionMismatch;
3887 }
3888
3889 // Record that we've loaded this module.
3890 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3891 return Success;
3892
3893 default:
3894 if (Stream.SkipBlock()) {
3895 Error("malformed block record in AST file");
3896 return Failure;
3897 }
3898 break;
3899 }
3900 }
3901
3902 return Success;
3903}
3904
3905void ASTReader::InitializeContext() {
3906 // If there's a listener, notify them that we "read" the translation unit.
3907 if (DeserializationListener)
3908 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3909 Context.getTranslationUnitDecl());
3910
Guy Benyei11169dd2012-12-18 14:30:41 +00003911 // FIXME: Find a better way to deal with collisions between these
3912 // built-in types. Right now, we just ignore the problem.
3913
3914 // Load the special types.
3915 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3916 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3917 if (!Context.CFConstantStringTypeDecl)
3918 Context.setCFConstantStringType(GetType(String));
3919 }
3920
3921 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3922 QualType FileType = GetType(File);
3923 if (FileType.isNull()) {
3924 Error("FILE type is NULL");
3925 return;
3926 }
3927
3928 if (!Context.FILEDecl) {
3929 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3930 Context.setFILEDecl(Typedef->getDecl());
3931 else {
3932 const TagType *Tag = FileType->getAs<TagType>();
3933 if (!Tag) {
3934 Error("Invalid FILE type in AST file");
3935 return;
3936 }
3937 Context.setFILEDecl(Tag->getDecl());
3938 }
3939 }
3940 }
3941
3942 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3943 QualType Jmp_bufType = GetType(Jmp_buf);
3944 if (Jmp_bufType.isNull()) {
3945 Error("jmp_buf type is NULL");
3946 return;
3947 }
3948
3949 if (!Context.jmp_bufDecl) {
3950 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3951 Context.setjmp_bufDecl(Typedef->getDecl());
3952 else {
3953 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3954 if (!Tag) {
3955 Error("Invalid jmp_buf type in AST file");
3956 return;
3957 }
3958 Context.setjmp_bufDecl(Tag->getDecl());
3959 }
3960 }
3961 }
3962
3963 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3964 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3965 if (Sigjmp_bufType.isNull()) {
3966 Error("sigjmp_buf type is NULL");
3967 return;
3968 }
3969
3970 if (!Context.sigjmp_bufDecl) {
3971 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3972 Context.setsigjmp_bufDecl(Typedef->getDecl());
3973 else {
3974 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3975 assert(Tag && "Invalid sigjmp_buf type in AST file");
3976 Context.setsigjmp_bufDecl(Tag->getDecl());
3977 }
3978 }
3979 }
3980
3981 if (unsigned ObjCIdRedef
3982 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3983 if (Context.ObjCIdRedefinitionType.isNull())
3984 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3985 }
3986
3987 if (unsigned ObjCClassRedef
3988 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3989 if (Context.ObjCClassRedefinitionType.isNull())
3990 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3991 }
3992
3993 if (unsigned ObjCSelRedef
3994 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3995 if (Context.ObjCSelRedefinitionType.isNull())
3996 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3997 }
3998
3999 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4000 QualType Ucontext_tType = GetType(Ucontext_t);
4001 if (Ucontext_tType.isNull()) {
4002 Error("ucontext_t type is NULL");
4003 return;
4004 }
4005
4006 if (!Context.ucontext_tDecl) {
4007 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4008 Context.setucontext_tDecl(Typedef->getDecl());
4009 else {
4010 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4011 assert(Tag && "Invalid ucontext_t type in AST file");
4012 Context.setucontext_tDecl(Tag->getDecl());
4013 }
4014 }
4015 }
4016 }
4017
4018 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4019
4020 // If there were any CUDA special declarations, deserialize them.
4021 if (!CUDASpecialDeclRefs.empty()) {
4022 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4023 Context.setcudaConfigureCallDecl(
4024 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4025 }
Richard Smith56be7542014-03-21 00:33:59 +00004026
Guy Benyei11169dd2012-12-18 14:30:41 +00004027 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00004028 // FIXME: This does not make macro-only imports visible again. It also doesn't
4029 // make #includes mapped to module imports visible.
4030 for (auto &Import : ImportedModules) {
4031 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004032 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00004033 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00004034 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00004035 }
4036 ImportedModules.clear();
4037}
4038
4039void ASTReader::finalizeForWriting() {
Richard Smith57721ac2014-07-21 04:10:40 +00004040 while (!HiddenNamesMap.empty()) {
4041 auto HiddenNames = std::move(*HiddenNamesMap.begin());
4042 HiddenNamesMap.erase(HiddenNamesMap.begin());
4043 makeNamesVisible(HiddenNames.second, HiddenNames.first,
4044 /*FromFinalization*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004045 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004046}
4047
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004048/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
4049/// cursor into the start of the given block ID, returning false on success and
4050/// true on failure.
4051static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004052 while (1) {
4053 llvm::BitstreamEntry Entry = Cursor.advance();
4054 switch (Entry.Kind) {
4055 case llvm::BitstreamEntry::Error:
4056 case llvm::BitstreamEntry::EndBlock:
4057 return true;
4058
4059 case llvm::BitstreamEntry::Record:
4060 // Ignore top-level records.
4061 Cursor.skipRecord(Entry.ID);
4062 break;
4063
4064 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004065 if (Entry.ID == BlockID) {
4066 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004067 return true;
4068 // Found it!
4069 return false;
4070 }
4071
4072 if (Cursor.SkipBlock())
4073 return true;
4074 }
4075 }
4076}
4077
Ben Langmuir487ea142014-10-23 18:05:36 +00004078static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
4079 BitstreamCursor Stream(StreamFile);
4080 if (Stream.Read(8) != 'C' ||
4081 Stream.Read(8) != 'P' ||
4082 Stream.Read(8) != 'C' ||
4083 Stream.Read(8) != 'H') {
4084 return 0;
4085 }
4086
4087 // Scan for the CONTROL_BLOCK_ID block.
4088 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4089 return 0;
4090
4091 // Scan for SIGNATURE inside the control block.
4092 ASTReader::RecordData Record;
4093 while (1) {
4094 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4095 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
4096 Entry.Kind != llvm::BitstreamEntry::Record)
4097 return 0;
4098
4099 Record.clear();
4100 StringRef Blob;
4101 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4102 return Record[0];
4103 }
4104}
4105
Guy Benyei11169dd2012-12-18 14:30:41 +00004106/// \brief Retrieve the name of the original source file name
4107/// directly from the AST file, without actually loading the AST
4108/// file.
4109std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
4110 FileManager &FileMgr,
4111 DiagnosticsEngine &Diags) {
4112 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004113 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004114 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004115 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4116 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004117 return std::string();
4118 }
4119
4120 // Initialize the stream
4121 llvm::BitstreamReader StreamFile;
Benjamin Kramera8857962014-10-26 22:44:13 +00004122 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
4123 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004124 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004125
4126 // Sniff for the signature.
4127 if (Stream.Read(8) != 'C' ||
4128 Stream.Read(8) != 'P' ||
4129 Stream.Read(8) != 'C' ||
4130 Stream.Read(8) != 'H') {
4131 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4132 return std::string();
4133 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004134
Chris Lattnere7b154b2013-01-19 21:39:22 +00004135 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004136 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004137 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4138 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004139 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004140
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004141 // Scan for ORIGINAL_FILE inside the control block.
4142 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004143 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004144 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004145 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4146 return std::string();
4147
4148 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4149 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4150 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004151 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004152
Guy Benyei11169dd2012-12-18 14:30:41 +00004153 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004154 StringRef Blob;
4155 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4156 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004157 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004158}
4159
4160namespace {
4161 class SimplePCHValidator : public ASTReaderListener {
4162 const LangOptions &ExistingLangOpts;
4163 const TargetOptions &ExistingTargetOpts;
4164 const PreprocessorOptions &ExistingPPOpts;
4165 FileManager &FileMgr;
4166
4167 public:
4168 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4169 const TargetOptions &ExistingTargetOpts,
4170 const PreprocessorOptions &ExistingPPOpts,
4171 FileManager &FileMgr)
4172 : ExistingLangOpts(ExistingLangOpts),
4173 ExistingTargetOpts(ExistingTargetOpts),
4174 ExistingPPOpts(ExistingPPOpts),
4175 FileMgr(FileMgr)
4176 {
4177 }
4178
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004179 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4180 bool AllowCompatibleDifferences) override {
4181 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4182 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004183 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004184 bool ReadTargetOptions(const TargetOptions &TargetOpts,
4185 bool Complain) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004186 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004187 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004188 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4189 bool Complain,
4190 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004191 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004192 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004193 }
4194 };
4195}
4196
4197bool ASTReader::readASTFileControlBlock(StringRef Filename,
4198 FileManager &FileMgr,
4199 ASTReaderListener &Listener) {
4200 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004201 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004202 if (!Buffer) {
4203 return true;
4204 }
4205
4206 // Initialize the stream
4207 llvm::BitstreamReader StreamFile;
Benjamin Kramera8857962014-10-26 22:44:13 +00004208 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
4209 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004210 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004211
4212 // Sniff for the signature.
4213 if (Stream.Read(8) != 'C' ||
4214 Stream.Read(8) != 'P' ||
4215 Stream.Read(8) != 'C' ||
4216 Stream.Read(8) != 'H') {
4217 return true;
4218 }
4219
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004220 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004221 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004222 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004223
4224 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004225 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004226 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004227 BitstreamCursor InputFilesCursor;
4228 if (NeedsInputFiles) {
4229 InputFilesCursor = Stream;
4230 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4231 return true;
4232
4233 // Read the abbreviations
4234 while (true) {
4235 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4236 unsigned Code = InputFilesCursor.ReadCode();
4237
4238 // We expect all abbrevs to be at the start of the block.
4239 if (Code != llvm::bitc::DEFINE_ABBREV) {
4240 InputFilesCursor.JumpToBit(Offset);
4241 break;
4242 }
4243 InputFilesCursor.ReadAbbrevRecord();
4244 }
4245 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004246
4247 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004248 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004249 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004250 while (1) {
4251 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4252 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4253 return false;
4254
4255 if (Entry.Kind != llvm::BitstreamEntry::Record)
4256 return true;
4257
Guy Benyei11169dd2012-12-18 14:30:41 +00004258 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004259 StringRef Blob;
4260 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004261 switch ((ControlRecordTypes)RecCode) {
4262 case METADATA: {
4263 if (Record[0] != VERSION_MAJOR)
4264 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004265
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004266 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004267 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004268
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004269 break;
4270 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004271 case MODULE_NAME:
4272 Listener.ReadModuleName(Blob);
4273 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004274 case MODULE_DIRECTORY:
4275 ModuleDir = Blob;
4276 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004277 case MODULE_MAP_FILE: {
4278 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004279 auto Path = ReadString(Record, Idx);
4280 ResolveImportedPath(Path, ModuleDir);
4281 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004282 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004283 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004284 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004285 if (ParseLanguageOptions(Record, false, Listener,
4286 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004287 return true;
4288 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004289
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004290 case TARGET_OPTIONS:
4291 if (ParseTargetOptions(Record, false, Listener))
4292 return true;
4293 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004294
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004295 case DIAGNOSTIC_OPTIONS:
4296 if (ParseDiagnosticOptions(Record, false, Listener))
4297 return true;
4298 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004299
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004300 case FILE_SYSTEM_OPTIONS:
4301 if (ParseFileSystemOptions(Record, false, Listener))
4302 return true;
4303 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004304
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004305 case HEADER_SEARCH_OPTIONS:
4306 if (ParseHeaderSearchOptions(Record, false, Listener))
4307 return true;
4308 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004309
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004310 case PREPROCESSOR_OPTIONS: {
4311 std::string IgnoredSuggestedPredefines;
4312 if (ParsePreprocessorOptions(Record, false, Listener,
4313 IgnoredSuggestedPredefines))
4314 return true;
4315 break;
4316 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004317
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004318 case INPUT_FILE_OFFSETS: {
4319 if (!NeedsInputFiles)
4320 break;
4321
4322 unsigned NumInputFiles = Record[0];
4323 unsigned NumUserFiles = Record[1];
4324 const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
4325 for (unsigned I = 0; I != NumInputFiles; ++I) {
4326 // Go find this input file.
4327 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004328
4329 if (isSystemFile && !NeedsSystemInputFiles)
4330 break; // the rest are system input files
4331
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004332 BitstreamCursor &Cursor = InputFilesCursor;
4333 SavedStreamPosition SavedPosition(Cursor);
4334 Cursor.JumpToBit(InputFileOffs[I]);
4335
4336 unsigned Code = Cursor.ReadCode();
4337 RecordData Record;
4338 StringRef Blob;
4339 bool shouldContinue = false;
4340 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4341 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004342 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004343 std::string Filename = Blob;
4344 ResolveImportedPath(Filename, ModuleDir);
4345 shouldContinue =
4346 Listener.visitInputFile(Filename, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004347 break;
4348 }
4349 if (!shouldContinue)
4350 break;
4351 }
4352 break;
4353 }
4354
Richard Smithd4b230b2014-10-27 23:01:16 +00004355 case IMPORTS: {
4356 if (!NeedsImports)
4357 break;
4358
4359 unsigned Idx = 0, N = Record.size();
4360 while (Idx < N) {
4361 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004362 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004363 std::string Filename = ReadString(Record, Idx);
4364 ResolveImportedPath(Filename, ModuleDir);
4365 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004366 }
4367 break;
4368 }
4369
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004370 default:
4371 // No other validation to perform.
4372 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004373 }
4374 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004375}
4376
4377
4378bool ASTReader::isAcceptableASTFile(StringRef Filename,
4379 FileManager &FileMgr,
4380 const LangOptions &LangOpts,
4381 const TargetOptions &TargetOpts,
4382 const PreprocessorOptions &PPOpts) {
4383 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
4384 return !readASTFileControlBlock(Filename, FileMgr, validator);
4385}
4386
Ben Langmuir2c9af442014-04-10 17:57:43 +00004387ASTReader::ASTReadResult
4388ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004389 // Enter the submodule block.
4390 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4391 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004392 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004393 }
4394
4395 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4396 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004397 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004398 RecordData Record;
4399 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004400 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4401
4402 switch (Entry.Kind) {
4403 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4404 case llvm::BitstreamEntry::Error:
4405 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004406 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004407 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004408 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004409 case llvm::BitstreamEntry::Record:
4410 // The interesting case.
4411 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004412 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004413
Guy Benyei11169dd2012-12-18 14:30:41 +00004414 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004415 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004416 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004417 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4418
4419 if ((Kind == SUBMODULE_METADATA) != First) {
4420 Error("submodule metadata record should be at beginning of block");
4421 return Failure;
4422 }
4423 First = false;
4424
4425 // Submodule information is only valid if we have a current module.
4426 // FIXME: Should we error on these cases?
4427 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4428 Kind != SUBMODULE_DEFINITION)
4429 continue;
4430
4431 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004432 default: // Default behavior: ignore.
4433 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004434
Richard Smith03478d92014-10-23 22:12:14 +00004435 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004436 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004437 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004438 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004439 }
Richard Smith03478d92014-10-23 22:12:14 +00004440
Chris Lattner0e6c9402013-01-20 02:38:54 +00004441 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004442 unsigned Idx = 0;
4443 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4444 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4445 bool IsFramework = Record[Idx++];
4446 bool IsExplicit = Record[Idx++];
4447 bool IsSystem = Record[Idx++];
4448 bool IsExternC = Record[Idx++];
4449 bool InferSubmodules = Record[Idx++];
4450 bool InferExplicitSubmodules = Record[Idx++];
4451 bool InferExportWildcard = Record[Idx++];
4452 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004453
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004454 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004455 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004456 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004457
Guy Benyei11169dd2012-12-18 14:30:41 +00004458 // Retrieve this (sub)module from the module map, creating it if
4459 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004460 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004461 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004462
4463 // FIXME: set the definition loc for CurrentModule, or call
4464 // ModMap.setInferredModuleAllowedBy()
4465
Guy Benyei11169dd2012-12-18 14:30:41 +00004466 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4467 if (GlobalIndex >= SubmodulesLoaded.size() ||
4468 SubmodulesLoaded[GlobalIndex]) {
4469 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004470 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004471 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004472
Douglas Gregor7029ce12013-03-19 00:28:20 +00004473 if (!ParentModule) {
4474 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4475 if (CurFile != F.File) {
4476 if (!Diags.isDiagnosticInFlight()) {
4477 Diag(diag::err_module_file_conflict)
4478 << CurrentModule->getTopLevelModuleName()
4479 << CurFile->getName()
4480 << F.File->getName();
4481 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004482 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004483 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004484 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004485
4486 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004487 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004488
Guy Benyei11169dd2012-12-18 14:30:41 +00004489 CurrentModule->IsFromModuleFile = true;
4490 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004491 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004492 CurrentModule->InferSubmodules = InferSubmodules;
4493 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4494 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004495 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004496 if (DeserializationListener)
4497 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4498
4499 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004500
Douglas Gregorfb912652013-03-20 21:10:35 +00004501 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004502 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004503 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004504 CurrentModule->UnresolvedConflicts.clear();
4505 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004506 break;
4507 }
4508
4509 case SUBMODULE_UMBRELLA_HEADER: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004510 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004511 if (!CurrentModule->getUmbrellaHeader())
4512 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4513 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004514 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4515 Error("mismatched umbrella headers in submodule");
4516 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004517 }
4518 }
4519 break;
4520 }
4521
Richard Smith202210b2014-10-24 20:23:01 +00004522 case SUBMODULE_HEADER:
4523 case SUBMODULE_EXCLUDED_HEADER:
4524 case SUBMODULE_PRIVATE_HEADER:
4525 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004526 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4527 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004528 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004529
Richard Smith202210b2014-10-24 20:23:01 +00004530 case SUBMODULE_TEXTUAL_HEADER:
4531 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4532 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4533 // them here.
4534 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004535
Guy Benyei11169dd2012-12-18 14:30:41 +00004536 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004537 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004538 break;
4539 }
4540
4541 case SUBMODULE_UMBRELLA_DIR: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004542 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004543 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004544 if (!CurrentModule->getUmbrellaDir())
4545 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4546 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004547 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4548 Error("mismatched umbrella directories in submodule");
4549 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004550 }
4551 }
4552 break;
4553 }
4554
4555 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004556 F.BaseSubmoduleID = getTotalNumSubmodules();
4557 F.LocalNumSubmodules = Record[0];
4558 unsigned LocalBaseSubmoduleID = Record[1];
4559 if (F.LocalNumSubmodules > 0) {
4560 // Introduce the global -> local mapping for submodules within this
4561 // module.
4562 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4563
4564 // Introduce the local -> global mapping for submodules within this
4565 // module.
4566 F.SubmoduleRemap.insertOrReplace(
4567 std::make_pair(LocalBaseSubmoduleID,
4568 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004569
Ben Langmuir52ca6782014-10-20 16:27:32 +00004570 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4571 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004572 break;
4573 }
4574
4575 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004576 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004577 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004578 Unresolved.File = &F;
4579 Unresolved.Mod = CurrentModule;
4580 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004581 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004582 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004583 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004584 }
4585 break;
4586 }
4587
4588 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004589 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004590 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004591 Unresolved.File = &F;
4592 Unresolved.Mod = CurrentModule;
4593 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004594 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004595 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004596 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004597 }
4598
4599 // Once we've loaded the set of exports, there's no reason to keep
4600 // the parsed, unresolved exports around.
4601 CurrentModule->UnresolvedExports.clear();
4602 break;
4603 }
4604 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004605 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004606 Context.getTargetInfo());
4607 break;
4608 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004609
4610 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004611 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004612 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004613 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004614
4615 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004616 CurrentModule->ConfigMacros.push_back(Blob.str());
4617 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004618
4619 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004620 UnresolvedModuleRef Unresolved;
4621 Unresolved.File = &F;
4622 Unresolved.Mod = CurrentModule;
4623 Unresolved.ID = Record[0];
4624 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4625 Unresolved.IsWildcard = false;
4626 Unresolved.String = Blob;
4627 UnresolvedModuleRefs.push_back(Unresolved);
4628 break;
4629 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004630 }
4631 }
4632}
4633
4634/// \brief Parse the record that corresponds to a LangOptions data
4635/// structure.
4636///
4637/// This routine parses the language options from the AST file and then gives
4638/// them to the AST listener if one is set.
4639///
4640/// \returns true if the listener deems the file unacceptable, false otherwise.
4641bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4642 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004643 ASTReaderListener &Listener,
4644 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004645 LangOptions LangOpts;
4646 unsigned Idx = 0;
4647#define LANGOPT(Name, Bits, Default, Description) \
4648 LangOpts.Name = Record[Idx++];
4649#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4650 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4651#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004652#define SANITIZER(NAME, ID) \
4653 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004654#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004655
4656 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4657 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4658 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4659
4660 unsigned Length = Record[Idx++];
4661 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4662 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004663
4664 Idx += Length;
4665
4666 // Comment options.
4667 for (unsigned N = Record[Idx++]; N; --N) {
4668 LangOpts.CommentOpts.BlockCommandNames.push_back(
4669 ReadString(Record, Idx));
4670 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004671 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004672
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004673 return Listener.ReadLanguageOptions(LangOpts, Complain,
4674 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004675}
4676
4677bool ASTReader::ParseTargetOptions(const RecordData &Record,
4678 bool Complain,
4679 ASTReaderListener &Listener) {
4680 unsigned Idx = 0;
4681 TargetOptions TargetOpts;
4682 TargetOpts.Triple = ReadString(Record, Idx);
4683 TargetOpts.CPU = ReadString(Record, Idx);
4684 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004685 for (unsigned N = Record[Idx++]; N; --N) {
4686 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4687 }
4688 for (unsigned N = Record[Idx++]; N; --N) {
4689 TargetOpts.Features.push_back(ReadString(Record, Idx));
4690 }
4691
4692 return Listener.ReadTargetOptions(TargetOpts, Complain);
4693}
4694
4695bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4696 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004697 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004698 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004699#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004700#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004701 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004702#include "clang/Basic/DiagnosticOptions.def"
4703
Richard Smith3be1cb22014-08-07 00:24:21 +00004704 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004705 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004706 for (unsigned N = Record[Idx++]; N; --N)
4707 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004708
4709 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4710}
4711
4712bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4713 ASTReaderListener &Listener) {
4714 FileSystemOptions FSOpts;
4715 unsigned Idx = 0;
4716 FSOpts.WorkingDir = ReadString(Record, Idx);
4717 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4718}
4719
4720bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4721 bool Complain,
4722 ASTReaderListener &Listener) {
4723 HeaderSearchOptions HSOpts;
4724 unsigned Idx = 0;
4725 HSOpts.Sysroot = ReadString(Record, Idx);
4726
4727 // Include entries.
4728 for (unsigned N = Record[Idx++]; N; --N) {
4729 std::string Path = ReadString(Record, Idx);
4730 frontend::IncludeDirGroup Group
4731 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004732 bool IsFramework = Record[Idx++];
4733 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004734 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004735 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004736 }
4737
4738 // System header prefixes.
4739 for (unsigned N = Record[Idx++]; N; --N) {
4740 std::string Prefix = ReadString(Record, Idx);
4741 bool IsSystemHeader = Record[Idx++];
4742 HSOpts.SystemHeaderPrefixes.push_back(
4743 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4744 }
4745
4746 HSOpts.ResourceDir = ReadString(Record, Idx);
4747 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004748 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004749 HSOpts.DisableModuleHash = Record[Idx++];
4750 HSOpts.UseBuiltinIncludes = Record[Idx++];
4751 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4752 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4753 HSOpts.UseLibcxx = Record[Idx++];
4754
4755 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4756}
4757
4758bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4759 bool Complain,
4760 ASTReaderListener &Listener,
4761 std::string &SuggestedPredefines) {
4762 PreprocessorOptions PPOpts;
4763 unsigned Idx = 0;
4764
4765 // Macro definitions/undefs
4766 for (unsigned N = Record[Idx++]; N; --N) {
4767 std::string Macro = ReadString(Record, Idx);
4768 bool IsUndef = Record[Idx++];
4769 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4770 }
4771
4772 // Includes
4773 for (unsigned N = Record[Idx++]; N; --N) {
4774 PPOpts.Includes.push_back(ReadString(Record, Idx));
4775 }
4776
4777 // Macro Includes
4778 for (unsigned N = Record[Idx++]; N; --N) {
4779 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4780 }
4781
4782 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004783 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004784 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4785 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4786 PPOpts.ObjCXXARCStandardLibrary =
4787 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4788 SuggestedPredefines.clear();
4789 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4790 SuggestedPredefines);
4791}
4792
4793std::pair<ModuleFile *, unsigned>
4794ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4795 GlobalPreprocessedEntityMapType::iterator
4796 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4797 assert(I != GlobalPreprocessedEntityMap.end() &&
4798 "Corrupted global preprocessed entity map");
4799 ModuleFile *M = I->second;
4800 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4801 return std::make_pair(M, LocalIndex);
4802}
4803
4804std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4805ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4806 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4807 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4808 Mod.NumPreprocessedEntities);
4809
4810 return std::make_pair(PreprocessingRecord::iterator(),
4811 PreprocessingRecord::iterator());
4812}
4813
4814std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4815ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4816 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4817 ModuleDeclIterator(this, &Mod,
4818 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4819}
4820
4821PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4822 PreprocessedEntityID PPID = Index+1;
4823 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4824 ModuleFile &M = *PPInfo.first;
4825 unsigned LocalIndex = PPInfo.second;
4826 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4827
Guy Benyei11169dd2012-12-18 14:30:41 +00004828 if (!PP.getPreprocessingRecord()) {
4829 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004830 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004831 }
4832
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004833 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4834 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4835
4836 llvm::BitstreamEntry Entry =
4837 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4838 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004839 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004840
Guy Benyei11169dd2012-12-18 14:30:41 +00004841 // Read the record.
4842 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4843 ReadSourceLocation(M, PPOffs.End));
4844 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004845 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004846 RecordData Record;
4847 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004848 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4849 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004850 switch (RecType) {
4851 case PPD_MACRO_EXPANSION: {
4852 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004853 IdentifierInfo *Name = nullptr;
4854 MacroDefinition *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004855 if (isBuiltin)
4856 Name = getLocalIdentifier(M, Record[1]);
4857 else {
4858 PreprocessedEntityID
4859 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4860 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4861 }
4862
4863 MacroExpansion *ME;
4864 if (isBuiltin)
4865 ME = new (PPRec) MacroExpansion(Name, Range);
4866 else
4867 ME = new (PPRec) MacroExpansion(Def, Range);
4868
4869 return ME;
4870 }
4871
4872 case PPD_MACRO_DEFINITION: {
4873 // Decode the identifier info and then check again; if the macro is
4874 // still defined and associated with the identifier,
4875 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4876 MacroDefinition *MD
4877 = new (PPRec) MacroDefinition(II, Range);
4878
4879 if (DeserializationListener)
4880 DeserializationListener->MacroDefinitionRead(PPID, MD);
4881
4882 return MD;
4883 }
4884
4885 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004886 const char *FullFileNameStart = Blob.data() + Record[0];
4887 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004888 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004889 if (!FullFileName.empty())
4890 File = PP.getFileManager().getFile(FullFileName);
4891
4892 // FIXME: Stable encoding
4893 InclusionDirective::InclusionKind Kind
4894 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4895 InclusionDirective *ID
4896 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004897 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004898 Record[1], Record[3],
4899 File,
4900 Range);
4901 return ID;
4902 }
4903 }
4904
4905 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4906}
4907
4908/// \brief \arg SLocMapI points at a chunk of a module that contains no
4909/// preprocessed entities or the entities it contains are not the ones we are
4910/// looking for. Find the next module that contains entities and return the ID
4911/// of the first entry.
4912PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4913 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4914 ++SLocMapI;
4915 for (GlobalSLocOffsetMapType::const_iterator
4916 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4917 ModuleFile &M = *SLocMapI->second;
4918 if (M.NumPreprocessedEntities)
4919 return M.BasePreprocessedEntityID;
4920 }
4921
4922 return getTotalNumPreprocessedEntities();
4923}
4924
4925namespace {
4926
4927template <unsigned PPEntityOffset::*PPLoc>
4928struct PPEntityComp {
4929 const ASTReader &Reader;
4930 ModuleFile &M;
4931
4932 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4933
4934 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4935 SourceLocation LHS = getLoc(L);
4936 SourceLocation RHS = getLoc(R);
4937 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4938 }
4939
4940 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4941 SourceLocation LHS = getLoc(L);
4942 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4943 }
4944
4945 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4946 SourceLocation RHS = getLoc(R);
4947 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4948 }
4949
4950 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4951 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4952 }
4953};
4954
4955}
4956
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004957PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4958 bool EndsAfter) const {
4959 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004960 return getTotalNumPreprocessedEntities();
4961
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004962 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4963 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004964 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4965 "Corrupted global sloc offset map");
4966
4967 if (SLocMapI->second->NumPreprocessedEntities == 0)
4968 return findNextPreprocessedEntity(SLocMapI);
4969
4970 ModuleFile &M = *SLocMapI->second;
4971 typedef const PPEntityOffset *pp_iterator;
4972 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4973 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4974
4975 size_t Count = M.NumPreprocessedEntities;
4976 size_t Half;
4977 pp_iterator First = pp_begin;
4978 pp_iterator PPI;
4979
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004980 if (EndsAfter) {
4981 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4982 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4983 } else {
4984 // Do a binary search manually instead of using std::lower_bound because
4985 // The end locations of entities may be unordered (when a macro expansion
4986 // is inside another macro argument), but for this case it is not important
4987 // whether we get the first macro expansion or its containing macro.
4988 while (Count > 0) {
4989 Half = Count / 2;
4990 PPI = First;
4991 std::advance(PPI, Half);
4992 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4993 Loc)) {
4994 First = PPI;
4995 ++First;
4996 Count = Count - Half - 1;
4997 } else
4998 Count = Half;
4999 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005000 }
5001
5002 if (PPI == pp_end)
5003 return findNextPreprocessedEntity(SLocMapI);
5004
5005 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5006}
5007
Guy Benyei11169dd2012-12-18 14:30:41 +00005008/// \brief Returns a pair of [Begin, End) indices of preallocated
5009/// preprocessed entities that \arg Range encompasses.
5010std::pair<unsigned, unsigned>
5011 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5012 if (Range.isInvalid())
5013 return std::make_pair(0,0);
5014 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5015
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005016 PreprocessedEntityID BeginID =
5017 findPreprocessedEntity(Range.getBegin(), false);
5018 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005019 return std::make_pair(BeginID, EndID);
5020}
5021
5022/// \brief Optionally returns true or false if the preallocated preprocessed
5023/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005024Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005025 FileID FID) {
5026 if (FID.isInvalid())
5027 return false;
5028
5029 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5030 ModuleFile &M = *PPInfo.first;
5031 unsigned LocalIndex = PPInfo.second;
5032 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5033
5034 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
5035 if (Loc.isInvalid())
5036 return false;
5037
5038 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5039 return true;
5040 else
5041 return false;
5042}
5043
5044namespace {
5045 /// \brief Visitor used to search for information about a header file.
5046 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005047 const FileEntry *FE;
5048
David Blaikie05785d12013-02-20 22:23:23 +00005049 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005050
5051 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005052 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5053 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00005054
5055 static bool visit(ModuleFile &M, void *UserData) {
5056 HeaderFileInfoVisitor *This
5057 = static_cast<HeaderFileInfoVisitor *>(UserData);
5058
Guy Benyei11169dd2012-12-18 14:30:41 +00005059 HeaderFileInfoLookupTable *Table
5060 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5061 if (!Table)
5062 return false;
5063
5064 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00005065 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005066 if (Pos == Table->end())
5067 return false;
5068
5069 This->HFI = *Pos;
5070 return true;
5071 }
5072
David Blaikie05785d12013-02-20 22:23:23 +00005073 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005074 };
5075}
5076
5077HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005078 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005079 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005080 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005081 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005082
5083 return HeaderFileInfo();
5084}
5085
5086void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5087 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005088 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005089 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5090 ModuleFile &F = *(*I);
5091 unsigned Idx = 0;
5092 DiagStates.clear();
5093 assert(!Diag.DiagStates.empty());
5094 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5095 while (Idx < F.PragmaDiagMappings.size()) {
5096 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5097 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5098 if (DiagStateID != 0) {
5099 Diag.DiagStatePoints.push_back(
5100 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5101 FullSourceLoc(Loc, SourceMgr)));
5102 continue;
5103 }
5104
5105 assert(DiagStateID == 0);
5106 // A new DiagState was created here.
5107 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5108 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5109 DiagStates.push_back(NewState);
5110 Diag.DiagStatePoints.push_back(
5111 DiagnosticsEngine::DiagStatePoint(NewState,
5112 FullSourceLoc(Loc, SourceMgr)));
5113 while (1) {
5114 assert(Idx < F.PragmaDiagMappings.size() &&
5115 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5116 if (Idx >= F.PragmaDiagMappings.size()) {
5117 break; // Something is messed up but at least avoid infinite loop in
5118 // release build.
5119 }
5120 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5121 if (DiagID == (unsigned)-1) {
5122 break; // no more diag/map pairs for this location.
5123 }
Alp Tokerc726c362014-06-10 09:31:37 +00005124 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5125 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5126 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005127 }
5128 }
5129 }
5130}
5131
5132/// \brief Get the correct cursor and offset for loading a type.
5133ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5134 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5135 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5136 ModuleFile *M = I->second;
5137 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5138}
5139
5140/// \brief Read and return the type with the given index..
5141///
5142/// The index is the type ID, shifted and minus the number of predefs. This
5143/// routine actually reads the record corresponding to the type at the given
5144/// location. It is a helper routine for GetType, which deals with reading type
5145/// IDs.
5146QualType ASTReader::readTypeRecord(unsigned Index) {
5147 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005148 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005149
5150 // Keep track of where we are in the stream, then jump back there
5151 // after reading this type.
5152 SavedStreamPosition SavedPosition(DeclsCursor);
5153
5154 ReadingKindTracker ReadingKind(Read_Type, *this);
5155
5156 // Note that we are loading a type record.
5157 Deserializing AType(this);
5158
5159 unsigned Idx = 0;
5160 DeclsCursor.JumpToBit(Loc.Offset);
5161 RecordData Record;
5162 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005163 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005164 case TYPE_EXT_QUAL: {
5165 if (Record.size() != 2) {
5166 Error("Incorrect encoding of extended qualifier type");
5167 return QualType();
5168 }
5169 QualType Base = readType(*Loc.F, Record, Idx);
5170 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5171 return Context.getQualifiedType(Base, Quals);
5172 }
5173
5174 case TYPE_COMPLEX: {
5175 if (Record.size() != 1) {
5176 Error("Incorrect encoding of complex type");
5177 return QualType();
5178 }
5179 QualType ElemType = readType(*Loc.F, Record, Idx);
5180 return Context.getComplexType(ElemType);
5181 }
5182
5183 case TYPE_POINTER: {
5184 if (Record.size() != 1) {
5185 Error("Incorrect encoding of pointer type");
5186 return QualType();
5187 }
5188 QualType PointeeType = readType(*Loc.F, Record, Idx);
5189 return Context.getPointerType(PointeeType);
5190 }
5191
Reid Kleckner8a365022013-06-24 17:51:48 +00005192 case TYPE_DECAYED: {
5193 if (Record.size() != 1) {
5194 Error("Incorrect encoding of decayed type");
5195 return QualType();
5196 }
5197 QualType OriginalType = readType(*Loc.F, Record, Idx);
5198 QualType DT = Context.getAdjustedParameterType(OriginalType);
5199 if (!isa<DecayedType>(DT))
5200 Error("Decayed type does not decay");
5201 return DT;
5202 }
5203
Reid Kleckner0503a872013-12-05 01:23:43 +00005204 case TYPE_ADJUSTED: {
5205 if (Record.size() != 2) {
5206 Error("Incorrect encoding of adjusted type");
5207 return QualType();
5208 }
5209 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5210 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5211 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5212 }
5213
Guy Benyei11169dd2012-12-18 14:30:41 +00005214 case TYPE_BLOCK_POINTER: {
5215 if (Record.size() != 1) {
5216 Error("Incorrect encoding of block pointer type");
5217 return QualType();
5218 }
5219 QualType PointeeType = readType(*Loc.F, Record, Idx);
5220 return Context.getBlockPointerType(PointeeType);
5221 }
5222
5223 case TYPE_LVALUE_REFERENCE: {
5224 if (Record.size() != 2) {
5225 Error("Incorrect encoding of lvalue reference type");
5226 return QualType();
5227 }
5228 QualType PointeeType = readType(*Loc.F, Record, Idx);
5229 return Context.getLValueReferenceType(PointeeType, Record[1]);
5230 }
5231
5232 case TYPE_RVALUE_REFERENCE: {
5233 if (Record.size() != 1) {
5234 Error("Incorrect encoding of rvalue reference type");
5235 return QualType();
5236 }
5237 QualType PointeeType = readType(*Loc.F, Record, Idx);
5238 return Context.getRValueReferenceType(PointeeType);
5239 }
5240
5241 case TYPE_MEMBER_POINTER: {
5242 if (Record.size() != 2) {
5243 Error("Incorrect encoding of member pointer type");
5244 return QualType();
5245 }
5246 QualType PointeeType = readType(*Loc.F, Record, Idx);
5247 QualType ClassType = readType(*Loc.F, Record, Idx);
5248 if (PointeeType.isNull() || ClassType.isNull())
5249 return QualType();
5250
5251 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5252 }
5253
5254 case TYPE_CONSTANT_ARRAY: {
5255 QualType ElementType = readType(*Loc.F, Record, Idx);
5256 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5257 unsigned IndexTypeQuals = Record[2];
5258 unsigned Idx = 3;
5259 llvm::APInt Size = ReadAPInt(Record, Idx);
5260 return Context.getConstantArrayType(ElementType, Size,
5261 ASM, IndexTypeQuals);
5262 }
5263
5264 case TYPE_INCOMPLETE_ARRAY: {
5265 QualType ElementType = readType(*Loc.F, Record, Idx);
5266 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5267 unsigned IndexTypeQuals = Record[2];
5268 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5269 }
5270
5271 case TYPE_VARIABLE_ARRAY: {
5272 QualType ElementType = readType(*Loc.F, Record, Idx);
5273 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5274 unsigned IndexTypeQuals = Record[2];
5275 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5276 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5277 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5278 ASM, IndexTypeQuals,
5279 SourceRange(LBLoc, RBLoc));
5280 }
5281
5282 case TYPE_VECTOR: {
5283 if (Record.size() != 3) {
5284 Error("incorrect encoding of vector type in AST file");
5285 return QualType();
5286 }
5287
5288 QualType ElementType = readType(*Loc.F, Record, Idx);
5289 unsigned NumElements = Record[1];
5290 unsigned VecKind = Record[2];
5291 return Context.getVectorType(ElementType, NumElements,
5292 (VectorType::VectorKind)VecKind);
5293 }
5294
5295 case TYPE_EXT_VECTOR: {
5296 if (Record.size() != 3) {
5297 Error("incorrect encoding of extended vector type in AST file");
5298 return QualType();
5299 }
5300
5301 QualType ElementType = readType(*Loc.F, Record, Idx);
5302 unsigned NumElements = Record[1];
5303 return Context.getExtVectorType(ElementType, NumElements);
5304 }
5305
5306 case TYPE_FUNCTION_NO_PROTO: {
5307 if (Record.size() != 6) {
5308 Error("incorrect encoding of no-proto function type");
5309 return QualType();
5310 }
5311 QualType ResultType = readType(*Loc.F, Record, Idx);
5312 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5313 (CallingConv)Record[4], Record[5]);
5314 return Context.getFunctionNoProtoType(ResultType, Info);
5315 }
5316
5317 case TYPE_FUNCTION_PROTO: {
5318 QualType ResultType = readType(*Loc.F, Record, Idx);
5319
5320 FunctionProtoType::ExtProtoInfo EPI;
5321 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5322 /*hasregparm*/ Record[2],
5323 /*regparm*/ Record[3],
5324 static_cast<CallingConv>(Record[4]),
5325 /*produces*/ Record[5]);
5326
5327 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005328
5329 EPI.Variadic = Record[Idx++];
5330 EPI.HasTrailingReturn = Record[Idx++];
5331 EPI.TypeQuals = Record[Idx++];
5332 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005333 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005334 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005335
5336 unsigned NumParams = Record[Idx++];
5337 SmallVector<QualType, 16> ParamTypes;
5338 for (unsigned I = 0; I != NumParams; ++I)
5339 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5340
Jordan Rose5c382722013-03-08 21:51:21 +00005341 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005342 }
5343
5344 case TYPE_UNRESOLVED_USING: {
5345 unsigned Idx = 0;
5346 return Context.getTypeDeclType(
5347 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5348 }
5349
5350 case TYPE_TYPEDEF: {
5351 if (Record.size() != 2) {
5352 Error("incorrect encoding of typedef type");
5353 return QualType();
5354 }
5355 unsigned Idx = 0;
5356 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5357 QualType Canonical = readType(*Loc.F, Record, Idx);
5358 if (!Canonical.isNull())
5359 Canonical = Context.getCanonicalType(Canonical);
5360 return Context.getTypedefType(Decl, Canonical);
5361 }
5362
5363 case TYPE_TYPEOF_EXPR:
5364 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5365
5366 case TYPE_TYPEOF: {
5367 if (Record.size() != 1) {
5368 Error("incorrect encoding of typeof(type) in AST file");
5369 return QualType();
5370 }
5371 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5372 return Context.getTypeOfType(UnderlyingType);
5373 }
5374
5375 case TYPE_DECLTYPE: {
5376 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5377 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5378 }
5379
5380 case TYPE_UNARY_TRANSFORM: {
5381 QualType BaseType = readType(*Loc.F, Record, Idx);
5382 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5383 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5384 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5385 }
5386
Richard Smith74aeef52013-04-26 16:15:35 +00005387 case TYPE_AUTO: {
5388 QualType Deduced = readType(*Loc.F, Record, Idx);
5389 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005390 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005391 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005392 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005393
5394 case TYPE_RECORD: {
5395 if (Record.size() != 2) {
5396 Error("incorrect encoding of record type");
5397 return QualType();
5398 }
5399 unsigned Idx = 0;
5400 bool IsDependent = Record[Idx++];
5401 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5402 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5403 QualType T = Context.getRecordType(RD);
5404 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5405 return T;
5406 }
5407
5408 case TYPE_ENUM: {
5409 if (Record.size() != 2) {
5410 Error("incorrect encoding of enum type");
5411 return QualType();
5412 }
5413 unsigned Idx = 0;
5414 bool IsDependent = Record[Idx++];
5415 QualType T
5416 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5417 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5418 return T;
5419 }
5420
5421 case TYPE_ATTRIBUTED: {
5422 if (Record.size() != 3) {
5423 Error("incorrect encoding of attributed type");
5424 return QualType();
5425 }
5426 QualType modifiedType = readType(*Loc.F, Record, Idx);
5427 QualType equivalentType = readType(*Loc.F, Record, Idx);
5428 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5429 return Context.getAttributedType(kind, modifiedType, equivalentType);
5430 }
5431
5432 case TYPE_PAREN: {
5433 if (Record.size() != 1) {
5434 Error("incorrect encoding of paren type");
5435 return QualType();
5436 }
5437 QualType InnerType = readType(*Loc.F, Record, Idx);
5438 return Context.getParenType(InnerType);
5439 }
5440
5441 case TYPE_PACK_EXPANSION: {
5442 if (Record.size() != 2) {
5443 Error("incorrect encoding of pack expansion type");
5444 return QualType();
5445 }
5446 QualType Pattern = readType(*Loc.F, Record, Idx);
5447 if (Pattern.isNull())
5448 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005449 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005450 if (Record[1])
5451 NumExpansions = Record[1] - 1;
5452 return Context.getPackExpansionType(Pattern, NumExpansions);
5453 }
5454
5455 case TYPE_ELABORATED: {
5456 unsigned Idx = 0;
5457 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5458 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5459 QualType NamedType = readType(*Loc.F, Record, Idx);
5460 return Context.getElaboratedType(Keyword, NNS, NamedType);
5461 }
5462
5463 case TYPE_OBJC_INTERFACE: {
5464 unsigned Idx = 0;
5465 ObjCInterfaceDecl *ItfD
5466 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5467 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5468 }
5469
5470 case TYPE_OBJC_OBJECT: {
5471 unsigned Idx = 0;
5472 QualType Base = readType(*Loc.F, Record, Idx);
5473 unsigned NumProtos = Record[Idx++];
5474 SmallVector<ObjCProtocolDecl*, 4> Protos;
5475 for (unsigned I = 0; I != NumProtos; ++I)
5476 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5477 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5478 }
5479
5480 case TYPE_OBJC_OBJECT_POINTER: {
5481 unsigned Idx = 0;
5482 QualType Pointee = readType(*Loc.F, Record, Idx);
5483 return Context.getObjCObjectPointerType(Pointee);
5484 }
5485
5486 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5487 unsigned Idx = 0;
5488 QualType Parm = readType(*Loc.F, Record, Idx);
5489 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005490 return Context.getSubstTemplateTypeParmType(
5491 cast<TemplateTypeParmType>(Parm),
5492 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005493 }
5494
5495 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5496 unsigned Idx = 0;
5497 QualType Parm = readType(*Loc.F, Record, Idx);
5498 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5499 return Context.getSubstTemplateTypeParmPackType(
5500 cast<TemplateTypeParmType>(Parm),
5501 ArgPack);
5502 }
5503
5504 case TYPE_INJECTED_CLASS_NAME: {
5505 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5506 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5507 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5508 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005509 const Type *T = nullptr;
5510 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5511 if (const Type *Existing = DI->getTypeForDecl()) {
5512 T = Existing;
5513 break;
5514 }
5515 }
5516 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005517 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005518 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5519 DI->setTypeForDecl(T);
5520 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005521 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005522 }
5523
5524 case TYPE_TEMPLATE_TYPE_PARM: {
5525 unsigned Idx = 0;
5526 unsigned Depth = Record[Idx++];
5527 unsigned Index = Record[Idx++];
5528 bool Pack = Record[Idx++];
5529 TemplateTypeParmDecl *D
5530 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5531 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5532 }
5533
5534 case TYPE_DEPENDENT_NAME: {
5535 unsigned Idx = 0;
5536 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5537 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5538 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5539 QualType Canon = readType(*Loc.F, Record, Idx);
5540 if (!Canon.isNull())
5541 Canon = Context.getCanonicalType(Canon);
5542 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5543 }
5544
5545 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5546 unsigned Idx = 0;
5547 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5548 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5549 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5550 unsigned NumArgs = Record[Idx++];
5551 SmallVector<TemplateArgument, 8> Args;
5552 Args.reserve(NumArgs);
5553 while (NumArgs--)
5554 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5555 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5556 Args.size(), Args.data());
5557 }
5558
5559 case TYPE_DEPENDENT_SIZED_ARRAY: {
5560 unsigned Idx = 0;
5561
5562 // ArrayType
5563 QualType ElementType = readType(*Loc.F, Record, Idx);
5564 ArrayType::ArraySizeModifier ASM
5565 = (ArrayType::ArraySizeModifier)Record[Idx++];
5566 unsigned IndexTypeQuals = Record[Idx++];
5567
5568 // DependentSizedArrayType
5569 Expr *NumElts = ReadExpr(*Loc.F);
5570 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5571
5572 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5573 IndexTypeQuals, Brackets);
5574 }
5575
5576 case TYPE_TEMPLATE_SPECIALIZATION: {
5577 unsigned Idx = 0;
5578 bool IsDependent = Record[Idx++];
5579 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5580 SmallVector<TemplateArgument, 8> Args;
5581 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5582 QualType Underlying = readType(*Loc.F, Record, Idx);
5583 QualType T;
5584 if (Underlying.isNull())
5585 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5586 Args.size());
5587 else
5588 T = Context.getTemplateSpecializationType(Name, Args.data(),
5589 Args.size(), Underlying);
5590 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5591 return T;
5592 }
5593
5594 case TYPE_ATOMIC: {
5595 if (Record.size() != 1) {
5596 Error("Incorrect encoding of atomic type");
5597 return QualType();
5598 }
5599 QualType ValueType = readType(*Loc.F, Record, Idx);
5600 return Context.getAtomicType(ValueType);
5601 }
5602 }
5603 llvm_unreachable("Invalid TypeCode!");
5604}
5605
Richard Smith564417a2014-03-20 21:47:22 +00005606void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5607 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005608 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005609 const RecordData &Record, unsigned &Idx) {
5610 ExceptionSpecificationType EST =
5611 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005612 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005613 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005614 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005615 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005616 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005617 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005618 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005619 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005620 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5621 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005622 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005623 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005624 }
5625}
5626
Guy Benyei11169dd2012-12-18 14:30:41 +00005627class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5628 ASTReader &Reader;
5629 ModuleFile &F;
5630 const ASTReader::RecordData &Record;
5631 unsigned &Idx;
5632
5633 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5634 unsigned &I) {
5635 return Reader.ReadSourceLocation(F, R, I);
5636 }
5637
5638 template<typename T>
5639 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5640 return Reader.ReadDeclAs<T>(F, Record, Idx);
5641 }
5642
5643public:
5644 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5645 const ASTReader::RecordData &Record, unsigned &Idx)
5646 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5647 { }
5648
5649 // We want compile-time assurance that we've enumerated all of
5650 // these, so unfortunately we have to declare them first, then
5651 // define them out-of-line.
5652#define ABSTRACT_TYPELOC(CLASS, PARENT)
5653#define TYPELOC(CLASS, PARENT) \
5654 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5655#include "clang/AST/TypeLocNodes.def"
5656
5657 void VisitFunctionTypeLoc(FunctionTypeLoc);
5658 void VisitArrayTypeLoc(ArrayTypeLoc);
5659};
5660
5661void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5662 // nothing to do
5663}
5664void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5665 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5666 if (TL.needsExtraLocalData()) {
5667 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5668 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5669 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5670 TL.setModeAttr(Record[Idx++]);
5671 }
5672}
5673void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5674 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5675}
5676void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5677 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5678}
Reid Kleckner8a365022013-06-24 17:51:48 +00005679void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5680 // nothing to do
5681}
Reid Kleckner0503a872013-12-05 01:23:43 +00005682void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5683 // nothing to do
5684}
Guy Benyei11169dd2012-12-18 14:30:41 +00005685void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5686 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5687}
5688void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5689 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5690}
5691void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5692 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5693}
5694void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5695 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5696 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5697}
5698void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5699 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5700 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5701 if (Record[Idx++])
5702 TL.setSizeExpr(Reader.ReadExpr(F));
5703 else
Craig Toppera13603a2014-05-22 05:54:18 +00005704 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005705}
5706void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5707 VisitArrayTypeLoc(TL);
5708}
5709void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5710 VisitArrayTypeLoc(TL);
5711}
5712void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5713 VisitArrayTypeLoc(TL);
5714}
5715void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5716 DependentSizedArrayTypeLoc TL) {
5717 VisitArrayTypeLoc(TL);
5718}
5719void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5720 DependentSizedExtVectorTypeLoc TL) {
5721 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5722}
5723void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5724 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5725}
5726void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5727 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5728}
5729void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5730 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5731 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5732 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5733 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005734 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5735 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005736 }
5737}
5738void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5739 VisitFunctionTypeLoc(TL);
5740}
5741void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5742 VisitFunctionTypeLoc(TL);
5743}
5744void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5745 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5746}
5747void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5748 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5749}
5750void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5751 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5752 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5753 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5754}
5755void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5756 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5757 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5758 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5759 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5760}
5761void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5762 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5763}
5764void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5765 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5766 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5767 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5768 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5769}
5770void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5771 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5772}
5773void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5774 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5775}
5776void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5777 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5778}
5779void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5780 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5781 if (TL.hasAttrOperand()) {
5782 SourceRange range;
5783 range.setBegin(ReadSourceLocation(Record, Idx));
5784 range.setEnd(ReadSourceLocation(Record, Idx));
5785 TL.setAttrOperandParensRange(range);
5786 }
5787 if (TL.hasAttrExprOperand()) {
5788 if (Record[Idx++])
5789 TL.setAttrExprOperand(Reader.ReadExpr(F));
5790 else
Craig Toppera13603a2014-05-22 05:54:18 +00005791 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005792 } else if (TL.hasAttrEnumOperand())
5793 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5794}
5795void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5796 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5797}
5798void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5799 SubstTemplateTypeParmTypeLoc TL) {
5800 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5801}
5802void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5803 SubstTemplateTypeParmPackTypeLoc TL) {
5804 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5805}
5806void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5807 TemplateSpecializationTypeLoc TL) {
5808 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5809 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5810 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5811 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5812 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5813 TL.setArgLocInfo(i,
5814 Reader.GetTemplateArgumentLocInfo(F,
5815 TL.getTypePtr()->getArg(i).getKind(),
5816 Record, Idx));
5817}
5818void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5819 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5820 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5821}
5822void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5823 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5824 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5825}
5826void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5827 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5828}
5829void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5830 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5831 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5832 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5833}
5834void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5835 DependentTemplateSpecializationTypeLoc TL) {
5836 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5837 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5838 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5839 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5840 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5841 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5842 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5843 TL.setArgLocInfo(I,
5844 Reader.GetTemplateArgumentLocInfo(F,
5845 TL.getTypePtr()->getArg(I).getKind(),
5846 Record, Idx));
5847}
5848void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5849 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5850}
5851void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5852 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5853}
5854void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5855 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5856 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5857 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5858 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5859 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5860}
5861void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5862 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5863}
5864void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5865 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5866 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5867 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5868}
5869
5870TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5871 const RecordData &Record,
5872 unsigned &Idx) {
5873 QualType InfoTy = readType(F, Record, Idx);
5874 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005875 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005876
5877 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5878 TypeLocReader TLR(*this, F, Record, Idx);
5879 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5880 TLR.Visit(TL);
5881 return TInfo;
5882}
5883
5884QualType ASTReader::GetType(TypeID ID) {
5885 unsigned FastQuals = ID & Qualifiers::FastMask;
5886 unsigned Index = ID >> Qualifiers::FastWidth;
5887
5888 if (Index < NUM_PREDEF_TYPE_IDS) {
5889 QualType T;
5890 switch ((PredefinedTypeIDs)Index) {
5891 case PREDEF_TYPE_NULL_ID: return QualType();
5892 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5893 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5894
5895 case PREDEF_TYPE_CHAR_U_ID:
5896 case PREDEF_TYPE_CHAR_S_ID:
5897 // FIXME: Check that the signedness of CharTy is correct!
5898 T = Context.CharTy;
5899 break;
5900
5901 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5902 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5903 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5904 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5905 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5906 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5907 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5908 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5909 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5910 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5911 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5912 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5913 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5914 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5915 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5916 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5917 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5918 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5919 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5920 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5921 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5922 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5923 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5924 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5925 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5926 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5927 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5928 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005929 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5930 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5931 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5932 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5933 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5934 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005935 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005936 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005937 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5938
5939 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5940 T = Context.getAutoRRefDeductType();
5941 break;
5942
5943 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5944 T = Context.ARCUnbridgedCastTy;
5945 break;
5946
5947 case PREDEF_TYPE_VA_LIST_TAG:
5948 T = Context.getVaListTagType();
5949 break;
5950
5951 case PREDEF_TYPE_BUILTIN_FN:
5952 T = Context.BuiltinFnTy;
5953 break;
5954 }
5955
5956 assert(!T.isNull() && "Unknown predefined type");
5957 return T.withFastQualifiers(FastQuals);
5958 }
5959
5960 Index -= NUM_PREDEF_TYPE_IDS;
5961 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5962 if (TypesLoaded[Index].isNull()) {
5963 TypesLoaded[Index] = readTypeRecord(Index);
5964 if (TypesLoaded[Index].isNull())
5965 return QualType();
5966
5967 TypesLoaded[Index]->setFromAST();
5968 if (DeserializationListener)
5969 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5970 TypesLoaded[Index]);
5971 }
5972
5973 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5974}
5975
5976QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5977 return GetType(getGlobalTypeID(F, LocalID));
5978}
5979
5980serialization::TypeID
5981ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5982 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5983 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5984
5985 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5986 return LocalID;
5987
5988 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5989 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5990 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5991
5992 unsigned GlobalIndex = LocalIndex + I->second;
5993 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5994}
5995
5996TemplateArgumentLocInfo
5997ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5998 TemplateArgument::ArgKind Kind,
5999 const RecordData &Record,
6000 unsigned &Index) {
6001 switch (Kind) {
6002 case TemplateArgument::Expression:
6003 return ReadExpr(F);
6004 case TemplateArgument::Type:
6005 return GetTypeSourceInfo(F, Record, Index);
6006 case TemplateArgument::Template: {
6007 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6008 Index);
6009 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6010 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6011 SourceLocation());
6012 }
6013 case TemplateArgument::TemplateExpansion: {
6014 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6015 Index);
6016 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6017 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6018 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6019 EllipsisLoc);
6020 }
6021 case TemplateArgument::Null:
6022 case TemplateArgument::Integral:
6023 case TemplateArgument::Declaration:
6024 case TemplateArgument::NullPtr:
6025 case TemplateArgument::Pack:
6026 // FIXME: Is this right?
6027 return TemplateArgumentLocInfo();
6028 }
6029 llvm_unreachable("unexpected template argument loc");
6030}
6031
6032TemplateArgumentLoc
6033ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6034 const RecordData &Record, unsigned &Index) {
6035 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6036
6037 if (Arg.getKind() == TemplateArgument::Expression) {
6038 if (Record[Index++]) // bool InfoHasSameExpr.
6039 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6040 }
6041 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6042 Record, Index));
6043}
6044
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006045const ASTTemplateArgumentListInfo*
6046ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6047 const RecordData &Record,
6048 unsigned &Index) {
6049 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6050 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6051 unsigned NumArgsAsWritten = Record[Index++];
6052 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6053 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6054 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6055 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6056}
6057
Guy Benyei11169dd2012-12-18 14:30:41 +00006058Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6059 return GetDecl(ID);
6060}
6061
Richard Smith053f6c62014-05-16 23:01:30 +00006062void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006063 if (NumCurrentElementsDeserializing) {
6064 // We arrange to not care about the complete redeclaration chain while we're
6065 // deserializing. Just remember that the AST has marked this one as complete
6066 // but that it's not actually complete yet, so we know we still need to
6067 // complete it later.
6068 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6069 return;
6070 }
6071
Richard Smith053f6c62014-05-16 23:01:30 +00006072 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6073
Richard Smith053f6c62014-05-16 23:01:30 +00006074 // If this is a named declaration, complete it by looking it up
6075 // within its context.
6076 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006077 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006078 // all mergeable entities within it.
6079 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6080 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6081 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
6082 auto *II = Name.getAsIdentifierInfo();
6083 if (isa<TranslationUnitDecl>(DC) && II) {
6084 // Outside of C++, we don't have a lookup table for the TU, so update
6085 // the identifier instead. In C++, either way should work fine.
6086 if (II->isOutOfDate())
6087 updateOutOfDateIdentifier(*II);
6088 } else
6089 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006090 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
6091 // FIXME: It'd be nice to do something a bit more targeted here.
6092 D->getDeclContext()->decls_begin();
Richard Smith053f6c62014-05-16 23:01:30 +00006093 }
6094 }
6095}
6096
Richard Smithcd45dbc2014-04-19 03:48:30 +00006097uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6098 const RecordData &Record,
6099 unsigned &Idx) {
6100 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6101 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006102 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006103 }
6104
Guy Benyei11169dd2012-12-18 14:30:41 +00006105 unsigned LocalID = Record[Idx++];
6106 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6107}
6108
6109CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6110 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006111 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006112 SavedStreamPosition SavedPosition(Cursor);
6113 Cursor.JumpToBit(Loc.Offset);
6114 ReadingKindTracker ReadingKind(Read_Decl, *this);
6115 RecordData Record;
6116 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006117 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006118 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006119 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006120 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006121 }
6122
6123 unsigned Idx = 0;
6124 unsigned NumBases = Record[Idx++];
6125 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6126 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6127 for (unsigned I = 0; I != NumBases; ++I)
6128 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6129 return Bases;
6130}
6131
6132serialization::DeclID
6133ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6134 if (LocalID < NUM_PREDEF_DECL_IDS)
6135 return LocalID;
6136
6137 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6138 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6139 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6140
6141 return LocalID + I->second;
6142}
6143
6144bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6145 ModuleFile &M) const {
6146 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6147 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6148 return &M == I->second;
6149}
6150
Douglas Gregor9f782892013-01-21 15:25:38 +00006151ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006152 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006153 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006154 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6155 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6156 return I->second;
6157}
6158
6159SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6160 if (ID < NUM_PREDEF_DECL_IDS)
6161 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006162
Guy Benyei11169dd2012-12-18 14:30:41 +00006163 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6164
6165 if (Index > DeclsLoaded.size()) {
6166 Error("declaration ID out-of-range for AST file");
6167 return SourceLocation();
6168 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006169
Guy Benyei11169dd2012-12-18 14:30:41 +00006170 if (Decl *D = DeclsLoaded[Index])
6171 return D->getLocation();
6172
6173 unsigned RawLocation = 0;
6174 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6175 return ReadSourceLocation(*Rec.F, RawLocation);
6176}
6177
Richard Smithcd45dbc2014-04-19 03:48:30 +00006178Decl *ASTReader::GetExistingDecl(DeclID ID) {
6179 if (ID < NUM_PREDEF_DECL_IDS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006180 switch ((PredefinedDeclIDs)ID) {
6181 case PREDEF_DECL_NULL_ID:
Craig Toppera13603a2014-05-22 05:54:18 +00006182 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006183
Guy Benyei11169dd2012-12-18 14:30:41 +00006184 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6185 return Context.getTranslationUnitDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006186
Guy Benyei11169dd2012-12-18 14:30:41 +00006187 case PREDEF_DECL_OBJC_ID_ID:
6188 return Context.getObjCIdDecl();
6189
6190 case PREDEF_DECL_OBJC_SEL_ID:
6191 return Context.getObjCSelDecl();
6192
6193 case PREDEF_DECL_OBJC_CLASS_ID:
6194 return Context.getObjCClassDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006195
Guy Benyei11169dd2012-12-18 14:30:41 +00006196 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6197 return Context.getObjCProtocolDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006198
Guy Benyei11169dd2012-12-18 14:30:41 +00006199 case PREDEF_DECL_INT_128_ID:
6200 return Context.getInt128Decl();
6201
6202 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6203 return Context.getUInt128Decl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006204
Guy Benyei11169dd2012-12-18 14:30:41 +00006205 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6206 return Context.getObjCInstanceTypeDecl();
6207
6208 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6209 return Context.getBuiltinVaListDecl();
6210 }
6211 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006212
Guy Benyei11169dd2012-12-18 14:30:41 +00006213 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6214
6215 if (Index >= DeclsLoaded.size()) {
6216 assert(0 && "declaration ID out-of-range for AST file");
6217 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006218 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006219 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006220
6221 return DeclsLoaded[Index];
6222}
6223
6224Decl *ASTReader::GetDecl(DeclID ID) {
6225 if (ID < NUM_PREDEF_DECL_IDS)
6226 return GetExistingDecl(ID);
6227
6228 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6229
6230 if (Index >= DeclsLoaded.size()) {
6231 assert(0 && "declaration ID out-of-range for AST file");
6232 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006233 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006234 }
6235
Guy Benyei11169dd2012-12-18 14:30:41 +00006236 if (!DeclsLoaded[Index]) {
6237 ReadDeclRecord(ID);
6238 if (DeserializationListener)
6239 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6240 }
6241
6242 return DeclsLoaded[Index];
6243}
6244
6245DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6246 DeclID GlobalID) {
6247 if (GlobalID < NUM_PREDEF_DECL_IDS)
6248 return GlobalID;
6249
6250 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6251 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6252 ModuleFile *Owner = I->second;
6253
6254 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6255 = M.GlobalToLocalDeclIDs.find(Owner);
6256 if (Pos == M.GlobalToLocalDeclIDs.end())
6257 return 0;
6258
6259 return GlobalID - Owner->BaseDeclID + Pos->second;
6260}
6261
6262serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6263 const RecordData &Record,
6264 unsigned &Idx) {
6265 if (Idx >= Record.size()) {
6266 Error("Corrupted AST file");
6267 return 0;
6268 }
6269
6270 return getGlobalDeclID(F, Record[Idx++]);
6271}
6272
6273/// \brief Resolve the offset of a statement into a statement.
6274///
6275/// This operation will read a new statement from the external
6276/// source each time it is called, and is meant to be used via a
6277/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6278Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6279 // Switch case IDs are per Decl.
6280 ClearSwitchCaseIDs();
6281
6282 // Offset here is a global offset across the entire chain.
6283 RecordLocation Loc = getLocalBitOffset(Offset);
6284 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6285 return ReadStmtFromStream(*Loc.F);
6286}
6287
6288namespace {
6289 class FindExternalLexicalDeclsVisitor {
6290 ASTReader &Reader;
6291 const DeclContext *DC;
6292 bool (*isKindWeWant)(Decl::Kind);
6293
6294 SmallVectorImpl<Decl*> &Decls;
6295 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6296
6297 public:
6298 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6299 bool (*isKindWeWant)(Decl::Kind),
6300 SmallVectorImpl<Decl*> &Decls)
6301 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6302 {
6303 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6304 PredefsVisited[I] = false;
6305 }
6306
6307 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6308 if (Preorder)
6309 return false;
6310
6311 FindExternalLexicalDeclsVisitor *This
6312 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6313
6314 ModuleFile::DeclContextInfosMap::iterator Info
6315 = M.DeclContextInfos.find(This->DC);
6316 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6317 return false;
6318
6319 // Load all of the declaration IDs
6320 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6321 *IDE = ID + Info->second.NumLexicalDecls;
6322 ID != IDE; ++ID) {
6323 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6324 continue;
6325
6326 // Don't add predefined declarations to the lexical context more
6327 // than once.
6328 if (ID->second < NUM_PREDEF_DECL_IDS) {
6329 if (This->PredefsVisited[ID->second])
6330 continue;
6331
6332 This->PredefsVisited[ID->second] = true;
6333 }
6334
6335 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6336 if (!This->DC->isDeclInLexicalTraversal(D))
6337 This->Decls.push_back(D);
6338 }
6339 }
6340
6341 return false;
6342 }
6343 };
6344}
6345
6346ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6347 bool (*isKindWeWant)(Decl::Kind),
6348 SmallVectorImpl<Decl*> &Decls) {
6349 // There might be lexical decls in multiple modules, for the TU at
6350 // least. Walk all of the modules in the order they were loaded.
6351 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6352 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6353 ++NumLexicalDeclContextsRead;
6354 return ELR_Success;
6355}
6356
6357namespace {
6358
6359class DeclIDComp {
6360 ASTReader &Reader;
6361 ModuleFile &Mod;
6362
6363public:
6364 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6365
6366 bool operator()(LocalDeclID L, LocalDeclID R) const {
6367 SourceLocation LHS = getLocation(L);
6368 SourceLocation RHS = getLocation(R);
6369 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6370 }
6371
6372 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6373 SourceLocation RHS = getLocation(R);
6374 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6375 }
6376
6377 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6378 SourceLocation LHS = getLocation(L);
6379 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6380 }
6381
6382 SourceLocation getLocation(LocalDeclID ID) const {
6383 return Reader.getSourceManager().getFileLoc(
6384 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6385 }
6386};
6387
6388}
6389
6390void ASTReader::FindFileRegionDecls(FileID File,
6391 unsigned Offset, unsigned Length,
6392 SmallVectorImpl<Decl *> &Decls) {
6393 SourceManager &SM = getSourceManager();
6394
6395 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6396 if (I == FileDeclIDs.end())
6397 return;
6398
6399 FileDeclsInfo &DInfo = I->second;
6400 if (DInfo.Decls.empty())
6401 return;
6402
6403 SourceLocation
6404 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6405 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6406
6407 DeclIDComp DIDComp(*this, *DInfo.Mod);
6408 ArrayRef<serialization::LocalDeclID>::iterator
6409 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6410 BeginLoc, DIDComp);
6411 if (BeginIt != DInfo.Decls.begin())
6412 --BeginIt;
6413
6414 // If we are pointing at a top-level decl inside an objc container, we need
6415 // to backtrack until we find it otherwise we will fail to report that the
6416 // region overlaps with an objc container.
6417 while (BeginIt != DInfo.Decls.begin() &&
6418 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6419 ->isTopLevelDeclInObjCContainer())
6420 --BeginIt;
6421
6422 ArrayRef<serialization::LocalDeclID>::iterator
6423 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6424 EndLoc, DIDComp);
6425 if (EndIt != DInfo.Decls.end())
6426 ++EndIt;
6427
6428 for (ArrayRef<serialization::LocalDeclID>::iterator
6429 DIt = BeginIt; DIt != EndIt; ++DIt)
6430 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6431}
6432
6433namespace {
6434 /// \brief ModuleFile visitor used to perform name lookup into a
6435 /// declaration context.
6436 class DeclContextNameLookupVisitor {
6437 ASTReader &Reader;
Richard Smith8c913ec2014-08-14 02:21:01 +00006438 ArrayRef<const DeclContext *> Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006439 DeclarationName Name;
6440 SmallVectorImpl<NamedDecl *> &Decls;
6441
6442 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006443 DeclContextNameLookupVisitor(ASTReader &Reader,
6444 ArrayRef<const DeclContext *> Contexts,
Guy Benyei11169dd2012-12-18 14:30:41 +00006445 DeclarationName Name,
6446 SmallVectorImpl<NamedDecl *> &Decls)
6447 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
6448
6449 static bool visit(ModuleFile &M, void *UserData) {
6450 DeclContextNameLookupVisitor *This
6451 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6452
6453 // Check whether we have any visible declaration information for
6454 // this context in this module.
6455 ModuleFile::DeclContextInfosMap::iterator Info;
6456 bool FoundInfo = false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006457 for (auto *DC : This->Contexts) {
6458 Info = M.DeclContextInfos.find(DC);
6459 if (Info != M.DeclContextInfos.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006460 Info->second.NameLookupTableData) {
6461 FoundInfo = true;
6462 break;
6463 }
6464 }
6465
6466 if (!FoundInfo)
6467 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006468
Guy Benyei11169dd2012-12-18 14:30:41 +00006469 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006470 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006471 Info->second.NameLookupTableData;
6472 ASTDeclContextNameLookupTable::iterator Pos
6473 = LookupTable->find(This->Name);
6474 if (Pos == LookupTable->end())
6475 return false;
6476
6477 bool FoundAnything = false;
6478 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6479 for (; Data.first != Data.second; ++Data.first) {
6480 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6481 if (!ND)
6482 continue;
6483
6484 if (ND->getDeclName() != This->Name) {
6485 // A name might be null because the decl's redeclarable part is
6486 // currently read before reading its name. The lookup is triggered by
6487 // building that decl (likely indirectly), and so it is later in the
6488 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006489 // FIXME: This should not happen; deserializing declarations should
6490 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006491 continue;
6492 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006493
Guy Benyei11169dd2012-12-18 14:30:41 +00006494 // Record this declaration.
6495 FoundAnything = true;
6496 This->Decls.push_back(ND);
6497 }
6498
6499 return FoundAnything;
6500 }
6501 };
6502}
6503
Douglas Gregor9f782892013-01-21 15:25:38 +00006504/// \brief Retrieve the "definitive" module file for the definition of the
6505/// given declaration context, if there is one.
6506///
6507/// The "definitive" module file is the only place where we need to look to
6508/// find information about the declarations within the given declaration
6509/// context. For example, C++ and Objective-C classes, C structs/unions, and
6510/// Objective-C protocols, categories, and extensions are all defined in a
6511/// single place in the source code, so they have definitive module files
6512/// associated with them. C++ namespaces, on the other hand, can have
6513/// definitions in multiple different module files.
6514///
6515/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6516/// NDEBUG checking.
6517static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6518 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006519 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6520 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006521
Craig Toppera13603a2014-05-22 05:54:18 +00006522 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006523}
6524
Richard Smith9ce12e32013-02-07 03:30:24 +00006525bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006526ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6527 DeclarationName Name) {
6528 assert(DC->hasExternalVisibleStorage() &&
6529 "DeclContext has no visible decls in storage");
6530 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006531 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006532
Richard Smith8c913ec2014-08-14 02:21:01 +00006533 Deserializing LookupResults(this);
6534
Guy Benyei11169dd2012-12-18 14:30:41 +00006535 SmallVector<NamedDecl *, 64> Decls;
Richard Smith8c913ec2014-08-14 02:21:01 +00006536
Guy Benyei11169dd2012-12-18 14:30:41 +00006537 // Compute the declaration contexts we need to look into. Multiple such
6538 // declaration contexts occur when two declaration contexts from disjoint
6539 // modules get merged, e.g., when two namespaces with the same name are
6540 // independently defined in separate modules.
6541 SmallVector<const DeclContext *, 2> Contexts;
6542 Contexts.push_back(DC);
Richard Smith8c913ec2014-08-14 02:21:01 +00006543
Guy Benyei11169dd2012-12-18 14:30:41 +00006544 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006545 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006546 if (Merged != MergedDecls.end()) {
6547 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6548 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6549 }
6550 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006551
6552 auto LookUpInContexts = [&](ArrayRef<const DeclContext*> Contexts) {
6553 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
6554
6555 // If we can definitively determine which module file to look into,
6556 // only look there. Otherwise, look in all module files.
6557 ModuleFile *Definitive;
6558 if (Contexts.size() == 1 &&
6559 (Definitive = getDefinitiveModuleFileFor(Contexts[0], *this))) {
6560 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6561 } else {
6562 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6563 }
6564 };
6565
6566 LookUpInContexts(Contexts);
6567
6568 // If this might be an implicit special member function, then also search
6569 // all merged definitions of the surrounding class. We need to search them
6570 // individually, because finding an entity in one of them doesn't imply that
6571 // we can't find a different entity in another one.
Richard Smithcd45dbc2014-04-19 03:48:30 +00006572 if (isa<CXXRecordDecl>(DC)) {
Richard Smith8c913ec2014-08-14 02:21:01 +00006573 auto Kind = Name.getNameKind();
6574 if (Kind == DeclarationName::CXXConstructorName ||
6575 Kind == DeclarationName::CXXDestructorName ||
6576 (Kind == DeclarationName::CXXOperatorName &&
6577 Name.getCXXOverloadedOperator() == OO_Equal)) {
6578 auto Merged = MergedLookups.find(DC);
Richard Smithe0612472014-11-21 05:16:13 +00006579 if (Merged != MergedLookups.end()) {
6580 for (unsigned I = 0; I != Merged->second.size(); ++I) {
6581 LookUpInContexts(Merged->second[I]);
6582 // We might have just added some more merged lookups. If so, our
6583 // iterator is now invalid, so grab a fresh one before continuing.
6584 Merged = MergedLookups.find(DC);
6585 }
6586 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006587 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006588 }
6589
Guy Benyei11169dd2012-12-18 14:30:41 +00006590 ++NumVisibleDeclContextsRead;
6591 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006592 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006593}
6594
6595namespace {
6596 /// \brief ModuleFile visitor used to retrieve all visible names in a
6597 /// declaration context.
6598 class DeclContextAllNamesVisitor {
6599 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006600 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006601 DeclsMap &Decls;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006602 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006603
6604 public:
6605 DeclContextAllNamesVisitor(ASTReader &Reader,
6606 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006607 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006608 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006609
6610 static bool visit(ModuleFile &M, void *UserData) {
6611 DeclContextAllNamesVisitor *This
6612 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6613
6614 // Check whether we have any visible declaration information for
6615 // this context in this module.
6616 ModuleFile::DeclContextInfosMap::iterator Info;
6617 bool FoundInfo = false;
6618 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6619 Info = M.DeclContextInfos.find(This->Contexts[I]);
6620 if (Info != M.DeclContextInfos.end() &&
6621 Info->second.NameLookupTableData) {
6622 FoundInfo = true;
6623 break;
6624 }
6625 }
6626
6627 if (!FoundInfo)
6628 return false;
6629
Richard Smith52e3fba2014-03-11 07:17:35 +00006630 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006631 Info->second.NameLookupTableData;
6632 bool FoundAnything = false;
6633 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006634 I = LookupTable->data_begin(), E = LookupTable->data_end();
6635 I != E;
6636 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006637 ASTDeclContextNameLookupTrait::data_type Data = *I;
6638 for (; Data.first != Data.second; ++Data.first) {
6639 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6640 *Data.first);
6641 if (!ND)
6642 continue;
6643
6644 // Record this declaration.
6645 FoundAnything = true;
6646 This->Decls[ND->getDeclName()].push_back(ND);
6647 }
6648 }
6649
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006650 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006651 }
6652 };
6653}
6654
6655void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6656 if (!DC->hasExternalVisibleStorage())
6657 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006658 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006659
6660 // Compute the declaration contexts we need to look into. Multiple such
6661 // declaration contexts occur when two declaration contexts from disjoint
6662 // modules get merged, e.g., when two namespaces with the same name are
6663 // independently defined in separate modules.
6664 SmallVector<const DeclContext *, 2> Contexts;
6665 Contexts.push_back(DC);
6666
6667 if (DC->isNamespace()) {
6668 MergedDeclsMap::iterator Merged
6669 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6670 if (Merged != MergedDecls.end()) {
6671 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6672 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6673 }
6674 }
6675
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006676 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6677 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006678 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6679 ++NumVisibleDeclContextsRead;
6680
Craig Topper79be4cd2013-07-05 04:33:53 +00006681 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006682 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6683 }
6684 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6685}
6686
6687/// \brief Under non-PCH compilation the consumer receives the objc methods
6688/// before receiving the implementation, and codegen depends on this.
6689/// We simulate this by deserializing and passing to consumer the methods of the
6690/// implementation before passing the deserialized implementation decl.
6691static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6692 ASTConsumer *Consumer) {
6693 assert(ImplD && Consumer);
6694
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006695 for (auto *I : ImplD->methods())
6696 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006697
6698 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6699}
6700
6701void ASTReader::PassInterestingDeclsToConsumer() {
6702 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006703
6704 if (PassingDeclsToConsumer)
6705 return;
6706
6707 // Guard variable to avoid recursively redoing the process of passing
6708 // decls to consumer.
6709 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6710 true);
6711
Guy Benyei11169dd2012-12-18 14:30:41 +00006712 while (!InterestingDecls.empty()) {
6713 Decl *D = InterestingDecls.front();
6714 InterestingDecls.pop_front();
6715
6716 PassInterestingDeclToConsumer(D);
6717 }
6718}
6719
6720void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6721 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6722 PassObjCImplDeclToConsumer(ImplD, Consumer);
6723 else
6724 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6725}
6726
6727void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6728 this->Consumer = Consumer;
6729
6730 if (!Consumer)
6731 return;
6732
Ben Langmuir332aafe2014-01-31 01:06:56 +00006733 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006734 // Force deserialization of this decl, which will cause it to be queued for
6735 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006736 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006737 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006738 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006739
6740 PassInterestingDeclsToConsumer();
6741}
6742
6743void ASTReader::PrintStats() {
6744 std::fprintf(stderr, "*** AST File Statistics:\n");
6745
6746 unsigned NumTypesLoaded
6747 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6748 QualType());
6749 unsigned NumDeclsLoaded
6750 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006751 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006752 unsigned NumIdentifiersLoaded
6753 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6754 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006755 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006756 unsigned NumMacrosLoaded
6757 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6758 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006759 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006760 unsigned NumSelectorsLoaded
6761 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6762 SelectorsLoaded.end(),
6763 Selector());
6764
6765 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6766 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6767 NumSLocEntriesRead, TotalNumSLocEntries,
6768 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6769 if (!TypesLoaded.empty())
6770 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6771 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6772 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6773 if (!DeclsLoaded.empty())
6774 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6775 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6776 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6777 if (!IdentifiersLoaded.empty())
6778 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6779 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6780 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6781 if (!MacrosLoaded.empty())
6782 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6783 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6784 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6785 if (!SelectorsLoaded.empty())
6786 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6787 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6788 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6789 if (TotalNumStatements)
6790 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6791 NumStatementsRead, TotalNumStatements,
6792 ((float)NumStatementsRead/TotalNumStatements * 100));
6793 if (TotalNumMacros)
6794 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6795 NumMacrosRead, TotalNumMacros,
6796 ((float)NumMacrosRead/TotalNumMacros * 100));
6797 if (TotalLexicalDeclContexts)
6798 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6799 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6800 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6801 * 100));
6802 if (TotalVisibleDeclContexts)
6803 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6804 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6805 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6806 * 100));
6807 if (TotalNumMethodPoolEntries) {
6808 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6809 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6810 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6811 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006812 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006813 if (NumMethodPoolLookups) {
6814 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6815 NumMethodPoolHits, NumMethodPoolLookups,
6816 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6817 }
6818 if (NumMethodPoolTableLookups) {
6819 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6820 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6821 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6822 * 100.0));
6823 }
6824
Douglas Gregor00a50f72013-01-25 00:38:33 +00006825 if (NumIdentifierLookupHits) {
6826 std::fprintf(stderr,
6827 " %u / %u identifier table lookups succeeded (%f%%)\n",
6828 NumIdentifierLookupHits, NumIdentifierLookups,
6829 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6830 }
6831
Douglas Gregore060e572013-01-25 01:03:03 +00006832 if (GlobalIndex) {
6833 std::fprintf(stderr, "\n");
6834 GlobalIndex->printStats();
6835 }
6836
Guy Benyei11169dd2012-12-18 14:30:41 +00006837 std::fprintf(stderr, "\n");
6838 dump();
6839 std::fprintf(stderr, "\n");
6840}
6841
6842template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6843static void
6844dumpModuleIDMap(StringRef Name,
6845 const ContinuousRangeMap<Key, ModuleFile *,
6846 InitialCapacity> &Map) {
6847 if (Map.begin() == Map.end())
6848 return;
6849
6850 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6851 llvm::errs() << Name << ":\n";
6852 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6853 I != IEnd; ++I) {
6854 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6855 << "\n";
6856 }
6857}
6858
6859void ASTReader::dump() {
6860 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6861 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6862 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6863 dumpModuleIDMap("Global type map", GlobalTypeMap);
6864 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6865 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6866 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6867 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6868 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6869 dumpModuleIDMap("Global preprocessed entity map",
6870 GlobalPreprocessedEntityMap);
6871
6872 llvm::errs() << "\n*** PCH/Modules Loaded:";
6873 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6874 MEnd = ModuleMgr.end();
6875 M != MEnd; ++M)
6876 (*M)->dump();
6877}
6878
6879/// Return the amount of memory used by memory buffers, breaking down
6880/// by heap-backed versus mmap'ed memory.
6881void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6882 for (ModuleConstIterator I = ModuleMgr.begin(),
6883 E = ModuleMgr.end(); I != E; ++I) {
6884 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6885 size_t bytes = buf->getBufferSize();
6886 switch (buf->getBufferKind()) {
6887 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6888 sizes.malloc_bytes += bytes;
6889 break;
6890 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6891 sizes.mmap_bytes += bytes;
6892 break;
6893 }
6894 }
6895 }
6896}
6897
6898void ASTReader::InitializeSema(Sema &S) {
6899 SemaObj = &S;
6900 S.addExternalSource(this);
6901
6902 // Makes sure any declarations that were deserialized "too early"
6903 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006904 for (uint64_t ID : PreloadedDeclIDs) {
6905 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6906 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006907 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006908 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006909
Richard Smith3d8e97e2013-10-18 06:54:39 +00006910 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006911 if (!FPPragmaOptions.empty()) {
6912 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6913 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6914 }
6915
Richard Smith3d8e97e2013-10-18 06:54:39 +00006916 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006917 if (!OpenCLExtensions.empty()) {
6918 unsigned I = 0;
6919#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6920#include "clang/Basic/OpenCLExtensions.def"
6921
6922 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6923 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006924
6925 UpdateSema();
6926}
6927
6928void ASTReader::UpdateSema() {
6929 assert(SemaObj && "no Sema to update");
6930
6931 // Load the offsets of the declarations that Sema references.
6932 // They will be lazily deserialized when needed.
6933 if (!SemaDeclRefs.empty()) {
6934 assert(SemaDeclRefs.size() % 2 == 0);
6935 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6936 if (!SemaObj->StdNamespace)
6937 SemaObj->StdNamespace = SemaDeclRefs[I];
6938 if (!SemaObj->StdBadAlloc)
6939 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6940 }
6941 SemaDeclRefs.clear();
6942 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006943
6944 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6945 // encountered the pragma in the source.
6946 if(OptimizeOffPragmaLocation.isValid())
6947 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006948}
6949
6950IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6951 // Note that we are loading an identifier.
6952 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006953 StringRef Name(NameStart, NameEnd - NameStart);
6954
6955 // If there is a global index, look there first to determine which modules
6956 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006957 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00006958 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00006959 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006960 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6961 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006962 }
6963 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006964 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006965 NumIdentifierLookups,
6966 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006967 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006968 IdentifierInfo *II = Visitor.getIdentifierInfo();
6969 markIdentifierUpToDate(II);
6970 return II;
6971}
6972
6973namespace clang {
6974 /// \brief An identifier-lookup iterator that enumerates all of the
6975 /// identifiers stored within a set of AST files.
6976 class ASTIdentifierIterator : public IdentifierIterator {
6977 /// \brief The AST reader whose identifiers are being enumerated.
6978 const ASTReader &Reader;
6979
6980 /// \brief The current index into the chain of AST files stored in
6981 /// the AST reader.
6982 unsigned Index;
6983
6984 /// \brief The current position within the identifier lookup table
6985 /// of the current AST file.
6986 ASTIdentifierLookupTable::key_iterator Current;
6987
6988 /// \brief The end position within the identifier lookup table of
6989 /// the current AST file.
6990 ASTIdentifierLookupTable::key_iterator End;
6991
6992 public:
6993 explicit ASTIdentifierIterator(const ASTReader &Reader);
6994
Craig Topper3e89dfe2014-03-13 02:13:41 +00006995 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006996 };
6997}
6998
6999ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
7000 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
7001 ASTIdentifierLookupTable *IdTable
7002 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
7003 Current = IdTable->key_begin();
7004 End = IdTable->key_end();
7005}
7006
7007StringRef ASTIdentifierIterator::Next() {
7008 while (Current == End) {
7009 // If we have exhausted all of our AST files, we're done.
7010 if (Index == 0)
7011 return StringRef();
7012
7013 --Index;
7014 ASTIdentifierLookupTable *IdTable
7015 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
7016 IdentifierLookupTable;
7017 Current = IdTable->key_begin();
7018 End = IdTable->key_end();
7019 }
7020
7021 // We have any identifiers remaining in the current AST file; return
7022 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007023 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007024 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007025 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007026}
7027
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007028IdentifierIterator *ASTReader::getIdentifiers() {
7029 if (!loadGlobalIndex())
7030 return GlobalIndex->createIdentifierIterator();
7031
Guy Benyei11169dd2012-12-18 14:30:41 +00007032 return new ASTIdentifierIterator(*this);
7033}
7034
7035namespace clang { namespace serialization {
7036 class ReadMethodPoolVisitor {
7037 ASTReader &Reader;
7038 Selector Sel;
7039 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007040 unsigned InstanceBits;
7041 unsigned FactoryBits;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007042 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7043 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007044
7045 public:
7046 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
7047 unsigned PriorGeneration)
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007048 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
7049 InstanceBits(0), FactoryBits(0) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00007050
7051 static bool visit(ModuleFile &M, void *UserData) {
7052 ReadMethodPoolVisitor *This
7053 = static_cast<ReadMethodPoolVisitor *>(UserData);
7054
7055 if (!M.SelectorLookupTable)
7056 return false;
7057
7058 // If we've already searched this module file, skip it now.
7059 if (M.Generation <= This->PriorGeneration)
7060 return true;
7061
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007062 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007063 ASTSelectorLookupTable *PoolTable
7064 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
7065 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
7066 if (Pos == PoolTable->end())
7067 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007068
7069 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00007070 ++This->Reader.NumSelectorsRead;
7071 // FIXME: Not quite happy with the statistics here. We probably should
7072 // disable this tracking when called via LoadSelector.
7073 // Also, should entries without methods count as misses?
7074 ++This->Reader.NumMethodPoolEntriesRead;
7075 ASTSelectorLookupTrait::data_type Data = *Pos;
7076 if (This->Reader.DeserializationListener)
7077 This->Reader.DeserializationListener->SelectorRead(Data.ID,
7078 This->Sel);
7079
7080 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7081 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007082 This->InstanceBits = Data.InstanceBits;
7083 This->FactoryBits = Data.FactoryBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00007084 return true;
7085 }
7086
7087 /// \brief Retrieve the instance methods found by this visitor.
7088 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7089 return InstanceMethods;
7090 }
7091
7092 /// \brief Retrieve the instance methods found by this visitor.
7093 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7094 return FactoryMethods;
7095 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007096
7097 unsigned getInstanceBits() const { return InstanceBits; }
7098 unsigned getFactoryBits() const { return FactoryBits; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007099 };
7100} } // end namespace clang::serialization
7101
7102/// \brief Add the given set of methods to the method list.
7103static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7104 ObjCMethodList &List) {
7105 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7106 S.addMethodToGlobalList(&List, Methods[I]);
7107 }
7108}
7109
7110void ASTReader::ReadMethodPool(Selector Sel) {
7111 // Get the selector generation and update it to the current generation.
7112 unsigned &Generation = SelectorGeneration[Sel];
7113 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007114 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007115
7116 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007117 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007118 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7119 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
7120
7121 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007122 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007123 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007124
7125 ++NumMethodPoolHits;
7126
Guy Benyei11169dd2012-12-18 14:30:41 +00007127 if (!getSema())
7128 return;
7129
7130 Sema &S = *getSema();
7131 Sema::GlobalMethodPool::iterator Pos
7132 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
7133
7134 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7135 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007136 Pos->second.first.setBits(Visitor.getInstanceBits());
7137 Pos->second.second.setBits(Visitor.getFactoryBits());
Guy Benyei11169dd2012-12-18 14:30:41 +00007138}
7139
7140void ASTReader::ReadKnownNamespaces(
7141 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7142 Namespaces.clear();
7143
7144 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7145 if (NamespaceDecl *Namespace
7146 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7147 Namespaces.push_back(Namespace);
7148 }
7149}
7150
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007151void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007152 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007153 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7154 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007155 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007156 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007157 Undefined.insert(std::make_pair(D, Loc));
7158 }
7159}
Nick Lewycky8334af82013-01-26 00:35:08 +00007160
Guy Benyei11169dd2012-12-18 14:30:41 +00007161void ASTReader::ReadTentativeDefinitions(
7162 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7163 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7164 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7165 if (Var)
7166 TentativeDefs.push_back(Var);
7167 }
7168 TentativeDefinitions.clear();
7169}
7170
7171void ASTReader::ReadUnusedFileScopedDecls(
7172 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7173 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7174 DeclaratorDecl *D
7175 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7176 if (D)
7177 Decls.push_back(D);
7178 }
7179 UnusedFileScopedDecls.clear();
7180}
7181
7182void ASTReader::ReadDelegatingConstructors(
7183 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7184 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7185 CXXConstructorDecl *D
7186 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7187 if (D)
7188 Decls.push_back(D);
7189 }
7190 DelegatingCtorDecls.clear();
7191}
7192
7193void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7194 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7195 TypedefNameDecl *D
7196 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7197 if (D)
7198 Decls.push_back(D);
7199 }
7200 ExtVectorDecls.clear();
7201}
7202
7203void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
7204 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
7205 CXXRecordDecl *D
7206 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
7207 if (D)
7208 Decls.push_back(D);
7209 }
7210 DynamicClasses.clear();
7211}
7212
Nico Weber72889432014-09-06 01:25:55 +00007213void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7214 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7215 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7216 ++I) {
7217 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7218 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7219 if (D)
7220 Decls.insert(D);
7221 }
7222 UnusedLocalTypedefNameCandidates.clear();
7223}
7224
Guy Benyei11169dd2012-12-18 14:30:41 +00007225void
Richard Smith78165b52013-01-10 23:43:47 +00007226ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
7227 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
7228 NamedDecl *D
7229 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007230 if (D)
7231 Decls.push_back(D);
7232 }
Richard Smith78165b52013-01-10 23:43:47 +00007233 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007234}
7235
7236void ASTReader::ReadReferencedSelectors(
7237 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7238 if (ReferencedSelectorsData.empty())
7239 return;
7240
7241 // If there are @selector references added them to its pool. This is for
7242 // implementation of -Wselector.
7243 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7244 unsigned I = 0;
7245 while (I < DataSize) {
7246 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7247 SourceLocation SelLoc
7248 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7249 Sels.push_back(std::make_pair(Sel, SelLoc));
7250 }
7251 ReferencedSelectorsData.clear();
7252}
7253
7254void ASTReader::ReadWeakUndeclaredIdentifiers(
7255 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7256 if (WeakUndeclaredIdentifiers.empty())
7257 return;
7258
7259 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7260 IdentifierInfo *WeakId
7261 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7262 IdentifierInfo *AliasId
7263 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7264 SourceLocation Loc
7265 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7266 bool Used = WeakUndeclaredIdentifiers[I++];
7267 WeakInfo WI(AliasId, Loc);
7268 WI.setUsed(Used);
7269 WeakIDs.push_back(std::make_pair(WeakId, WI));
7270 }
7271 WeakUndeclaredIdentifiers.clear();
7272}
7273
7274void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7275 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7276 ExternalVTableUse VT;
7277 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7278 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7279 VT.DefinitionRequired = VTableUses[Idx++];
7280 VTables.push_back(VT);
7281 }
7282
7283 VTableUses.clear();
7284}
7285
7286void ASTReader::ReadPendingInstantiations(
7287 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7288 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7289 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7290 SourceLocation Loc
7291 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7292
7293 Pending.push_back(std::make_pair(D, Loc));
7294 }
7295 PendingInstantiations.clear();
7296}
7297
Richard Smithe40f2ba2013-08-07 21:41:30 +00007298void ASTReader::ReadLateParsedTemplates(
7299 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7300 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7301 /* In loop */) {
7302 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7303
7304 LateParsedTemplate *LT = new LateParsedTemplate;
7305 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7306
7307 ModuleFile *F = getOwningModuleFile(LT->D);
7308 assert(F && "No module");
7309
7310 unsigned TokN = LateParsedTemplates[Idx++];
7311 LT->Toks.reserve(TokN);
7312 for (unsigned T = 0; T < TokN; ++T)
7313 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7314
7315 LPTMap[FD] = LT;
7316 }
7317
7318 LateParsedTemplates.clear();
7319}
7320
Guy Benyei11169dd2012-12-18 14:30:41 +00007321void ASTReader::LoadSelector(Selector Sel) {
7322 // It would be complicated to avoid reading the methods anyway. So don't.
7323 ReadMethodPool(Sel);
7324}
7325
7326void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7327 assert(ID && "Non-zero identifier ID required");
7328 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7329 IdentifiersLoaded[ID - 1] = II;
7330 if (DeserializationListener)
7331 DeserializationListener->IdentifierRead(ID, II);
7332}
7333
7334/// \brief Set the globally-visible declarations associated with the given
7335/// identifier.
7336///
7337/// If the AST reader is currently in a state where the given declaration IDs
7338/// cannot safely be resolved, they are queued until it is safe to resolve
7339/// them.
7340///
7341/// \param II an IdentifierInfo that refers to one or more globally-visible
7342/// declarations.
7343///
7344/// \param DeclIDs the set of declaration IDs with the name @p II that are
7345/// visible at global scope.
7346///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007347/// \param Decls if non-null, this vector will be populated with the set of
7348/// deserialized declarations. These declarations will not be pushed into
7349/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007350void
7351ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7352 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007353 SmallVectorImpl<Decl *> *Decls) {
7354 if (NumCurrentElementsDeserializing && !Decls) {
7355 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007356 return;
7357 }
7358
7359 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007360 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007361 // Queue this declaration so that it will be added to the
7362 // translation unit scope and identifier's declaration chain
7363 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007364 PreloadedDeclIDs.push_back(DeclIDs[I]);
7365 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007366 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007367
7368 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7369
7370 // If we're simply supposed to record the declarations, do so now.
7371 if (Decls) {
7372 Decls->push_back(D);
7373 continue;
7374 }
7375
7376 // Introduce this declaration into the translation-unit scope
7377 // and add it to the declaration chain for this identifier, so
7378 // that (unqualified) name lookup will find it.
7379 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007380 }
7381}
7382
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007383IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007384 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007385 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007386
7387 if (IdentifiersLoaded.empty()) {
7388 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007389 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007390 }
7391
7392 ID -= 1;
7393 if (!IdentifiersLoaded[ID]) {
7394 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7395 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7396 ModuleFile *M = I->second;
7397 unsigned Index = ID - M->BaseIdentifierID;
7398 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7399
7400 // All of the strings in the AST file are preceded by a 16-bit length.
7401 // Extract that 16-bit length to avoid having to execute strlen().
7402 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7403 // unsigned integers. This is important to avoid integer overflow when
7404 // we cast them to 'unsigned'.
7405 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7406 unsigned StrLen = (((unsigned) StrLenPtr[0])
7407 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007408 IdentifiersLoaded[ID]
7409 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007410 if (DeserializationListener)
7411 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7412 }
7413
7414 return IdentifiersLoaded[ID];
7415}
7416
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007417IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7418 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007419}
7420
7421IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7422 if (LocalID < NUM_PREDEF_IDENT_IDS)
7423 return LocalID;
7424
7425 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7426 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7427 assert(I != M.IdentifierRemap.end()
7428 && "Invalid index into identifier index remap");
7429
7430 return LocalID + I->second;
7431}
7432
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007433MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007434 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007435 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007436
7437 if (MacrosLoaded.empty()) {
7438 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007439 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007440 }
7441
7442 ID -= NUM_PREDEF_MACRO_IDS;
7443 if (!MacrosLoaded[ID]) {
7444 GlobalMacroMapType::iterator I
7445 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7446 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7447 ModuleFile *M = I->second;
7448 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007449 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7450
7451 if (DeserializationListener)
7452 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7453 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007454 }
7455
7456 return MacrosLoaded[ID];
7457}
7458
7459MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7460 if (LocalID < NUM_PREDEF_MACRO_IDS)
7461 return LocalID;
7462
7463 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7464 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7465 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7466
7467 return LocalID + I->second;
7468}
7469
7470serialization::SubmoduleID
7471ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7472 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7473 return LocalID;
7474
7475 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7476 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7477 assert(I != M.SubmoduleRemap.end()
7478 && "Invalid index into submodule index remap");
7479
7480 return LocalID + I->second;
7481}
7482
7483Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7484 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7485 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007486 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007487 }
7488
7489 if (GlobalID > SubmodulesLoaded.size()) {
7490 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007491 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007492 }
7493
7494 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7495}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007496
7497Module *ASTReader::getModule(unsigned ID) {
7498 return getSubmodule(ID);
7499}
7500
Guy Benyei11169dd2012-12-18 14:30:41 +00007501Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7502 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7503}
7504
7505Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7506 if (ID == 0)
7507 return Selector();
7508
7509 if (ID > SelectorsLoaded.size()) {
7510 Error("selector ID out of range in AST file");
7511 return Selector();
7512 }
7513
Craig Toppera13603a2014-05-22 05:54:18 +00007514 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007515 // Load this selector from the selector table.
7516 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7517 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7518 ModuleFile &M = *I->second;
7519 ASTSelectorLookupTrait Trait(*this, M);
7520 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7521 SelectorsLoaded[ID - 1] =
7522 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7523 if (DeserializationListener)
7524 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7525 }
7526
7527 return SelectorsLoaded[ID - 1];
7528}
7529
7530Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7531 return DecodeSelector(ID);
7532}
7533
7534uint32_t ASTReader::GetNumExternalSelectors() {
7535 // ID 0 (the null selector) is considered an external selector.
7536 return getTotalNumSelectors() + 1;
7537}
7538
7539serialization::SelectorID
7540ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7541 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7542 return LocalID;
7543
7544 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7545 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7546 assert(I != M.SelectorRemap.end()
7547 && "Invalid index into selector index remap");
7548
7549 return LocalID + I->second;
7550}
7551
7552DeclarationName
7553ASTReader::ReadDeclarationName(ModuleFile &F,
7554 const RecordData &Record, unsigned &Idx) {
7555 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7556 switch (Kind) {
7557 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007558 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007559
7560 case DeclarationName::ObjCZeroArgSelector:
7561 case DeclarationName::ObjCOneArgSelector:
7562 case DeclarationName::ObjCMultiArgSelector:
7563 return DeclarationName(ReadSelector(F, Record, Idx));
7564
7565 case DeclarationName::CXXConstructorName:
7566 return Context.DeclarationNames.getCXXConstructorName(
7567 Context.getCanonicalType(readType(F, Record, Idx)));
7568
7569 case DeclarationName::CXXDestructorName:
7570 return Context.DeclarationNames.getCXXDestructorName(
7571 Context.getCanonicalType(readType(F, Record, Idx)));
7572
7573 case DeclarationName::CXXConversionFunctionName:
7574 return Context.DeclarationNames.getCXXConversionFunctionName(
7575 Context.getCanonicalType(readType(F, Record, Idx)));
7576
7577 case DeclarationName::CXXOperatorName:
7578 return Context.DeclarationNames.getCXXOperatorName(
7579 (OverloadedOperatorKind)Record[Idx++]);
7580
7581 case DeclarationName::CXXLiteralOperatorName:
7582 return Context.DeclarationNames.getCXXLiteralOperatorName(
7583 GetIdentifierInfo(F, Record, Idx));
7584
7585 case DeclarationName::CXXUsingDirective:
7586 return DeclarationName::getUsingDirectiveName();
7587 }
7588
7589 llvm_unreachable("Invalid NameKind!");
7590}
7591
7592void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7593 DeclarationNameLoc &DNLoc,
7594 DeclarationName Name,
7595 const RecordData &Record, unsigned &Idx) {
7596 switch (Name.getNameKind()) {
7597 case DeclarationName::CXXConstructorName:
7598 case DeclarationName::CXXDestructorName:
7599 case DeclarationName::CXXConversionFunctionName:
7600 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7601 break;
7602
7603 case DeclarationName::CXXOperatorName:
7604 DNLoc.CXXOperatorName.BeginOpNameLoc
7605 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7606 DNLoc.CXXOperatorName.EndOpNameLoc
7607 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7608 break;
7609
7610 case DeclarationName::CXXLiteralOperatorName:
7611 DNLoc.CXXLiteralOperatorName.OpNameLoc
7612 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7613 break;
7614
7615 case DeclarationName::Identifier:
7616 case DeclarationName::ObjCZeroArgSelector:
7617 case DeclarationName::ObjCOneArgSelector:
7618 case DeclarationName::ObjCMultiArgSelector:
7619 case DeclarationName::CXXUsingDirective:
7620 break;
7621 }
7622}
7623
7624void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7625 DeclarationNameInfo &NameInfo,
7626 const RecordData &Record, unsigned &Idx) {
7627 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7628 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7629 DeclarationNameLoc DNLoc;
7630 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7631 NameInfo.setInfo(DNLoc);
7632}
7633
7634void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7635 const RecordData &Record, unsigned &Idx) {
7636 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7637 unsigned NumTPLists = Record[Idx++];
7638 Info.NumTemplParamLists = NumTPLists;
7639 if (NumTPLists) {
7640 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7641 for (unsigned i=0; i != NumTPLists; ++i)
7642 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7643 }
7644}
7645
7646TemplateName
7647ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7648 unsigned &Idx) {
7649 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7650 switch (Kind) {
7651 case TemplateName::Template:
7652 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7653
7654 case TemplateName::OverloadedTemplate: {
7655 unsigned size = Record[Idx++];
7656 UnresolvedSet<8> Decls;
7657 while (size--)
7658 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7659
7660 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7661 }
7662
7663 case TemplateName::QualifiedTemplate: {
7664 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7665 bool hasTemplKeyword = Record[Idx++];
7666 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7667 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7668 }
7669
7670 case TemplateName::DependentTemplate: {
7671 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7672 if (Record[Idx++]) // isIdentifier
7673 return Context.getDependentTemplateName(NNS,
7674 GetIdentifierInfo(F, Record,
7675 Idx));
7676 return Context.getDependentTemplateName(NNS,
7677 (OverloadedOperatorKind)Record[Idx++]);
7678 }
7679
7680 case TemplateName::SubstTemplateTemplateParm: {
7681 TemplateTemplateParmDecl *param
7682 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7683 if (!param) return TemplateName();
7684 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7685 return Context.getSubstTemplateTemplateParm(param, replacement);
7686 }
7687
7688 case TemplateName::SubstTemplateTemplateParmPack: {
7689 TemplateTemplateParmDecl *Param
7690 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7691 if (!Param)
7692 return TemplateName();
7693
7694 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7695 if (ArgPack.getKind() != TemplateArgument::Pack)
7696 return TemplateName();
7697
7698 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7699 }
7700 }
7701
7702 llvm_unreachable("Unhandled template name kind!");
7703}
7704
7705TemplateArgument
7706ASTReader::ReadTemplateArgument(ModuleFile &F,
7707 const RecordData &Record, unsigned &Idx) {
7708 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7709 switch (Kind) {
7710 case TemplateArgument::Null:
7711 return TemplateArgument();
7712 case TemplateArgument::Type:
7713 return TemplateArgument(readType(F, Record, Idx));
7714 case TemplateArgument::Declaration: {
7715 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007716 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007717 }
7718 case TemplateArgument::NullPtr:
7719 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7720 case TemplateArgument::Integral: {
7721 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7722 QualType T = readType(F, Record, Idx);
7723 return TemplateArgument(Context, Value, T);
7724 }
7725 case TemplateArgument::Template:
7726 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7727 case TemplateArgument::TemplateExpansion: {
7728 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007729 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007730 if (unsigned NumExpansions = Record[Idx++])
7731 NumTemplateExpansions = NumExpansions - 1;
7732 return TemplateArgument(Name, NumTemplateExpansions);
7733 }
7734 case TemplateArgument::Expression:
7735 return TemplateArgument(ReadExpr(F));
7736 case TemplateArgument::Pack: {
7737 unsigned NumArgs = Record[Idx++];
7738 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7739 for (unsigned I = 0; I != NumArgs; ++I)
7740 Args[I] = ReadTemplateArgument(F, Record, Idx);
7741 return TemplateArgument(Args, NumArgs);
7742 }
7743 }
7744
7745 llvm_unreachable("Unhandled template argument kind!");
7746}
7747
7748TemplateParameterList *
7749ASTReader::ReadTemplateParameterList(ModuleFile &F,
7750 const RecordData &Record, unsigned &Idx) {
7751 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7752 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7753 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7754
7755 unsigned NumParams = Record[Idx++];
7756 SmallVector<NamedDecl *, 16> Params;
7757 Params.reserve(NumParams);
7758 while (NumParams--)
7759 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7760
7761 TemplateParameterList* TemplateParams =
7762 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7763 Params.data(), Params.size(), RAngleLoc);
7764 return TemplateParams;
7765}
7766
7767void
7768ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007769ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007770 ModuleFile &F, const RecordData &Record,
7771 unsigned &Idx) {
7772 unsigned NumTemplateArgs = Record[Idx++];
7773 TemplArgs.reserve(NumTemplateArgs);
7774 while (NumTemplateArgs--)
7775 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7776}
7777
7778/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007779void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007780 const RecordData &Record, unsigned &Idx) {
7781 unsigned NumDecls = Record[Idx++];
7782 Set.reserve(Context, NumDecls);
7783 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007784 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007785 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007786 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007787 }
7788}
7789
7790CXXBaseSpecifier
7791ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7792 const RecordData &Record, unsigned &Idx) {
7793 bool isVirtual = static_cast<bool>(Record[Idx++]);
7794 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7795 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7796 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7797 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7798 SourceRange Range = ReadSourceRange(F, Record, Idx);
7799 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7800 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7801 EllipsisLoc);
7802 Result.setInheritConstructors(inheritConstructors);
7803 return Result;
7804}
7805
7806std::pair<CXXCtorInitializer **, unsigned>
7807ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7808 unsigned &Idx) {
Craig Toppera13603a2014-05-22 05:54:18 +00007809 CXXCtorInitializer **CtorInitializers = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007810 unsigned NumInitializers = Record[Idx++];
7811 if (NumInitializers) {
7812 CtorInitializers
7813 = new (Context) CXXCtorInitializer*[NumInitializers];
7814 for (unsigned i=0; i != NumInitializers; ++i) {
Craig Toppera13603a2014-05-22 05:54:18 +00007815 TypeSourceInfo *TInfo = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007816 bool IsBaseVirtual = false;
Craig Toppera13603a2014-05-22 05:54:18 +00007817 FieldDecl *Member = nullptr;
7818 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007819
7820 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7821 switch (Type) {
7822 case CTOR_INITIALIZER_BASE:
7823 TInfo = GetTypeSourceInfo(F, Record, Idx);
7824 IsBaseVirtual = Record[Idx++];
7825 break;
7826
7827 case CTOR_INITIALIZER_DELEGATING:
7828 TInfo = GetTypeSourceInfo(F, Record, Idx);
7829 break;
7830
7831 case CTOR_INITIALIZER_MEMBER:
7832 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7833 break;
7834
7835 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7836 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7837 break;
7838 }
7839
7840 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7841 Expr *Init = ReadExpr(F);
7842 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7843 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7844 bool IsWritten = Record[Idx++];
7845 unsigned SourceOrderOrNumArrayIndices;
7846 SmallVector<VarDecl *, 8> Indices;
7847 if (IsWritten) {
7848 SourceOrderOrNumArrayIndices = Record[Idx++];
7849 } else {
7850 SourceOrderOrNumArrayIndices = Record[Idx++];
7851 Indices.reserve(SourceOrderOrNumArrayIndices);
7852 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7853 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7854 }
7855
7856 CXXCtorInitializer *BOMInit;
7857 if (Type == CTOR_INITIALIZER_BASE) {
7858 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7859 LParenLoc, Init, RParenLoc,
7860 MemberOrEllipsisLoc);
7861 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7862 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7863 Init, RParenLoc);
7864 } else if (IsWritten) {
7865 if (Member)
7866 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7867 LParenLoc, Init, RParenLoc);
7868 else
7869 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7870 MemberOrEllipsisLoc, LParenLoc,
7871 Init, RParenLoc);
7872 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007873 if (IndirectMember) {
7874 assert(Indices.empty() && "Indirect field improperly initialized");
7875 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7876 MemberOrEllipsisLoc, LParenLoc,
7877 Init, RParenLoc);
7878 } else {
7879 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7880 LParenLoc, Init, RParenLoc,
7881 Indices.data(), Indices.size());
7882 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007883 }
7884
7885 if (IsWritten)
7886 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7887 CtorInitializers[i] = BOMInit;
7888 }
7889 }
7890
7891 return std::make_pair(CtorInitializers, NumInitializers);
7892}
7893
7894NestedNameSpecifier *
7895ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7896 const RecordData &Record, unsigned &Idx) {
7897 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007898 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007899 for (unsigned I = 0; I != N; ++I) {
7900 NestedNameSpecifier::SpecifierKind Kind
7901 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7902 switch (Kind) {
7903 case NestedNameSpecifier::Identifier: {
7904 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7905 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7906 break;
7907 }
7908
7909 case NestedNameSpecifier::Namespace: {
7910 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7911 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7912 break;
7913 }
7914
7915 case NestedNameSpecifier::NamespaceAlias: {
7916 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7917 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7918 break;
7919 }
7920
7921 case NestedNameSpecifier::TypeSpec:
7922 case NestedNameSpecifier::TypeSpecWithTemplate: {
7923 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7924 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007925 return nullptr;
7926
Guy Benyei11169dd2012-12-18 14:30:41 +00007927 bool Template = Record[Idx++];
7928 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7929 break;
7930 }
7931
7932 case NestedNameSpecifier::Global: {
7933 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7934 // No associated value, and there can't be a prefix.
7935 break;
7936 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007937
7938 case NestedNameSpecifier::Super: {
7939 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7940 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7941 break;
7942 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007943 }
7944 Prev = NNS;
7945 }
7946 return NNS;
7947}
7948
7949NestedNameSpecifierLoc
7950ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7951 unsigned &Idx) {
7952 unsigned N = Record[Idx++];
7953 NestedNameSpecifierLocBuilder Builder;
7954 for (unsigned I = 0; I != N; ++I) {
7955 NestedNameSpecifier::SpecifierKind Kind
7956 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7957 switch (Kind) {
7958 case NestedNameSpecifier::Identifier: {
7959 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7960 SourceRange Range = ReadSourceRange(F, Record, Idx);
7961 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7962 break;
7963 }
7964
7965 case NestedNameSpecifier::Namespace: {
7966 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7967 SourceRange Range = ReadSourceRange(F, Record, Idx);
7968 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7969 break;
7970 }
7971
7972 case NestedNameSpecifier::NamespaceAlias: {
7973 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7974 SourceRange Range = ReadSourceRange(F, Record, Idx);
7975 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7976 break;
7977 }
7978
7979 case NestedNameSpecifier::TypeSpec:
7980 case NestedNameSpecifier::TypeSpecWithTemplate: {
7981 bool Template = Record[Idx++];
7982 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7983 if (!T)
7984 return NestedNameSpecifierLoc();
7985 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7986
7987 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7988 Builder.Extend(Context,
7989 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7990 T->getTypeLoc(), ColonColonLoc);
7991 break;
7992 }
7993
7994 case NestedNameSpecifier::Global: {
7995 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7996 Builder.MakeGlobal(Context, ColonColonLoc);
7997 break;
7998 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007999
8000 case NestedNameSpecifier::Super: {
8001 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8002 SourceRange Range = ReadSourceRange(F, Record, Idx);
8003 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8004 break;
8005 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008006 }
8007 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008008
Guy Benyei11169dd2012-12-18 14:30:41 +00008009 return Builder.getWithLocInContext(Context);
8010}
8011
8012SourceRange
8013ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8014 unsigned &Idx) {
8015 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8016 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8017 return SourceRange(beg, end);
8018}
8019
8020/// \brief Read an integral value
8021llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8022 unsigned BitWidth = Record[Idx++];
8023 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8024 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8025 Idx += NumWords;
8026 return Result;
8027}
8028
8029/// \brief Read a signed integral value
8030llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8031 bool isUnsigned = Record[Idx++];
8032 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8033}
8034
8035/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008036llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8037 const llvm::fltSemantics &Sem,
8038 unsigned &Idx) {
8039 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008040}
8041
8042// \brief Read a string
8043std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8044 unsigned Len = Record[Idx++];
8045 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8046 Idx += Len;
8047 return Result;
8048}
8049
Richard Smith7ed1bc92014-12-05 22:42:13 +00008050std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8051 unsigned &Idx) {
8052 std::string Filename = ReadString(Record, Idx);
8053 ResolveImportedPath(F, Filename);
8054 return Filename;
8055}
8056
Guy Benyei11169dd2012-12-18 14:30:41 +00008057VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8058 unsigned &Idx) {
8059 unsigned Major = Record[Idx++];
8060 unsigned Minor = Record[Idx++];
8061 unsigned Subminor = Record[Idx++];
8062 if (Minor == 0)
8063 return VersionTuple(Major);
8064 if (Subminor == 0)
8065 return VersionTuple(Major, Minor - 1);
8066 return VersionTuple(Major, Minor - 1, Subminor - 1);
8067}
8068
8069CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8070 const RecordData &Record,
8071 unsigned &Idx) {
8072 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8073 return CXXTemporary::Create(Context, Decl);
8074}
8075
8076DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008077 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008078}
8079
8080DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8081 return Diags.Report(Loc, DiagID);
8082}
8083
8084/// \brief Retrieve the identifier table associated with the
8085/// preprocessor.
8086IdentifierTable &ASTReader::getIdentifierTable() {
8087 return PP.getIdentifierTable();
8088}
8089
8090/// \brief Record that the given ID maps to the given switch-case
8091/// statement.
8092void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008093 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008094 "Already have a SwitchCase with this ID");
8095 (*CurrSwitchCaseStmts)[ID] = SC;
8096}
8097
8098/// \brief Retrieve the switch-case statement with the given ID.
8099SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008100 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008101 return (*CurrSwitchCaseStmts)[ID];
8102}
8103
8104void ASTReader::ClearSwitchCaseIDs() {
8105 CurrSwitchCaseStmts->clear();
8106}
8107
8108void ASTReader::ReadComments() {
8109 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008110 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008111 serialization::ModuleFile *> >::iterator
8112 I = CommentsCursors.begin(),
8113 E = CommentsCursors.end();
8114 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008115 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008116 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008117 serialization::ModuleFile &F = *I->second;
8118 SavedStreamPosition SavedPosition(Cursor);
8119
8120 RecordData Record;
8121 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008122 llvm::BitstreamEntry Entry =
8123 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008124
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008125 switch (Entry.Kind) {
8126 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8127 case llvm::BitstreamEntry::Error:
8128 Error("malformed block record in AST file");
8129 return;
8130 case llvm::BitstreamEntry::EndBlock:
8131 goto NextCursor;
8132 case llvm::BitstreamEntry::Record:
8133 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008134 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008135 }
8136
8137 // Read a record.
8138 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008139 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008140 case COMMENTS_RAW_COMMENT: {
8141 unsigned Idx = 0;
8142 SourceRange SR = ReadSourceRange(F, Record, Idx);
8143 RawComment::CommentKind Kind =
8144 (RawComment::CommentKind) Record[Idx++];
8145 bool IsTrailingComment = Record[Idx++];
8146 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008147 Comments.push_back(new (Context) RawComment(
8148 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8149 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008150 break;
8151 }
8152 }
8153 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008154 NextCursor:
8155 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008156 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008157}
8158
Argyrios Kyrtzidis1bde1172014-11-18 05:24:18 +00008159void ASTReader::getInputFiles(ModuleFile &F,
8160 SmallVectorImpl<serialization::InputFile> &Files) {
8161 for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
8162 unsigned ID = I+1;
8163 Files.push_back(getInputFile(F, ID));
8164 }
8165}
8166
Richard Smithcd45dbc2014-04-19 03:48:30 +00008167std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8168 // If we know the owning module, use it.
8169 if (Module *M = D->getOwningModule())
8170 return M->getFullModuleName();
8171
8172 // Otherwise, use the name of the top-level module the decl is within.
8173 if (ModuleFile *M = getOwningModuleFile(D))
8174 return M->ModuleName;
8175
8176 // Not from a module.
8177 return "";
8178}
8179
Guy Benyei11169dd2012-12-18 14:30:41 +00008180void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008181 while (!PendingIdentifierInfos.empty() ||
8182 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008183 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008184 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008185 // If any identifiers with corresponding top-level declarations have
8186 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008187 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8188 TopLevelDeclsMap;
8189 TopLevelDeclsMap TopLevelDecls;
8190
Guy Benyei11169dd2012-12-18 14:30:41 +00008191 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008192 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008193 SmallVector<uint32_t, 4> DeclIDs =
8194 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008195 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008196
8197 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008198 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008199
Richard Smith851072e2014-05-19 20:59:20 +00008200 // For each decl chain that we wanted to complete while deserializing, mark
8201 // it as "still needs to be completed".
8202 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8203 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8204 }
8205 PendingIncompleteDeclChains.clear();
8206
Guy Benyei11169dd2012-12-18 14:30:41 +00008207 // Load pending declaration chains.
8208 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
8209 loadPendingDeclChain(PendingDeclChains[I]);
8210 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
8211 }
8212 PendingDeclChains.clear();
8213
Douglas Gregor6168bd22013-02-18 15:53:43 +00008214 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008215 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8216 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008217 IdentifierInfo *II = TLD->first;
8218 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008219 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008220 }
8221 }
8222
Guy Benyei11169dd2012-12-18 14:30:41 +00008223 // Load any pending macro definitions.
8224 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008225 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8226 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8227 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8228 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008229 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008230 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008231 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008232 if (Info.M->Kind != MK_ImplicitModule &&
8233 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008234 resolvePendingMacro(II, Info);
8235 }
8236 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008237 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008238 ++IDIdx) {
8239 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008240 if (Info.M->Kind == MK_ImplicitModule ||
8241 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008242 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008243 }
8244 }
8245 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008246
8247 // Wire up the DeclContexts for Decls that we delayed setting until
8248 // recursive loading is completed.
8249 while (!PendingDeclContextInfos.empty()) {
8250 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8251 PendingDeclContextInfos.pop_front();
8252 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8253 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8254 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8255 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008256
Richard Smithd1c46742014-04-30 02:24:17 +00008257 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008258 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008259 auto Update = PendingUpdateRecords.pop_back_val();
8260 ReadingKindTracker ReadingKind(Read_Decl, *this);
8261 loadDeclUpdateRecords(Update.first, Update.second);
8262 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008263 }
8264
8265 // If we deserialized any C++ or Objective-C class definitions, any
8266 // Objective-C protocol definitions, or any redeclarable templates, make sure
8267 // that all redeclarations point to the definitions. Note that this can only
8268 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008269 for (Decl *D : PendingDefinitions) {
8270 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008271 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008272 // Make sure that the TagType points at the definition.
8273 const_cast<TagType*>(TagT)->decl = TD;
8274 }
8275
Craig Topperc6914d02014-08-25 04:15:02 +00008276 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith2c381642014-08-27 23:11:59 +00008277 for (auto R : RD->redecls()) {
8278 assert((R == D) == R->isThisDeclarationADefinition() &&
8279 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008280 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008281 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008282 }
8283
8284 continue;
8285 }
8286
Craig Topperc6914d02014-08-25 04:15:02 +00008287 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008288 // Make sure that the ObjCInterfaceType points at the definition.
8289 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8290 ->Decl = ID;
8291
Aaron Ballman86c93902014-03-06 23:45:36 +00008292 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008293 R->Data = ID->Data;
8294
8295 continue;
8296 }
8297
Craig Topperc6914d02014-08-25 04:15:02 +00008298 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Aaron Ballman86c93902014-03-06 23:45:36 +00008299 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008300 R->Data = PD->Data;
8301
8302 continue;
8303 }
8304
Craig Topperc6914d02014-08-25 04:15:02 +00008305 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00008306 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008307 R->Common = RTD->Common;
8308 }
8309 PendingDefinitions.clear();
8310
8311 // Load the bodies of any functions or methods we've encountered. We do
8312 // this now (delayed) so that we can be sure that the declaration chains
8313 // have been fully wired up.
8314 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8315 PBEnd = PendingBodies.end();
8316 PB != PBEnd; ++PB) {
8317 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8318 // FIXME: Check for =delete/=default?
8319 // FIXME: Complain about ODR violations here?
8320 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8321 FD->setLazyBody(PB->second);
8322 continue;
8323 }
8324
8325 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8326 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8327 MD->setLazyBody(PB->second);
8328 }
8329 PendingBodies.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008330}
8331
8332void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008333 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8334 return;
8335
Richard Smitha0ce9c42014-07-29 23:23:27 +00008336 // Trigger the import of the full definition of each class that had any
8337 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008338 // These updates may in turn find and diagnose some ODR failures, so take
8339 // ownership of the set first.
8340 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8341 PendingOdrMergeFailures.clear();
8342 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008343 Merge.first->buildLookup();
8344 Merge.first->decls_begin();
8345 Merge.first->bases_begin();
8346 Merge.first->vbases_begin();
8347 for (auto *RD : Merge.second) {
8348 RD->decls_begin();
8349 RD->bases_begin();
8350 RD->vbases_begin();
8351 }
8352 }
8353
8354 // For each declaration from a merged context, check that the canonical
8355 // definition of that context also contains a declaration of the same
8356 // entity.
8357 //
8358 // Caution: this loop does things that might invalidate iterators into
8359 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8360 while (!PendingOdrMergeChecks.empty()) {
8361 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8362
8363 // FIXME: Skip over implicit declarations for now. This matters for things
8364 // like implicitly-declared special member functions. This isn't entirely
8365 // correct; we can end up with multiple unmerged declarations of the same
8366 // implicit entity.
8367 if (D->isImplicit())
8368 continue;
8369
8370 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008371
8372 bool Found = false;
8373 const Decl *DCanon = D->getCanonicalDecl();
8374
Richard Smith01bdb7a2014-08-28 05:44:07 +00008375 for (auto RI : D->redecls()) {
8376 if (RI->getLexicalDeclContext() == CanonDef) {
8377 Found = true;
8378 break;
8379 }
8380 }
8381 if (Found)
8382 continue;
8383
Richard Smitha0ce9c42014-07-29 23:23:27 +00008384 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith01bdb7a2014-08-28 05:44:07 +00008385 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
Richard Smitha0ce9c42014-07-29 23:23:27 +00008386 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8387 !Found && I != E; ++I) {
8388 for (auto RI : (*I)->redecls()) {
8389 if (RI->getLexicalDeclContext() == CanonDef) {
8390 // This declaration is present in the canonical definition. If it's
8391 // in the same redecl chain, it's the one we're looking for.
8392 if (RI->getCanonicalDecl() == DCanon)
8393 Found = true;
8394 else
8395 Candidates.push_back(cast<NamedDecl>(RI));
8396 break;
8397 }
8398 }
8399 }
8400
8401 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008402 // The AST doesn't like TagDecls becoming invalid after they've been
8403 // completed. We only really need to mark FieldDecls as invalid here.
8404 if (!isa<TagDecl>(D))
8405 D->setInvalidDecl();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008406
8407 std::string CanonDefModule =
8408 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8409 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8410 << D << getOwningModuleNameForDiagnostic(D)
8411 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8412
8413 if (Candidates.empty())
8414 Diag(cast<Decl>(CanonDef)->getLocation(),
8415 diag::note_module_odr_violation_no_possible_decls) << D;
8416 else {
8417 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8418 Diag(Candidates[I]->getLocation(),
8419 diag::note_module_odr_violation_possible_decl)
8420 << Candidates[I];
8421 }
8422
8423 DiagnosedOdrMergeFailures.insert(CanonDef);
8424 }
8425 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008426
8427 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008428 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008429 // If we've already pointed out a specific problem with this class, don't
8430 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008431 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008432 continue;
8433
8434 bool Diagnosed = false;
8435 for (auto *RD : Merge.second) {
8436 // Multiple different declarations got merged together; tell the user
8437 // where they came from.
8438 if (Merge.first != RD) {
8439 // FIXME: Walk the definition, figure out what's different,
8440 // and diagnose that.
8441 if (!Diagnosed) {
8442 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8443 Diag(Merge.first->getLocation(),
8444 diag::err_module_odr_violation_different_definitions)
8445 << Merge.first << Module.empty() << Module;
8446 Diagnosed = true;
8447 }
8448
8449 Diag(RD->getLocation(),
8450 diag::note_module_odr_violation_different_definitions)
8451 << getOwningModuleNameForDiagnostic(RD);
8452 }
8453 }
8454
8455 if (!Diagnosed) {
8456 // All definitions are updates to the same declaration. This happens if a
8457 // module instantiates the declaration of a class template specialization
8458 // and two or more other modules instantiate its definition.
8459 //
8460 // FIXME: Indicate which modules had instantiations of this definition.
8461 // FIXME: How can this even happen?
8462 Diag(Merge.first->getLocation(),
8463 diag::err_module_odr_violation_different_instantiations)
8464 << Merge.first;
8465 }
8466 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008467}
8468
8469void ASTReader::FinishedDeserializing() {
8470 assert(NumCurrentElementsDeserializing &&
8471 "FinishedDeserializing not paired with StartedDeserializing");
8472 if (NumCurrentElementsDeserializing == 1) {
8473 // We decrease NumCurrentElementsDeserializing only after pending actions
8474 // are finished, to avoid recursively re-calling finishPendingActions().
8475 finishPendingActions();
8476 }
8477 --NumCurrentElementsDeserializing;
8478
Richard Smitha0ce9c42014-07-29 23:23:27 +00008479 if (NumCurrentElementsDeserializing == 0) {
8480 diagnoseOdrViolations();
8481
Richard Smith04d05b52014-03-23 00:27:18 +00008482 // We are not in recursive loading, so it's safe to pass the "interesting"
8483 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008484 if (Consumer)
8485 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008486 }
8487}
8488
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008489void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00008490 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008491
8492 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8493 SemaObj->TUScope->AddDecl(D);
8494 } else if (SemaObj->TUScope) {
8495 // Adding the decl to IdResolver may have failed because it was already in
8496 // (even though it was not added in scope). If it is already in, make sure
8497 // it gets in the scope as well.
8498 if (std::find(SemaObj->IdResolver.begin(Name),
8499 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8500 SemaObj->TUScope->AddDecl(D);
8501 }
8502}
8503
Nico Weber824285e2014-05-08 04:26:47 +00008504ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8505 bool DisableValidation, bool AllowASTWithCompilerErrors,
8506 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008507 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008508 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008509 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Craig Toppera13603a2014-05-22 05:54:18 +00008510 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
8511 SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
8512 ModuleMgr(PP.getFileManager()), isysroot(isysroot),
8513 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008514 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8515 AllowConfigurationMismatch(AllowConfigurationMismatch),
8516 ValidateSystemInputs(ValidateSystemInputs),
8517 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Richard Smith053f6c62014-05-16 23:01:30 +00008518 CurrSwitchCaseStmts(&SwitchCaseStmts),
Nico Weber824285e2014-05-08 04:26:47 +00008519 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8520 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8521 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8522 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8523 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8524 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8525 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8526 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8527 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8528 PassingDeclsToConsumer(false), NumCXXBaseSpecifiersLoaded(0),
8529 ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008530 SourceMgr.setExternalSLocEntrySource(this);
8531}
8532
8533ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008534 if (OwnsDeserializationListener)
8535 delete DeserializationListener;
8536
Guy Benyei11169dd2012-12-18 14:30:41 +00008537 for (DeclContextVisibleUpdatesPending::iterator
8538 I = PendingVisibleUpdates.begin(),
8539 E = PendingVisibleUpdates.end();
8540 I != E; ++I) {
8541 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8542 F = I->second.end();
8543 J != F; ++J)
8544 delete J->first;
8545 }
8546}