blob: 69d8f117cb99380c80dd45821e4a16dcfcd8d61e [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"
Adrian Prantlc4091aa2015-02-20 19:44:52 +000049#include "llvm/Object/COFF.h"
50#include "llvm/Object/ObjectFile.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000051#include "llvm/Support/ErrorHandling.h"
52#include "llvm/Support/FileSystem.h"
53#include "llvm/Support/MemoryBuffer.h"
54#include "llvm/Support/Path.h"
55#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000056#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000057#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000058#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000059#include <iterator>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000060#include <system_error>
Guy Benyei11169dd2012-12-18 14:30:41 +000061
62using namespace clang;
63using namespace clang::serialization;
64using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000065using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000066
Ben Langmuircb69b572014-03-07 06:40:32 +000067
68//===----------------------------------------------------------------------===//
69// ChainedASTReaderListener implementation
70//===----------------------------------------------------------------------===//
71
72bool
73ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
74 return First->ReadFullVersionInformation(FullVersion) ||
75 Second->ReadFullVersionInformation(FullVersion);
76}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000077void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
78 First->ReadModuleName(ModuleName);
79 Second->ReadModuleName(ModuleName);
80}
81void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
82 First->ReadModuleMapFile(ModuleMapPath);
83 Second->ReadModuleMapFile(ModuleMapPath);
84}
Richard Smith1e2cf0d2014-10-31 02:28:58 +000085bool
86ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
87 bool Complain,
88 bool AllowCompatibleDifferences) {
89 return First->ReadLanguageOptions(LangOpts, Complain,
90 AllowCompatibleDifferences) ||
91 Second->ReadLanguageOptions(LangOpts, Complain,
92 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000093}
94bool
95ChainedASTReaderListener::ReadTargetOptions(const TargetOptions &TargetOpts,
96 bool Complain) {
97 return First->ReadTargetOptions(TargetOpts, Complain) ||
98 Second->ReadTargetOptions(TargetOpts, Complain);
99}
100bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000101 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000102 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
103 Second->ReadDiagnosticOptions(DiagOpts, Complain);
104}
105bool
106ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
107 bool Complain) {
108 return First->ReadFileSystemOptions(FSOpts, Complain) ||
109 Second->ReadFileSystemOptions(FSOpts, Complain);
110}
111
112bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000113 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
114 bool Complain) {
115 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
116 Complain) ||
117 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
118 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000119}
120bool ChainedASTReaderListener::ReadPreprocessorOptions(
121 const PreprocessorOptions &PPOpts, bool Complain,
122 std::string &SuggestedPredefines) {
123 return First->ReadPreprocessorOptions(PPOpts, Complain,
124 SuggestedPredefines) ||
125 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
126}
127void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
128 unsigned Value) {
129 First->ReadCounter(M, Value);
130 Second->ReadCounter(M, Value);
131}
132bool ChainedASTReaderListener::needsInputFileVisitation() {
133 return First->needsInputFileVisitation() ||
134 Second->needsInputFileVisitation();
135}
136bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
137 return First->needsSystemInputFileVisitation() ||
138 Second->needsSystemInputFileVisitation();
139}
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000140void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
141 First->visitModuleFile(Filename);
142 Second->visitModuleFile(Filename);
143}
Ben Langmuircb69b572014-03-07 06:40:32 +0000144bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000145 bool isSystem,
146 bool isOverridden) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000147 bool Continue = false;
148 if (First->needsInputFileVisitation() &&
149 (!isSystem || First->needsSystemInputFileVisitation()))
150 Continue |= First->visitInputFile(Filename, isSystem, isOverridden);
151 if (Second->needsInputFileVisitation() &&
152 (!isSystem || Second->needsSystemInputFileVisitation()))
153 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden);
154 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000155}
156
Guy Benyei11169dd2012-12-18 14:30:41 +0000157//===----------------------------------------------------------------------===//
158// PCH validator implementation
159//===----------------------------------------------------------------------===//
160
161ASTReaderListener::~ASTReaderListener() {}
162
163/// \brief Compare the given set of language options against an existing set of
164/// language options.
165///
166/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000167/// \param AllowCompatibleDifferences If true, differences between compatible
168/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000169///
170/// \returns true if the languagae options mis-match, false otherwise.
171static bool checkLanguageOptions(const LangOptions &LangOpts,
172 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000173 DiagnosticsEngine *Diags,
174 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000175#define LANGOPT(Name, Bits, Default, Description) \
176 if (ExistingLangOpts.Name != LangOpts.Name) { \
177 if (Diags) \
178 Diags->Report(diag::err_pch_langopt_mismatch) \
179 << Description << LangOpts.Name << ExistingLangOpts.Name; \
180 return true; \
181 }
182
183#define VALUE_LANGOPT(Name, Bits, Default, Description) \
184 if (ExistingLangOpts.Name != LangOpts.Name) { \
185 if (Diags) \
186 Diags->Report(diag::err_pch_langopt_value_mismatch) \
187 << Description; \
188 return true; \
189 }
190
191#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
192 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
193 if (Diags) \
194 Diags->Report(diag::err_pch_langopt_value_mismatch) \
195 << Description; \
196 return true; \
197 }
198
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000199#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
200 if (!AllowCompatibleDifferences) \
201 LANGOPT(Name, Bits, Default, Description)
202
203#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
204 if (!AllowCompatibleDifferences) \
205 ENUM_LANGOPT(Name, Bits, Default, Description)
206
Guy Benyei11169dd2012-12-18 14:30:41 +0000207#define BENIGN_LANGOPT(Name, Bits, Default, Description)
208#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
209#include "clang/Basic/LangOptions.def"
210
211 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
212 if (Diags)
213 Diags->Report(diag::err_pch_langopt_value_mismatch)
214 << "target Objective-C runtime";
215 return true;
216 }
217
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000218 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
219 LangOpts.CommentOpts.BlockCommandNames) {
220 if (Diags)
221 Diags->Report(diag::err_pch_langopt_value_mismatch)
222 << "block command names";
223 return true;
224 }
225
Guy Benyei11169dd2012-12-18 14:30:41 +0000226 return false;
227}
228
229/// \brief Compare the given set of target options against an existing set of
230/// target options.
231///
232/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
233///
234/// \returns true if the target options mis-match, false otherwise.
235static bool checkTargetOptions(const TargetOptions &TargetOpts,
236 const TargetOptions &ExistingTargetOpts,
237 DiagnosticsEngine *Diags) {
238#define CHECK_TARGET_OPT(Field, Name) \
239 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
240 if (Diags) \
241 Diags->Report(diag::err_pch_targetopt_mismatch) \
242 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
243 return true; \
244 }
245
246 CHECK_TARGET_OPT(Triple, "target");
247 CHECK_TARGET_OPT(CPU, "target CPU");
248 CHECK_TARGET_OPT(ABI, "target ABI");
Guy Benyei11169dd2012-12-18 14:30:41 +0000249#undef CHECK_TARGET_OPT
250
251 // Compare feature sets.
252 SmallVector<StringRef, 4> ExistingFeatures(
253 ExistingTargetOpts.FeaturesAsWritten.begin(),
254 ExistingTargetOpts.FeaturesAsWritten.end());
255 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
256 TargetOpts.FeaturesAsWritten.end());
257 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
258 std::sort(ReadFeatures.begin(), ReadFeatures.end());
259
260 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
261 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
262 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
263 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
264 ++ExistingIdx;
265 ++ReadIdx;
266 continue;
267 }
268
269 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
270 if (Diags)
271 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
272 << false << ReadFeatures[ReadIdx];
273 return true;
274 }
275
276 if (Diags)
277 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
278 << true << ExistingFeatures[ExistingIdx];
279 return true;
280 }
281
282 if (ExistingIdx < ExistingN) {
283 if (Diags)
284 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
285 << true << ExistingFeatures[ExistingIdx];
286 return true;
287 }
288
289 if (ReadIdx < ReadN) {
290 if (Diags)
291 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
292 << false << ReadFeatures[ReadIdx];
293 return true;
294 }
295
296 return false;
297}
298
299bool
300PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000301 bool Complain,
302 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000303 const LangOptions &ExistingLangOpts = PP.getLangOpts();
304 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000305 Complain ? &Reader.Diags : nullptr,
306 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000307}
308
309bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
310 bool Complain) {
311 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
312 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000313 Complain? &Reader.Diags : nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000314}
315
316namespace {
317 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
318 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000319 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
320 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000321}
322
Ben Langmuirb92de022014-04-29 16:25:26 +0000323static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
324 DiagnosticsEngine &Diags,
325 bool Complain) {
326 typedef DiagnosticsEngine::Level Level;
327
328 // Check current mappings for new -Werror mappings, and the stored mappings
329 // for cases that were explicitly mapped to *not* be errors that are now
330 // errors because of options like -Werror.
331 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
332
333 for (DiagnosticsEngine *MappingSource : MappingSources) {
334 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
335 diag::kind DiagID = DiagIDMappingPair.first;
336 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
337 if (CurLevel < DiagnosticsEngine::Error)
338 continue; // not significant
339 Level StoredLevel =
340 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
341 if (StoredLevel < DiagnosticsEngine::Error) {
342 if (Complain)
343 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
344 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
345 return true;
346 }
347 }
348 }
349
350 return false;
351}
352
Alp Tokerac4e8e52014-06-22 21:58:33 +0000353static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
354 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
355 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
356 return true;
357 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000358}
359
360static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
361 DiagnosticsEngine &Diags,
362 bool IsSystem, bool Complain) {
363 // Top-level options
364 if (IsSystem) {
365 if (Diags.getSuppressSystemWarnings())
366 return false;
367 // If -Wsystem-headers was not enabled before, be conservative
368 if (StoredDiags.getSuppressSystemWarnings()) {
369 if (Complain)
370 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
371 return true;
372 }
373 }
374
375 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
376 if (Complain)
377 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
378 return true;
379 }
380
381 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
382 !StoredDiags.getEnableAllWarnings()) {
383 if (Complain)
384 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
385 return true;
386 }
387
388 if (isExtHandlingFromDiagsError(Diags) &&
389 !isExtHandlingFromDiagsError(StoredDiags)) {
390 if (Complain)
391 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
392 return true;
393 }
394
395 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
396}
397
398bool PCHValidator::ReadDiagnosticOptions(
399 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
400 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
401 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
402 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000403 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000404 // This should never fail, because we would have processed these options
405 // before writing them to an ASTFile.
406 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
407
408 ModuleManager &ModuleMgr = Reader.getModuleManager();
409 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
410
411 // If the original import came from a file explicitly generated by the user,
412 // don't check the diagnostic mappings.
413 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000414 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000415 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
416 // the transitive closure of its imports, since unrelated modules cannot be
417 // imported until after this module finishes validation.
418 ModuleFile *TopImport = *ModuleMgr.rbegin();
419 while (!TopImport->ImportedBy.empty())
420 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000421 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000422 return false;
423
424 StringRef ModuleName = TopImport->ModuleName;
425 assert(!ModuleName.empty() && "diagnostic options read before module name");
426
427 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
428 assert(M && "missing module");
429
430 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
431 // contains the union of their flags.
432 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
433}
434
Guy Benyei11169dd2012-12-18 14:30:41 +0000435/// \brief Collect the macro definitions provided by the given preprocessor
436/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000437static void
438collectMacroDefinitions(const PreprocessorOptions &PPOpts,
439 MacroDefinitionsMap &Macros,
440 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000441 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
442 StringRef Macro = PPOpts.Macros[I].first;
443 bool IsUndef = PPOpts.Macros[I].second;
444
445 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
446 StringRef MacroName = MacroPair.first;
447 StringRef MacroBody = MacroPair.second;
448
449 // For an #undef'd macro, we only care about the name.
450 if (IsUndef) {
451 if (MacroNames && !Macros.count(MacroName))
452 MacroNames->push_back(MacroName);
453
454 Macros[MacroName] = std::make_pair("", true);
455 continue;
456 }
457
458 // For a #define'd macro, figure out the actual definition.
459 if (MacroName.size() == Macro.size())
460 MacroBody = "1";
461 else {
462 // Note: GCC drops anything following an end-of-line character.
463 StringRef::size_type End = MacroBody.find_first_of("\n\r");
464 MacroBody = MacroBody.substr(0, End);
465 }
466
467 if (MacroNames && !Macros.count(MacroName))
468 MacroNames->push_back(MacroName);
469 Macros[MacroName] = std::make_pair(MacroBody, false);
470 }
471}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000472
Guy Benyei11169dd2012-12-18 14:30:41 +0000473/// \brief Check the preprocessor options deserialized from the control block
474/// against the preprocessor options in an existing preprocessor.
475///
476/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
477static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
478 const PreprocessorOptions &ExistingPPOpts,
479 DiagnosticsEngine *Diags,
480 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000481 std::string &SuggestedPredefines,
482 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000483 // Check macro definitions.
484 MacroDefinitionsMap ASTFileMacros;
485 collectMacroDefinitions(PPOpts, ASTFileMacros);
486 MacroDefinitionsMap ExistingMacros;
487 SmallVector<StringRef, 4> ExistingMacroNames;
488 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
489
490 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
491 // Dig out the macro definition in the existing preprocessor options.
492 StringRef MacroName = ExistingMacroNames[I];
493 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
494
495 // Check whether we know anything about this macro name or not.
496 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
497 = ASTFileMacros.find(MacroName);
498 if (Known == ASTFileMacros.end()) {
499 // FIXME: Check whether this identifier was referenced anywhere in the
500 // AST file. If so, we should reject the AST file. Unfortunately, this
501 // information isn't in the control block. What shall we do about it?
502
503 if (Existing.second) {
504 SuggestedPredefines += "#undef ";
505 SuggestedPredefines += MacroName.str();
506 SuggestedPredefines += '\n';
507 } else {
508 SuggestedPredefines += "#define ";
509 SuggestedPredefines += MacroName.str();
510 SuggestedPredefines += ' ';
511 SuggestedPredefines += Existing.first.str();
512 SuggestedPredefines += '\n';
513 }
514 continue;
515 }
516
517 // If the macro was defined in one but undef'd in the other, we have a
518 // conflict.
519 if (Existing.second != Known->second.second) {
520 if (Diags) {
521 Diags->Report(diag::err_pch_macro_def_undef)
522 << MacroName << Known->second.second;
523 }
524 return true;
525 }
526
527 // If the macro was #undef'd in both, or if the macro bodies are identical,
528 // it's fine.
529 if (Existing.second || Existing.first == Known->second.first)
530 continue;
531
532 // The macro bodies differ; complain.
533 if (Diags) {
534 Diags->Report(diag::err_pch_macro_def_conflict)
535 << MacroName << Known->second.first << Existing.first;
536 }
537 return true;
538 }
539
540 // Check whether we're using predefines.
541 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
542 if (Diags) {
543 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
544 }
545 return true;
546 }
547
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000548 // Detailed record is important since it is used for the module cache hash.
549 if (LangOpts.Modules &&
550 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
551 if (Diags) {
552 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
553 }
554 return true;
555 }
556
Guy Benyei11169dd2012-12-18 14:30:41 +0000557 // Compute the #include and #include_macros lines we need.
558 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
559 StringRef File = ExistingPPOpts.Includes[I];
560 if (File == ExistingPPOpts.ImplicitPCHInclude)
561 continue;
562
563 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
564 != PPOpts.Includes.end())
565 continue;
566
567 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000568 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000569 SuggestedPredefines += "\"\n";
570 }
571
572 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
573 StringRef File = ExistingPPOpts.MacroIncludes[I];
574 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
575 File)
576 != PPOpts.MacroIncludes.end())
577 continue;
578
579 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000580 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000581 SuggestedPredefines += "\"\n##\n";
582 }
583
584 return false;
585}
586
587bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
588 bool Complain,
589 std::string &SuggestedPredefines) {
590 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
591
592 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000593 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000594 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000595 SuggestedPredefines,
596 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000597}
598
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000599/// Check the header search options deserialized from the control block
600/// against the header search options in an existing preprocessor.
601///
602/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
603static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
604 StringRef SpecificModuleCachePath,
605 StringRef ExistingModuleCachePath,
606 DiagnosticsEngine *Diags,
607 const LangOptions &LangOpts) {
608 if (LangOpts.Modules) {
609 if (SpecificModuleCachePath != ExistingModuleCachePath) {
610 if (Diags)
611 Diags->Report(diag::err_pch_modulecache_mismatch)
612 << SpecificModuleCachePath << ExistingModuleCachePath;
613 return true;
614 }
615 }
616
617 return false;
618}
619
620bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
621 StringRef SpecificModuleCachePath,
622 bool Complain) {
623 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
624 PP.getHeaderSearchInfo().getModuleCachePath(),
625 Complain ? &Reader.Diags : nullptr,
626 PP.getLangOpts());
627}
628
Guy Benyei11169dd2012-12-18 14:30:41 +0000629void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
630 PP.setCounterValue(Value);
631}
632
633//===----------------------------------------------------------------------===//
634// AST reader implementation
635//===----------------------------------------------------------------------===//
636
Adrian Prantlc4091aa2015-02-20 19:44:52 +0000637void ASTReader::InitStreamFileWithModule(llvm::MemoryBufferRef Buffer,
638 llvm::BitstreamReader &StreamFile) {
639 if (auto OF = llvm::object::ObjectFile::createObjectFile(Buffer)) {
640 bool IsCOFF = isa<llvm::object::COFFObjectFile>(OF.get().get());
641 // Find the clang AST section in the container.
642 for (auto &Section : OF->get()->sections()) {
643 StringRef Name;
644 Section.getName(Name);
645 if ((!IsCOFF && Name == "__clangast") ||
646 ( IsCOFF && Name == "clangast")) {
647 StringRef Buf;
648 Section.getContents(Buf);
649 return StreamFile.init((const unsigned char*)Buf.begin(),
650 (const unsigned char*)Buf.end());
651 }
652 }
653 }
654 StreamFile.init((const unsigned char *)Buffer.getBufferStart(),
655 (const unsigned char *)Buffer.getBufferEnd());
656}
657
Nico Weber824285e2014-05-08 04:26:47 +0000658void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
659 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000660 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000661 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000662}
663
664
665
666unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
667 return serialization::ComputeHash(Sel);
668}
669
670
671std::pair<unsigned, unsigned>
672ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000673 using namespace llvm::support;
674 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
675 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000676 return std::make_pair(KeyLen, DataLen);
677}
678
679ASTSelectorLookupTrait::internal_key_type
680ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000681 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000682 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000683 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
684 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
685 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000686 if (N == 0)
687 return SelTable.getNullarySelector(FirstII);
688 else if (N == 1)
689 return SelTable.getUnarySelector(FirstII);
690
691 SmallVector<IdentifierInfo *, 16> Args;
692 Args.push_back(FirstII);
693 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000694 Args.push_back(Reader.getLocalIdentifier(
695 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000696
697 return SelTable.getSelector(N, Args.data());
698}
699
700ASTSelectorLookupTrait::data_type
701ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
702 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000703 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000704
705 data_type Result;
706
Justin Bogner57ba0b22014-03-28 22:03:24 +0000707 Result.ID = Reader.getGlobalSelectorID(
708 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000709 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
710 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
711 Result.InstanceBits = FullInstanceBits & 0x3;
712 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
713 Result.FactoryBits = FullFactoryBits & 0x3;
714 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
715 unsigned NumInstanceMethods = FullInstanceBits >> 3;
716 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000717
718 // Load instance methods
719 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000720 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
721 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000722 Result.Instance.push_back(Method);
723 }
724
725 // Load factory methods
726 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000727 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
728 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000729 Result.Factory.push_back(Method);
730 }
731
732 return Result;
733}
734
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000735unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
736 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000737}
738
739std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000740ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000741 using namespace llvm::support;
742 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
743 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000744 return std::make_pair(KeyLen, DataLen);
745}
746
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000747ASTIdentifierLookupTraitBase::internal_key_type
748ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000749 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000750 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000751}
752
Douglas Gregordcf25082013-02-11 18:16:18 +0000753/// \brief Whether the given identifier is "interesting".
754static bool isInterestingIdentifier(IdentifierInfo &II) {
755 return II.isPoisoned() ||
756 II.isExtensionToken() ||
757 II.getObjCOrBuiltinID() ||
758 II.hasRevertedTokenIDToIdentifier() ||
759 II.hadMacroDefinition() ||
760 II.getFETokenInfo<void>();
761}
762
Guy Benyei11169dd2012-12-18 14:30:41 +0000763IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
764 const unsigned char* d,
765 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000766 using namespace llvm::support;
767 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000768 bool IsInteresting = RawID & 0x01;
769
770 // Wipe out the "is interesting" bit.
771 RawID = RawID >> 1;
772
773 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
774 if (!IsInteresting) {
775 // For uninteresting identifiers, just build the IdentifierInfo
776 // and associate it with the persistent ID.
777 IdentifierInfo *II = KnownII;
778 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000779 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000780 KnownII = II;
781 }
782 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000783 if (!II->isFromAST()) {
784 bool WasInteresting = isInterestingIdentifier(*II);
785 II->setIsFromAST();
786 if (WasInteresting)
787 II->setChangedSinceDeserialization();
788 }
789 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000790 return II;
791 }
792
Justin Bogner57ba0b22014-03-28 22:03:24 +0000793 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
794 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000795 bool CPlusPlusOperatorKeyword = Bits & 0x01;
796 Bits >>= 1;
797 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
798 Bits >>= 1;
799 bool Poisoned = Bits & 0x01;
800 Bits >>= 1;
801 bool ExtensionToken = Bits & 0x01;
802 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000803 bool hasSubmoduleMacros = Bits & 0x01;
804 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000805 bool hadMacroDefinition = Bits & 0x01;
806 Bits >>= 1;
807
808 assert(Bits == 0 && "Extra bits in the identifier?");
809 DataLen -= 8;
810
811 // Build the IdentifierInfo itself and link the identifier ID with
812 // the new IdentifierInfo.
813 IdentifierInfo *II = KnownII;
814 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000815 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000816 KnownII = II;
817 }
818 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000819 if (!II->isFromAST()) {
820 bool WasInteresting = isInterestingIdentifier(*II);
821 II->setIsFromAST();
822 if (WasInteresting)
823 II->setChangedSinceDeserialization();
824 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000825
826 // Set or check the various bits in the IdentifierInfo structure.
827 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000828 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000829 II->RevertTokenIDToIdentifier();
830 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
831 assert(II->isExtensionToken() == ExtensionToken &&
832 "Incorrect extension token flag");
833 (void)ExtensionToken;
834 if (Poisoned)
835 II->setIsPoisoned(true);
836 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
837 "Incorrect C++ operator keyword flag");
838 (void)CPlusPlusOperatorKeyword;
839
840 // If this identifier is a macro, deserialize the macro
841 // definition.
842 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000843 uint32_t MacroDirectivesOffset =
844 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000845 DataLen -= 4;
846 SmallVector<uint32_t, 8> LocalMacroIDs;
847 if (hasSubmoduleMacros) {
Richard Smithdaa69e02014-07-25 04:40:03 +0000848 while (true) {
849 uint32_t LocalMacroID =
850 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000851 DataLen -= 4;
Richard Smithdaa69e02014-07-25 04:40:03 +0000852 if (LocalMacroID == 0xdeadbeef) break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000853 LocalMacroIDs.push_back(LocalMacroID);
854 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000855 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000856
Richard Smithe842a472014-10-22 02:05:46 +0000857 if (F.Kind == MK_ImplicitModule || F.Kind == MK_ExplicitModule) {
Richard Smith49f906a2014-03-01 00:08:04 +0000858 // Macro definitions are stored from newest to oldest, so reverse them
859 // before registering them.
860 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000861 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000862 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
863 unsigned Size = 1;
864
865 static const uint32_t HasOverridesFlag = 0x80000000U;
866 if (I + 1 != E && (I[1] & HasOverridesFlag))
867 Size += 1 + (I[1] & ~HasOverridesFlag);
868
869 MacroSizes.push_back(Size);
870 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000871 }
Richard Smith49f906a2014-03-01 00:08:04 +0000872
873 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
874 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
875 SE = MacroSizes.rend();
876 SI != SE; ++SI) {
877 I -= *SI;
878
879 uint32_t LocalMacroID = *I;
Craig Topper00bbdcf2014-06-28 23:22:23 +0000880 ArrayRef<uint32_t> Overrides;
Richard Smith49f906a2014-03-01 00:08:04 +0000881 if (*SI != 1)
882 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
883 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
884 }
885 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000886 } else {
887 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
888 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000889 }
890
891 Reader.SetIdentifierInfo(ID, II);
892
893 // Read all of the declarations visible at global scope with this
894 // name.
895 if (DataLen > 0) {
896 SmallVector<uint32_t, 4> DeclIDs;
897 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000898 DeclIDs.push_back(Reader.getGlobalDeclID(
899 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000900 Reader.SetGloballyVisibleDecls(II, DeclIDs);
901 }
902
903 return II;
904}
905
906unsigned
907ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
908 llvm::FoldingSetNodeID ID;
909 ID.AddInteger(Key.Kind);
910
911 switch (Key.Kind) {
912 case DeclarationName::Identifier:
913 case DeclarationName::CXXLiteralOperatorName:
914 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
915 break;
916 case DeclarationName::ObjCZeroArgSelector:
917 case DeclarationName::ObjCOneArgSelector:
918 case DeclarationName::ObjCMultiArgSelector:
919 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
920 break;
921 case DeclarationName::CXXOperatorName:
922 ID.AddInteger((OverloadedOperatorKind)Key.Data);
923 break;
924 case DeclarationName::CXXConstructorName:
925 case DeclarationName::CXXDestructorName:
926 case DeclarationName::CXXConversionFunctionName:
927 case DeclarationName::CXXUsingDirective:
928 break;
929 }
930
931 return ID.ComputeHash();
932}
933
934ASTDeclContextNameLookupTrait::internal_key_type
935ASTDeclContextNameLookupTrait::GetInternalKey(
936 const external_key_type& Name) const {
937 DeclNameKey Key;
938 Key.Kind = Name.getNameKind();
939 switch (Name.getNameKind()) {
940 case DeclarationName::Identifier:
941 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
942 break;
943 case DeclarationName::ObjCZeroArgSelector:
944 case DeclarationName::ObjCOneArgSelector:
945 case DeclarationName::ObjCMultiArgSelector:
946 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
947 break;
948 case DeclarationName::CXXOperatorName:
949 Key.Data = Name.getCXXOverloadedOperator();
950 break;
951 case DeclarationName::CXXLiteralOperatorName:
952 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
953 break;
954 case DeclarationName::CXXConstructorName:
955 case DeclarationName::CXXDestructorName:
956 case DeclarationName::CXXConversionFunctionName:
957 case DeclarationName::CXXUsingDirective:
958 Key.Data = 0;
959 break;
960 }
961
962 return Key;
963}
964
965std::pair<unsigned, unsigned>
966ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000967 using namespace llvm::support;
968 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
969 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000970 return std::make_pair(KeyLen, DataLen);
971}
972
973ASTDeclContextNameLookupTrait::internal_key_type
974ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000975 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000976
977 DeclNameKey Key;
978 Key.Kind = (DeclarationName::NameKind)*d++;
979 switch (Key.Kind) {
980 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000981 Key.Data = (uint64_t)Reader.getLocalIdentifier(
982 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000983 break;
984 case DeclarationName::ObjCZeroArgSelector:
985 case DeclarationName::ObjCOneArgSelector:
986 case DeclarationName::ObjCMultiArgSelector:
987 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000988 (uint64_t)Reader.getLocalSelector(
989 F, endian::readNext<uint32_t, little, unaligned>(
990 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000991 break;
992 case DeclarationName::CXXOperatorName:
993 Key.Data = *d++; // OverloadedOperatorKind
994 break;
995 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000996 Key.Data = (uint64_t)Reader.getLocalIdentifier(
997 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000998 break;
999 case DeclarationName::CXXConstructorName:
1000 case DeclarationName::CXXDestructorName:
1001 case DeclarationName::CXXConversionFunctionName:
1002 case DeclarationName::CXXUsingDirective:
1003 Key.Data = 0;
1004 break;
1005 }
1006
1007 return Key;
1008}
1009
1010ASTDeclContextNameLookupTrait::data_type
1011ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
1012 const unsigned char* d,
1013 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001014 using namespace llvm::support;
1015 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +00001016 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
1017 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001018 return std::make_pair(Start, Start + NumDecls);
1019}
1020
1021bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001022 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00001023 const std::pair<uint64_t, uint64_t> &Offsets,
1024 DeclContextInfo &Info) {
1025 SavedStreamPosition SavedPosition(Cursor);
1026 // First the lexical decls.
1027 if (Offsets.first != 0) {
1028 Cursor.JumpToBit(Offsets.first);
1029
1030 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001031 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00001032 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001033 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001034 if (RecCode != DECL_CONTEXT_LEXICAL) {
1035 Error("Expected lexical block");
1036 return true;
1037 }
1038
Chris Lattner0e6c9402013-01-20 02:38:54 +00001039 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
1040 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +00001041 }
1042
1043 // Now the lookup table.
1044 if (Offsets.second != 0) {
1045 Cursor.JumpToBit(Offsets.second);
1046
1047 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001048 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00001049 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001050 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001051 if (RecCode != DECL_CONTEXT_VISIBLE) {
1052 Error("Expected visible lookup table block");
1053 return true;
1054 }
Justin Bognerda4e6502014-04-14 16:34:29 +00001055 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
1056 (const unsigned char *)Blob.data() + Record[0],
1057 (const unsigned char *)Blob.data() + sizeof(uint32_t),
1058 (const unsigned char *)Blob.data(),
1059 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +00001060 }
1061
1062 return false;
1063}
1064
1065void ASTReader::Error(StringRef Msg) {
1066 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +00001067 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
1068 Diag(diag::note_module_cache_path)
1069 << PP.getHeaderSearchInfo().getModuleCachePath();
1070 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001071}
1072
1073void ASTReader::Error(unsigned DiagID,
1074 StringRef Arg1, StringRef Arg2) {
1075 if (Diags.isDiagnosticInFlight())
1076 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1077 else
1078 Diag(DiagID) << Arg1 << Arg2;
1079}
1080
1081//===----------------------------------------------------------------------===//
1082// Source Manager Deserialization
1083//===----------------------------------------------------------------------===//
1084
1085/// \brief Read the line table in the source manager block.
1086/// \returns true if there was an error.
1087bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001088 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001089 unsigned Idx = 0;
1090 LineTableInfo &LineTable = SourceMgr.getLineTable();
1091
1092 // Parse the file names
1093 std::map<int, int> FileIDs;
1094 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1095 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001096 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001097 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1098 }
1099
1100 // Parse the line entries
1101 std::vector<LineEntry> Entries;
1102 while (Idx < Record.size()) {
1103 int FID = Record[Idx++];
1104 assert(FID >= 0 && "Serialized line entries for non-local file.");
1105 // Remap FileID from 1-based old view.
1106 FID += F.SLocEntryBaseID - 1;
1107
1108 // Extract the line entries
1109 unsigned NumEntries = Record[Idx++];
1110 assert(NumEntries && "Numentries is 00000");
1111 Entries.clear();
1112 Entries.reserve(NumEntries);
1113 for (unsigned I = 0; I != NumEntries; ++I) {
1114 unsigned FileOffset = Record[Idx++];
1115 unsigned LineNo = Record[Idx++];
1116 int FilenameID = FileIDs[Record[Idx++]];
1117 SrcMgr::CharacteristicKind FileKind
1118 = (SrcMgr::CharacteristicKind)Record[Idx++];
1119 unsigned IncludeOffset = Record[Idx++];
1120 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1121 FileKind, IncludeOffset));
1122 }
1123 LineTable.AddEntry(FileID::get(FID), Entries);
1124 }
1125
1126 return false;
1127}
1128
1129/// \brief Read a source manager block
1130bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1131 using namespace SrcMgr;
1132
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001133 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001134
1135 // Set the source-location entry cursor to the current position in
1136 // the stream. This cursor will be used to read the contents of the
1137 // source manager block initially, and then lazily read
1138 // source-location entries as needed.
1139 SLocEntryCursor = F.Stream;
1140
1141 // The stream itself is going to skip over the source manager block.
1142 if (F.Stream.SkipBlock()) {
1143 Error("malformed block record in AST file");
1144 return true;
1145 }
1146
1147 // Enter the source manager block.
1148 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1149 Error("malformed source manager block record in AST file");
1150 return true;
1151 }
1152
1153 RecordData Record;
1154 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001155 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1156
1157 switch (E.Kind) {
1158 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1159 case llvm::BitstreamEntry::Error:
1160 Error("malformed block record in AST file");
1161 return true;
1162 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001163 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001164 case llvm::BitstreamEntry::Record:
1165 // The interesting case.
1166 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001167 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001168
Guy Benyei11169dd2012-12-18 14:30:41 +00001169 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001170 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001171 StringRef Blob;
1172 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001173 default: // Default behavior: ignore.
1174 break;
1175
1176 case SM_SLOC_FILE_ENTRY:
1177 case SM_SLOC_BUFFER_ENTRY:
1178 case SM_SLOC_EXPANSION_ENTRY:
1179 // Once we hit one of the source location entries, we're done.
1180 return false;
1181 }
1182 }
1183}
1184
1185/// \brief If a header file is not found at the path that we expect it to be
1186/// and the PCH file was moved from its original location, try to resolve the
1187/// file by assuming that header+PCH were moved together and the header is in
1188/// the same place relative to the PCH.
1189static std::string
1190resolveFileRelativeToOriginalDir(const std::string &Filename,
1191 const std::string &OriginalDir,
1192 const std::string &CurrDir) {
1193 assert(OriginalDir != CurrDir &&
1194 "No point trying to resolve the file if the PCH dir didn't change");
1195 using namespace llvm::sys;
1196 SmallString<128> filePath(Filename);
1197 fs::make_absolute(filePath);
1198 assert(path::is_absolute(OriginalDir));
1199 SmallString<128> currPCHPath(CurrDir);
1200
1201 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1202 fileDirE = path::end(path::parent_path(filePath));
1203 path::const_iterator origDirI = path::begin(OriginalDir),
1204 origDirE = path::end(OriginalDir);
1205 // Skip the common path components from filePath and OriginalDir.
1206 while (fileDirI != fileDirE && origDirI != origDirE &&
1207 *fileDirI == *origDirI) {
1208 ++fileDirI;
1209 ++origDirI;
1210 }
1211 for (; origDirI != origDirE; ++origDirI)
1212 path::append(currPCHPath, "..");
1213 path::append(currPCHPath, fileDirI, fileDirE);
1214 path::append(currPCHPath, path::filename(Filename));
1215 return currPCHPath.str();
1216}
1217
1218bool ASTReader::ReadSLocEntry(int ID) {
1219 if (ID == 0)
1220 return false;
1221
1222 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1223 Error("source location entry ID out-of-range for AST file");
1224 return true;
1225 }
1226
1227 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1228 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001229 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001230 unsigned BaseOffset = F->SLocEntryBaseOffset;
1231
1232 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001233 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1234 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001235 Error("incorrectly-formatted source location entry in AST file");
1236 return true;
1237 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001238
Guy Benyei11169dd2012-12-18 14:30:41 +00001239 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001240 StringRef Blob;
1241 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001242 default:
1243 Error("incorrectly-formatted source location entry in AST file");
1244 return true;
1245
1246 case SM_SLOC_FILE_ENTRY: {
1247 // We will detect whether a file changed and return 'Failure' for it, but
1248 // we will also try to fail gracefully by setting up the SLocEntry.
1249 unsigned InputID = Record[4];
1250 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001251 const FileEntry *File = IF.getFile();
1252 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001253
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001254 // Note that we only check if a File was returned. If it was out-of-date
1255 // we have complained but we will continue creating a FileID to recover
1256 // gracefully.
1257 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001258 return true;
1259
1260 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1261 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1262 // This is the module's main file.
1263 IncludeLoc = getImportLocation(F);
1264 }
1265 SrcMgr::CharacteristicKind
1266 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1267 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1268 ID, BaseOffset + Record[0]);
1269 SrcMgr::FileInfo &FileInfo =
1270 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1271 FileInfo.NumCreatedFIDs = Record[5];
1272 if (Record[3])
1273 FileInfo.setHasLineDirectives();
1274
1275 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1276 unsigned NumFileDecls = Record[7];
1277 if (NumFileDecls) {
1278 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1279 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1280 NumFileDecls));
1281 }
1282
1283 const SrcMgr::ContentCache *ContentCache
1284 = SourceMgr.getOrCreateContentCache(File,
1285 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1286 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1287 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1288 unsigned Code = SLocEntryCursor.ReadCode();
1289 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001290 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001291
1292 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1293 Error("AST record has invalid code");
1294 return true;
1295 }
1296
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001297 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001298 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001299 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001300 }
1301
1302 break;
1303 }
1304
1305 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001306 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001307 unsigned Offset = Record[0];
1308 SrcMgr::CharacteristicKind
1309 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1310 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001311 if (IncludeLoc.isInvalid() &&
1312 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001313 IncludeLoc = getImportLocation(F);
1314 }
1315 unsigned Code = SLocEntryCursor.ReadCode();
1316 Record.clear();
1317 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001318 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001319
1320 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1321 Error("AST record has invalid code");
1322 return true;
1323 }
1324
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001325 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1326 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001327 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001328 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001329 break;
1330 }
1331
1332 case SM_SLOC_EXPANSION_ENTRY: {
1333 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1334 SourceMgr.createExpansionLoc(SpellingLoc,
1335 ReadSourceLocation(*F, Record[2]),
1336 ReadSourceLocation(*F, Record[3]),
1337 Record[4],
1338 ID,
1339 BaseOffset + Record[0]);
1340 break;
1341 }
1342 }
1343
1344 return false;
1345}
1346
1347std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1348 if (ID == 0)
1349 return std::make_pair(SourceLocation(), "");
1350
1351 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1352 Error("source location entry ID out-of-range for AST file");
1353 return std::make_pair(SourceLocation(), "");
1354 }
1355
1356 // Find which module file this entry lands in.
1357 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001358 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001359 return std::make_pair(SourceLocation(), "");
1360
1361 // FIXME: Can we map this down to a particular submodule? That would be
1362 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001363 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001364}
1365
1366/// \brief Find the location where the module F is imported.
1367SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1368 if (F->ImportLoc.isValid())
1369 return F->ImportLoc;
1370
1371 // Otherwise we have a PCH. It's considered to be "imported" at the first
1372 // location of its includer.
1373 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001374 // Main file is the importer.
1375 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1376 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001377 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001378 return F->ImportedBy[0]->FirstLoc;
1379}
1380
1381/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1382/// specified cursor. Read the abbreviations that are at the top of the block
1383/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001384bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001385 if (Cursor.EnterSubBlock(BlockID)) {
1386 Error("malformed block record in AST file");
1387 return Failure;
1388 }
1389
1390 while (true) {
1391 uint64_t Offset = Cursor.GetCurrentBitNo();
1392 unsigned Code = Cursor.ReadCode();
1393
1394 // We expect all abbrevs to be at the start of the block.
1395 if (Code != llvm::bitc::DEFINE_ABBREV) {
1396 Cursor.JumpToBit(Offset);
1397 return false;
1398 }
1399 Cursor.ReadAbbrevRecord();
1400 }
1401}
1402
Richard Smithe40f2ba2013-08-07 21:41:30 +00001403Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001404 unsigned &Idx) {
1405 Token Tok;
1406 Tok.startToken();
1407 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1408 Tok.setLength(Record[Idx++]);
1409 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1410 Tok.setIdentifierInfo(II);
1411 Tok.setKind((tok::TokenKind)Record[Idx++]);
1412 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1413 return Tok;
1414}
1415
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001416MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001417 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001418
1419 // Keep track of where we are in the stream, then jump back there
1420 // after reading this macro.
1421 SavedStreamPosition SavedPosition(Stream);
1422
1423 Stream.JumpToBit(Offset);
1424 RecordData Record;
1425 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001426 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001427
Guy Benyei11169dd2012-12-18 14:30:41 +00001428 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001429 // Advance to the next record, but if we get to the end of the block, don't
1430 // pop it (removing all the abbreviations from the cursor) since we want to
1431 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001432 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001433 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1434
1435 switch (Entry.Kind) {
1436 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1437 case llvm::BitstreamEntry::Error:
1438 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001439 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001440 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001441 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001442 case llvm::BitstreamEntry::Record:
1443 // The interesting case.
1444 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001445 }
1446
1447 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001448 Record.clear();
1449 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001450 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001451 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001452 case PP_MACRO_DIRECTIVE_HISTORY:
1453 return Macro;
1454
Guy Benyei11169dd2012-12-18 14:30:41 +00001455 case PP_MACRO_OBJECT_LIKE:
1456 case PP_MACRO_FUNCTION_LIKE: {
1457 // If we already have a macro, that means that we've hit the end
1458 // of the definition of the macro we were looking for. We're
1459 // done.
1460 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001461 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001462
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001463 unsigned NextIndex = 1; // Skip identifier ID.
1464 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001465 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001466 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001467 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001468 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001469 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001470
Guy Benyei11169dd2012-12-18 14:30:41 +00001471 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1472 // Decode function-like macro info.
1473 bool isC99VarArgs = Record[NextIndex++];
1474 bool isGNUVarArgs = Record[NextIndex++];
1475 bool hasCommaPasting = Record[NextIndex++];
1476 MacroArgs.clear();
1477 unsigned NumArgs = Record[NextIndex++];
1478 for (unsigned i = 0; i != NumArgs; ++i)
1479 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1480
1481 // Install function-like macro info.
1482 MI->setIsFunctionLike();
1483 if (isC99VarArgs) MI->setIsC99Varargs();
1484 if (isGNUVarArgs) MI->setIsGNUVarargs();
1485 if (hasCommaPasting) MI->setHasCommaPasting();
1486 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1487 PP.getPreprocessorAllocator());
1488 }
1489
Guy Benyei11169dd2012-12-18 14:30:41 +00001490 // Remember that we saw this macro last so that we add the tokens that
1491 // form its body to it.
1492 Macro = MI;
1493
1494 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1495 Record[NextIndex]) {
1496 // We have a macro definition. Register the association
1497 PreprocessedEntityID
1498 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1499 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001500 PreprocessingRecord::PPEntityID
1501 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1502 MacroDefinition *PPDef =
1503 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1504 if (PPDef)
1505 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001506 }
1507
1508 ++NumMacrosRead;
1509 break;
1510 }
1511
1512 case PP_TOKEN: {
1513 // If we see a TOKEN before a PP_MACRO_*, then the file is
1514 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001515 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001516
John McCallf413f5e2013-05-03 00:10:13 +00001517 unsigned Idx = 0;
1518 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001519 Macro->AddTokenToBody(Tok);
1520 break;
1521 }
1522 }
1523 }
1524}
1525
1526PreprocessedEntityID
1527ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1528 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1529 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1530 assert(I != M.PreprocessedEntityRemap.end()
1531 && "Invalid index into preprocessed entity index remap");
1532
1533 return LocalID + I->second;
1534}
1535
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001536unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1537 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001538}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001539
Guy Benyei11169dd2012-12-18 14:30:41 +00001540HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001541HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1542 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
Richard Smith7ed1bc92014-12-05 22:42:13 +00001543 FE->getName(), /*Imported*/false };
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001544 return ikey;
1545}
Guy Benyei11169dd2012-12-18 14:30:41 +00001546
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001547bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1548 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001549 return false;
1550
Richard Smith7ed1bc92014-12-05 22:42:13 +00001551 if (llvm::sys::path::is_absolute(a.Filename) &&
1552 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001553 return true;
1554
Guy Benyei11169dd2012-12-18 14:30:41 +00001555 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001556 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001557 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1558 if (!Key.Imported)
1559 return FileMgr.getFile(Key.Filename);
1560
1561 std::string Resolved = Key.Filename;
1562 Reader.ResolveImportedPath(M, Resolved);
1563 return FileMgr.getFile(Resolved);
1564 };
1565
1566 const FileEntry *FEA = GetFile(a);
1567 const FileEntry *FEB = GetFile(b);
1568 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001569}
1570
1571std::pair<unsigned, unsigned>
1572HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001573 using namespace llvm::support;
1574 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001575 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001576 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001577}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001578
1579HeaderFileInfoTrait::internal_key_type
1580HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001581 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001582 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001583 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1584 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001585 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001586 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001587 return ikey;
1588}
1589
Guy Benyei11169dd2012-12-18 14:30:41 +00001590HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001591HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001592 unsigned DataLen) {
1593 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001594 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001595 HeaderFileInfo HFI;
1596 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001597 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1598 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001599 HFI.isImport = (Flags >> 5) & 0x01;
1600 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1601 HFI.DirInfo = (Flags >> 2) & 0x03;
1602 HFI.Resolved = (Flags >> 1) & 0x01;
1603 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001604 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1605 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1606 M, endian::readNext<uint32_t, little, unaligned>(d));
1607 if (unsigned FrameworkOffset =
1608 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001609 // The framework offset is 1 greater than the actual offset,
1610 // since 0 is used as an indicator for "no framework name".
1611 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1612 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1613 }
1614
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001615 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001616 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001617 if (LocalSMID) {
1618 // This header is part of a module. Associate it with the module to enable
1619 // implicit module import.
1620 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1621 Module *Mod = Reader.getSubmodule(GlobalSMID);
1622 HFI.isModuleHeader = true;
1623 FileManager &FileMgr = Reader.getFileManager();
1624 ModuleMap &ModMap =
1625 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001626 // FIXME: This information should be propagated through the
1627 // SUBMODULE_HEADER etc records rather than from here.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001628 // FIXME: We don't ever mark excluded headers.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001629 std::string Filename = key.Filename;
1630 if (key.Imported)
1631 Reader.ResolveImportedPath(M, Filename);
1632 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Hans Wennborg0101b542014-12-02 02:13:09 +00001633 ModMap.addHeader(Mod, H, HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001634 }
1635 }
1636
Guy Benyei11169dd2012-12-18 14:30:41 +00001637 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1638 (void)End;
1639
1640 // This HeaderFileInfo was externally loaded.
1641 HFI.External = true;
1642 return HFI;
1643}
1644
Richard Smith49f906a2014-03-01 00:08:04 +00001645void
1646ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1647 GlobalMacroID GMacID,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001648 ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001649 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Craig Toppera13603a2014-05-22 05:54:18 +00001650 SubmoduleID *OverrideData = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001651 if (!Overrides.empty()) {
1652 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1653 OverrideData[0] = Overrides.size();
1654 for (unsigned I = 0; I != Overrides.size(); ++I)
1655 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1656 }
1657 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001658}
1659
1660void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1661 ModuleFile *M,
1662 uint64_t MacroDirectivesOffset) {
1663 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1664 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001665}
1666
1667void ASTReader::ReadDefinedMacros() {
1668 // Note that we are loading defined macros.
1669 Deserializing Macros(this);
1670
1671 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1672 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001673 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001674
1675 // If there was no preprocessor block, skip this file.
1676 if (!MacroCursor.getBitStreamReader())
1677 continue;
1678
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001679 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001680 Cursor.JumpToBit((*I)->MacroStartOffset);
1681
1682 RecordData Record;
1683 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001684 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1685
1686 switch (E.Kind) {
1687 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1688 case llvm::BitstreamEntry::Error:
1689 Error("malformed block record in AST file");
1690 return;
1691 case llvm::BitstreamEntry::EndBlock:
1692 goto NextCursor;
1693
1694 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001695 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001696 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001697 default: // Default behavior: ignore.
1698 break;
1699
1700 case PP_MACRO_OBJECT_LIKE:
1701 case PP_MACRO_FUNCTION_LIKE:
1702 getLocalIdentifier(**I, Record[0]);
1703 break;
1704
1705 case PP_TOKEN:
1706 // Ignore tokens.
1707 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001708 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001709 break;
1710 }
1711 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001712 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001713 }
1714}
1715
1716namespace {
1717 /// \brief Visitor class used to look up identifirs in an AST file.
1718 class IdentifierLookupVisitor {
1719 StringRef Name;
1720 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001721 unsigned &NumIdentifierLookups;
1722 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001723 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001724
Guy Benyei11169dd2012-12-18 14:30:41 +00001725 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001726 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1727 unsigned &NumIdentifierLookups,
1728 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001729 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001730 NumIdentifierLookups(NumIdentifierLookups),
1731 NumIdentifierLookupHits(NumIdentifierLookupHits),
1732 Found()
1733 {
1734 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001735
1736 static bool visit(ModuleFile &M, void *UserData) {
1737 IdentifierLookupVisitor *This
1738 = static_cast<IdentifierLookupVisitor *>(UserData);
1739
1740 // If we've already searched this module file, skip it now.
1741 if (M.Generation <= This->PriorGeneration)
1742 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001743
Guy Benyei11169dd2012-12-18 14:30:41 +00001744 ASTIdentifierLookupTable *IdTable
1745 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1746 if (!IdTable)
1747 return false;
1748
1749 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1750 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001751 ++This->NumIdentifierLookups;
1752 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001753 if (Pos == IdTable->end())
1754 return false;
1755
1756 // Dereferencing the iterator has the effect of building the
1757 // IdentifierInfo node and populating it with the various
1758 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001759 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001760 This->Found = *Pos;
1761 return true;
1762 }
1763
1764 // \brief Retrieve the identifier info found within the module
1765 // files.
1766 IdentifierInfo *getIdentifierInfo() const { return Found; }
1767 };
1768}
1769
1770void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1771 // Note that we are loading an identifier.
1772 Deserializing AnIdentifier(this);
1773
1774 unsigned PriorGeneration = 0;
1775 if (getContext().getLangOpts().Modules)
1776 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001777
1778 // If there is a global index, look there first to determine which modules
1779 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001780 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001781 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001782 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001783 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1784 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001785 }
1786 }
1787
Douglas Gregor7211ac12013-01-25 23:32:03 +00001788 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001789 NumIdentifierLookups,
1790 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001791 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001792 markIdentifierUpToDate(&II);
1793}
1794
1795void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1796 if (!II)
1797 return;
1798
1799 II->setOutOfDate(false);
1800
1801 // Update the generation for this identifier.
1802 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001803 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001804}
1805
Richard Smith49f906a2014-03-01 00:08:04 +00001806struct ASTReader::ModuleMacroInfo {
1807 SubmoduleID SubModID;
1808 MacroInfo *MI;
1809 SubmoduleID *Overrides;
1810 // FIXME: Remove this.
1811 ModuleFile *F;
1812
1813 bool isDefine() const { return MI; }
1814
1815 SubmoduleID getSubmoduleID() const { return SubModID; }
1816
Craig Topper00bbdcf2014-06-28 23:22:23 +00001817 ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
Richard Smith49f906a2014-03-01 00:08:04 +00001818 if (!Overrides)
Craig Topper00bbdcf2014-06-28 23:22:23 +00001819 return None;
Richard Smith49f906a2014-03-01 00:08:04 +00001820 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1821 }
1822
Richard Smithdaa69e02014-07-25 04:40:03 +00001823 MacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
Richard Smith49f906a2014-03-01 00:08:04 +00001824 if (!MI)
Richard Smithdaa69e02014-07-25 04:40:03 +00001825 return PP.AllocateUndefMacroDirective(ImportLoc, SubModID,
1826 getOverriddenSubmodules());
1827 return PP.AllocateDefMacroDirective(MI, ImportLoc, SubModID,
1828 getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00001829 }
1830};
1831
1832ASTReader::ModuleMacroInfo *
1833ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1834 ModuleMacroInfo Info;
1835
1836 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1837 if (ID & 1) {
1838 // Macro undefinition.
1839 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
Craig Toppera13603a2014-05-22 05:54:18 +00001840 Info.MI = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001841 } else {
1842 // Macro definition.
1843 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1844 assert(GMacID);
1845
1846 // If this macro has already been loaded, don't do so again.
1847 // FIXME: This is highly dubious. Multiple macro definitions can have the
1848 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1849 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
Craig Toppera13603a2014-05-22 05:54:18 +00001850 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001851
1852 Info.MI = getMacro(GMacID);
1853 Info.SubModID = Info.MI->getOwningModuleID();
1854 }
1855 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1856 Info.F = PMInfo.M;
1857
1858 return new (Context) ModuleMacroInfo(Info);
1859}
1860
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001861void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1862 const PendingMacroInfo &PMInfo) {
1863 assert(II);
1864
Richard Smithe842a472014-10-22 02:05:46 +00001865 if (PMInfo.M->Kind != MK_ImplicitModule &&
1866 PMInfo.M->Kind != MK_ExplicitModule) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001867 installPCHMacroDirectives(II, *PMInfo.M,
1868 PMInfo.PCHMacroData.MacroDirectivesOffset);
1869 return;
1870 }
Richard Smith49f906a2014-03-01 00:08:04 +00001871
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001872 // Module Macro.
1873
Richard Smith49f906a2014-03-01 00:08:04 +00001874 ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1875 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001876 return;
1877
Richard Smith49f906a2014-03-01 00:08:04 +00001878 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1879 if (Owner && Owner->NameVisibility == Module::Hidden) {
1880 // Macros in the owning module are hidden. Just remember this macro to
1881 // install if we make this module visible.
1882 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1883 } else {
Richard Smithdaa69e02014-07-25 04:40:03 +00001884 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001885 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001886}
1887
1888void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1889 ModuleFile &M, uint64_t Offset) {
Richard Smithe842a472014-10-22 02:05:46 +00001890 assert(M.Kind != MK_ImplicitModule && M.Kind != MK_ExplicitModule);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001891
1892 BitstreamCursor &Cursor = M.MacroCursor;
1893 SavedStreamPosition SavedPosition(Cursor);
1894 Cursor.JumpToBit(Offset);
1895
1896 llvm::BitstreamEntry Entry =
1897 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1898 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1899 Error("malformed block record in AST file");
1900 return;
1901 }
1902
1903 RecordData Record;
1904 PreprocessorRecordTypes RecType =
1905 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1906 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1907 Error("malformed block record in AST file");
1908 return;
1909 }
1910
1911 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001912 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001913 unsigned Idx = 0, N = Record.size();
1914 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001915 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001916 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001917 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1918 switch (K) {
1919 case MacroDirective::MD_Define: {
1920 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1921 MacroInfo *MI = getMacro(GMacID);
Richard Smithdaa69e02014-07-25 04:40:03 +00001922 SubmoduleID ImportedFrom = Record[Idx++];
1923 bool IsAmbiguous = Record[Idx++];
1924 llvm::SmallVector<unsigned, 4> Overrides;
1925 if (ImportedFrom) {
1926 Overrides.insert(Overrides.end(),
1927 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1928 Idx += Overrides.size() + 1;
1929 }
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001930 DefMacroDirective *DefMD =
Richard Smithdaa69e02014-07-25 04:40:03 +00001931 PP.AllocateDefMacroDirective(MI, Loc, ImportedFrom, Overrides);
1932 DefMD->setAmbiguous(IsAmbiguous);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001933 MD = DefMD;
1934 break;
1935 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001936 case MacroDirective::MD_Undefine: {
1937 SubmoduleID ImportedFrom = Record[Idx++];
1938 llvm::SmallVector<unsigned, 4> Overrides;
1939 if (ImportedFrom) {
1940 Overrides.insert(Overrides.end(),
1941 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1942 Idx += Overrides.size() + 1;
1943 }
1944 MD = PP.AllocateUndefMacroDirective(Loc, ImportedFrom, Overrides);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001945 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001946 }
1947 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001948 bool isPublic = Record[Idx++];
1949 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1950 break;
1951 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001952
1953 if (!Latest)
1954 Latest = MD;
1955 if (Earliest)
1956 Earliest->setPrevious(MD);
1957 Earliest = MD;
1958 }
1959
1960 PP.setLoadedMacroDirective(II, Latest);
1961}
1962
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001963/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001964/// modules.
1965static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001966 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001967 assert(PrevMI && NewMI);
Craig Toppera13603a2014-05-22 05:54:18 +00001968 Module *PrevOwner = nullptr;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001969 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1970 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001971 SourceManager &SrcMgr = Reader.getSourceManager();
1972 bool PrevInSystem
1973 = PrevOwner? PrevOwner->IsSystem
1974 : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1975 bool NewInSystem
1976 = NewOwner? NewOwner->IsSystem
1977 : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1978 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001979 return false;
Douglas Gregor5e461192013-06-07 22:56:11 +00001980 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001981}
1982
Richard Smith49f906a2014-03-01 00:08:04 +00001983void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001984 SourceLocation ImportLoc,
Richard Smith49f906a2014-03-01 00:08:04 +00001985 AmbiguousMacros &Ambig,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001986 ArrayRef<SubmoduleID> Overrides) {
Richard Smith49f906a2014-03-01 00:08:04 +00001987 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1988 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001989
Richard Smith49f906a2014-03-01 00:08:04 +00001990 // If this macro is not yet visible, remove it from the hidden names list.
Richard Smithbb853c72014-08-13 01:23:33 +00001991 // It won't be there if we're in the middle of making the owner visible.
Richard Smith49f906a2014-03-01 00:08:04 +00001992 Module *Owner = getSubmodule(OwnerID);
Richard Smithbb853c72014-08-13 01:23:33 +00001993 auto HiddenIt = HiddenNamesMap.find(Owner);
1994 if (HiddenIt != HiddenNamesMap.end()) {
1995 HiddenNames &Hidden = HiddenIt->second;
1996 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1997 if (HI != Hidden.HiddenMacros.end()) {
1998 // Register the macro now so we don't lose it when we re-export.
1999 PP.appendMacroDirective(II, HI->second->import(PP, ImportLoc));
Richard Smithdaa69e02014-07-25 04:40:03 +00002000
Richard Smithbb853c72014-08-13 01:23:33 +00002001 auto SubOverrides = HI->second->getOverriddenSubmodules();
2002 Hidden.HiddenMacros.erase(HI);
2003 removeOverriddenMacros(II, ImportLoc, Ambig, SubOverrides);
2004 }
Richard Smith49f906a2014-03-01 00:08:04 +00002005 }
2006
2007 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00002008 Ambig.erase(
2009 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
2010 return MD->getInfo()->getOwningModuleID() == OwnerID;
2011 }),
2012 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00002013 }
2014}
2015
2016ASTReader::AmbiguousMacros *
2017ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00002018 SourceLocation ImportLoc,
Craig Topper00bbdcf2014-06-28 23:22:23 +00002019 ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002020 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00002021 if (!Prev && Overrides.empty())
Craig Toppera13603a2014-05-22 05:54:18 +00002022 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00002023
Craig Toppera13603a2014-05-22 05:54:18 +00002024 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective()
2025 : nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00002026 if (PrevDef && PrevDef->isAmbiguous()) {
2027 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
2028 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
2029 Ambig.push_back(PrevDef);
2030
Richard Smithdaa69e02014-07-25 04:40:03 +00002031 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00002032
2033 if (!Ambig.empty())
2034 return &Ambig;
2035
2036 AmbiguousMacroDefs.erase(II);
2037 } else {
2038 // There's no ambiguity yet. Maybe we're introducing one.
Benjamin Kramer834652a2014-05-03 18:44:26 +00002039 AmbiguousMacros Ambig;
Richard Smith49f906a2014-03-01 00:08:04 +00002040 if (PrevDef)
2041 Ambig.push_back(PrevDef);
2042
Richard Smithdaa69e02014-07-25 04:40:03 +00002043 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00002044
2045 if (!Ambig.empty()) {
2046 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
Benjamin Kramer834652a2014-05-03 18:44:26 +00002047 std::swap(Result, Ambig);
Richard Smith49f906a2014-03-01 00:08:04 +00002048 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002049 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002050 }
Richard Smith49f906a2014-03-01 00:08:04 +00002051
2052 // We ended up with no ambiguity.
Craig Toppera13603a2014-05-22 05:54:18 +00002053 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00002054}
2055
2056void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
Richard Smithdaa69e02014-07-25 04:40:03 +00002057 Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00002058 assert(II && Owner);
2059
2060 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
Richard Smithdaa69e02014-07-25 04:40:03 +00002061 if (ImportLoc.isInvalid()) {
Richard Smith49f906a2014-03-01 00:08:04 +00002062 // FIXME: If we made macros from this module visible but didn't provide a
2063 // source location for the import, we don't have a location for the macro.
2064 // Use the location at which the containing module file was first imported
2065 // for now.
2066 ImportLoc = MMI->F->DirectImportLoc;
Richard Smith56be7542014-03-21 00:33:59 +00002067 assert(ImportLoc.isValid() && "no import location for a visible macro?");
Richard Smith49f906a2014-03-01 00:08:04 +00002068 }
2069
Benjamin Kramer834652a2014-05-03 18:44:26 +00002070 AmbiguousMacros *Prev =
Richard Smithdaa69e02014-07-25 04:40:03 +00002071 removeOverriddenMacros(II, ImportLoc, MMI->getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00002072
Richard Smith49f906a2014-03-01 00:08:04 +00002073 // Create a synthetic macro definition corresponding to the import (or null
2074 // if this was an undefinition of the macro).
Richard Smithdaa69e02014-07-25 04:40:03 +00002075 MacroDirective *Imported = MMI->import(PP, ImportLoc);
2076 DefMacroDirective *MD = dyn_cast<DefMacroDirective>(Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002077
2078 // If there's no ambiguity, just install the macro.
2079 if (!Prev) {
Richard Smithdaa69e02014-07-25 04:40:03 +00002080 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002081 return;
2082 }
2083 assert(!Prev->empty());
2084
2085 if (!MD) {
2086 // We imported a #undef that didn't remove all prior definitions. The most
2087 // recent prior definition remains, and we install it in the place of the
Richard Smithdaa69e02014-07-25 04:40:03 +00002088 // imported directive, as if by a local #pragma pop_macro.
Richard Smith49f906a2014-03-01 00:08:04 +00002089 MacroInfo *NewMI = Prev->back()->getInfo();
2090 Prev->pop_back();
Richard Smithdaa69e02014-07-25 04:40:03 +00002091 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc);
2092
2093 // Install our #undef first so that we don't lose track of it. We'll replace
2094 // this with whichever macro definition ends up winning.
2095 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002096 }
2097
2098 // We're introducing a macro definition that creates or adds to an ambiguity.
2099 // We can resolve that ambiguity if this macro is token-for-token identical to
2100 // all of the existing definitions.
2101 MacroInfo *NewMI = MD->getInfo();
2102 assert(NewMI && "macro definition with no MacroInfo?");
2103 while (!Prev->empty()) {
2104 MacroInfo *PrevMI = Prev->back()->getInfo();
2105 assert(PrevMI && "macro definition with no MacroInfo?");
2106
2107 // Before marking the macros as ambiguous, check if this is a case where
2108 // both macros are in system headers. If so, we trust that the system
2109 // did not get it wrong. This also handles cases where Clang's own
2110 // headers have a different spelling of certain system macros:
2111 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
2112 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
2113 //
2114 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
2115 // overrides the system limits.h's macros, so there's no conflict here.
2116 if (NewMI != PrevMI &&
2117 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
2118 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
2119 break;
2120
2121 // The previous definition is the same as this one (or both are defined in
2122 // system modules so we can assume they're equivalent); we don't need to
2123 // track it any more.
2124 Prev->pop_back();
2125 }
2126
2127 if (!Prev->empty())
2128 MD->setAmbiguous(true);
2129
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002130 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002131}
2132
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002133ASTReader::InputFileInfo
2134ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002135 // Go find this input file.
2136 BitstreamCursor &Cursor = F.InputFilesCursor;
2137 SavedStreamPosition SavedPosition(Cursor);
2138 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2139
2140 unsigned Code = Cursor.ReadCode();
2141 RecordData Record;
2142 StringRef Blob;
2143
2144 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2145 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2146 "invalid record type for input file");
2147 (void)Result;
2148
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002149 std::string Filename;
2150 off_t StoredSize;
2151 time_t StoredTime;
2152 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002153
Ben Langmuir198c1682014-03-07 07:27:49 +00002154 assert(Record[0] == ID && "Bogus stored ID or offset");
2155 StoredSize = static_cast<off_t>(Record[1]);
2156 StoredTime = static_cast<time_t>(Record[2]);
2157 Overridden = static_cast<bool>(Record[3]);
2158 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002159 ResolveImportedPath(F, Filename);
2160
Hans Wennborg73945142014-03-14 17:45:06 +00002161 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
2162 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002163}
2164
2165std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002166 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00002167}
2168
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002169InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002170 // If this ID is bogus, just return an empty input file.
2171 if (ID == 0 || ID > F.InputFilesLoaded.size())
2172 return InputFile();
2173
2174 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002175 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002176 return F.InputFilesLoaded[ID-1];
2177
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002178 if (F.InputFilesLoaded[ID-1].isNotFound())
2179 return InputFile();
2180
Guy Benyei11169dd2012-12-18 14:30:41 +00002181 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002182 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002183 SavedStreamPosition SavedPosition(Cursor);
2184 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2185
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002186 InputFileInfo FI = readInputFileInfo(F, ID);
2187 off_t StoredSize = FI.StoredSize;
2188 time_t StoredTime = FI.StoredTime;
2189 bool Overridden = FI.Overridden;
2190 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002191
Ben Langmuir198c1682014-03-07 07:27:49 +00002192 const FileEntry *File
2193 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
2194 : FileMgr.getFile(Filename, /*OpenFile=*/false);
2195
2196 // If we didn't find the file, resolve it relative to the
2197 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002198 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002199 F.OriginalDir != CurrentDir) {
2200 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2201 F.OriginalDir,
2202 CurrentDir);
2203 if (!Resolved.empty())
2204 File = FileMgr.getFile(Resolved);
2205 }
2206
2207 // For an overridden file, create a virtual file with the stored
2208 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00002209 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002210 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2211 }
2212
Craig Toppera13603a2014-05-22 05:54:18 +00002213 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002214 if (Complain) {
2215 std::string ErrorStr = "could not find file '";
2216 ErrorStr += Filename;
2217 ErrorStr += "' referenced by AST file";
2218 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00002219 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002220 // Record that we didn't find the file.
2221 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2222 return InputFile();
2223 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002224
Ben Langmuir198c1682014-03-07 07:27:49 +00002225 // Check if there was a request to override the contents of the file
2226 // that was part of the precompiled header. Overridding such a file
2227 // can lead to problems when lexing using the source locations from the
2228 // PCH.
2229 SourceManager &SM = getSourceManager();
2230 if (!Overridden && SM.isFileOverridden(File)) {
2231 if (Complain)
2232 Error(diag::err_fe_pch_file_overridden, Filename);
2233 // After emitting the diagnostic, recover by disabling the override so
2234 // that the original file will be used.
2235 SM.disableFileContentsOverride(File);
2236 // The FileEntry is a virtual file entry with the size of the contents
2237 // that would override the original contents. Set it to the original's
2238 // size/time.
2239 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2240 StoredSize, StoredTime);
2241 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002242
Ben Langmuir198c1682014-03-07 07:27:49 +00002243 bool IsOutOfDate = false;
2244
2245 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002246 if (!Overridden && //
2247 (StoredSize != File->getSize() ||
2248#if defined(LLVM_ON_WIN32)
2249 false
2250#else
Ben Langmuir198c1682014-03-07 07:27:49 +00002251 // In our regression testing, the Windows file system seems to
2252 // have inconsistent modification times that sometimes
2253 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00002254 //
2255 // This also happens in networked file systems, so disable this
2256 // check if validation is disabled or if we have an explicitly
2257 // built PCM file.
2258 //
2259 // FIXME: Should we also do this for PCH files? They could also
2260 // reasonably get shared across a network during a distributed build.
2261 (StoredTime != File->getModificationTime() && !DisableValidation &&
2262 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00002263#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002264 )) {
2265 if (Complain) {
2266 // Build a list of the PCH imports that got us here (in reverse).
2267 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2268 while (ImportStack.back()->ImportedBy.size() > 0)
2269 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002270
Ben Langmuir198c1682014-03-07 07:27:49 +00002271 // The top-level PCH is stale.
2272 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2273 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002274
Ben Langmuir198c1682014-03-07 07:27:49 +00002275 // Print the import stack.
2276 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2277 Diag(diag::note_pch_required_by)
2278 << Filename << ImportStack[0]->FileName;
2279 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002280 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002281 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002282 }
2283
Ben Langmuir198c1682014-03-07 07:27:49 +00002284 if (!Diags.isDiagnosticInFlight())
2285 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002286 }
2287
Ben Langmuir198c1682014-03-07 07:27:49 +00002288 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002289 }
2290
Ben Langmuir198c1682014-03-07 07:27:49 +00002291 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2292
2293 // Note that we've loaded this input file.
2294 F.InputFilesLoaded[ID-1] = IF;
2295 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002296}
2297
Richard Smith7ed1bc92014-12-05 22:42:13 +00002298/// \brief If we are loading a relocatable PCH or module file, and the filename
2299/// is not an absolute path, add the system or module root to the beginning of
2300/// the file name.
2301void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2302 // Resolve relative to the base directory, if we have one.
2303 if (!M.BaseDirectory.empty())
2304 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002305}
2306
Richard Smith7ed1bc92014-12-05 22:42:13 +00002307void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002308 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2309 return;
2310
Richard Smith7ed1bc92014-12-05 22:42:13 +00002311 SmallString<128> Buffer;
2312 llvm::sys::path::append(Buffer, Prefix, Filename);
2313 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002314}
2315
2316ASTReader::ASTReadResult
2317ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002318 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002319 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002320 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002321 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002322
2323 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2324 Error("malformed block record in AST file");
2325 return Failure;
2326 }
2327
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002328 // Should we allow the configuration of the module file to differ from the
2329 // configuration of the current translation unit in a compatible way?
2330 //
2331 // FIXME: Allow this for files explicitly specified with -include-pch too.
2332 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2333
Guy Benyei11169dd2012-12-18 14:30:41 +00002334 // Read all of the records and blocks in the control block.
2335 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002336 unsigned NumInputs = 0;
2337 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002338 while (1) {
2339 llvm::BitstreamEntry Entry = Stream.advance();
2340
2341 switch (Entry.Kind) {
2342 case llvm::BitstreamEntry::Error:
2343 Error("malformed block record in AST file");
2344 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002345 case llvm::BitstreamEntry::EndBlock: {
2346 // Validate input files.
2347 const HeaderSearchOptions &HSOpts =
2348 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002349
Richard Smitha1825302014-10-23 22:18:29 +00002350 // All user input files reside at the index range [0, NumUserInputs), and
2351 // system input files reside at [NumUserInputs, NumInputs).
Ben Langmuiracb803e2014-11-10 22:13:10 +00002352 if (!DisableValidation) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002353 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002354
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002355 // If we are reading a module, we will create a verification timestamp,
2356 // so we verify all input files. Otherwise, verify only user input
2357 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002358
2359 unsigned N = NumUserInputs;
2360 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002361 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002362 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002363 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002364 N = NumInputs;
2365
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002366 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002367 InputFile IF = getInputFile(F, I+1, Complain);
2368 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002369 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002370 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002372
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002373 if (Listener)
2374 Listener->visitModuleFile(F.FileName);
2375
Ben Langmuircb69b572014-03-07 06:40:32 +00002376 if (Listener && Listener->needsInputFileVisitation()) {
2377 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2378 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002379 for (unsigned I = 0; I < N; ++I) {
2380 bool IsSystem = I >= NumUserInputs;
2381 InputFileInfo FI = readInputFileInfo(F, I+1);
2382 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2383 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002384 }
2385
Guy Benyei11169dd2012-12-18 14:30:41 +00002386 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002387 }
2388
Chris Lattnere7b154b2013-01-19 21:39:22 +00002389 case llvm::BitstreamEntry::SubBlock:
2390 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002391 case INPUT_FILES_BLOCK_ID:
2392 F.InputFilesCursor = Stream;
2393 if (Stream.SkipBlock() || // Skip with the main cursor
2394 // Read the abbreviations
2395 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2396 Error("malformed block record in AST file");
2397 return Failure;
2398 }
2399 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002400
Guy Benyei11169dd2012-12-18 14:30:41 +00002401 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002402 if (Stream.SkipBlock()) {
2403 Error("malformed block record in AST file");
2404 return Failure;
2405 }
2406 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002407 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002408
2409 case llvm::BitstreamEntry::Record:
2410 // The interesting case.
2411 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002412 }
2413
2414 // Read and process a record.
2415 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002416 StringRef Blob;
2417 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002418 case METADATA: {
2419 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2420 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002421 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2422 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002423 return VersionMismatch;
2424 }
2425
2426 bool hasErrors = Record[5];
2427 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2428 Diag(diag::err_pch_with_compiler_errors);
2429 return HadErrors;
2430 }
2431
2432 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002433 // Relative paths in a relocatable PCH are relative to our sysroot.
2434 if (F.RelocatablePCH)
2435 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002436
2437 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002438 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002439 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2440 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002441 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002442 return VersionMismatch;
2443 }
2444 break;
2445 }
2446
Ben Langmuir487ea142014-10-23 18:05:36 +00002447 case SIGNATURE:
2448 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2449 F.Signature = Record[0];
2450 break;
2451
Guy Benyei11169dd2012-12-18 14:30:41 +00002452 case IMPORTS: {
2453 // Load each of the imported PCH files.
2454 unsigned Idx = 0, N = Record.size();
2455 while (Idx < N) {
2456 // Read information about the AST file.
2457 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2458 // The import location will be the local one for now; we will adjust
2459 // all import locations of module imports after the global source
2460 // location info are setup.
2461 SourceLocation ImportLoc =
2462 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002463 off_t StoredSize = (off_t)Record[Idx++];
2464 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002465 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002466 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002467
2468 // Load the AST file.
2469 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00002470 StoredSize, StoredModTime, StoredSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00002471 ClientLoadCapabilities)) {
2472 case Failure: return Failure;
2473 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002474 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002475 case OutOfDate: return OutOfDate;
2476 case VersionMismatch: return VersionMismatch;
2477 case ConfigurationMismatch: return ConfigurationMismatch;
2478 case HadErrors: return HadErrors;
2479 case Success: break;
2480 }
2481 }
2482 break;
2483 }
2484
2485 case LANGUAGE_OPTIONS: {
2486 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002487 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002488 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002489 ParseLanguageOptions(Record, Complain, *Listener,
2490 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002491 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002492 return ConfigurationMismatch;
2493 break;
2494 }
2495
2496 case TARGET_OPTIONS: {
2497 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2498 if (Listener && &F == *ModuleMgr.begin() &&
2499 ParseTargetOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002500 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002501 return ConfigurationMismatch;
2502 break;
2503 }
2504
2505 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002506 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002507 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002508 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002509 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002510 !DisableValidation)
2511 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002512 break;
2513 }
2514
2515 case FILE_SYSTEM_OPTIONS: {
2516 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2517 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002518 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002519 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002520 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002521 return ConfigurationMismatch;
2522 break;
2523 }
2524
2525 case HEADER_SEARCH_OPTIONS: {
2526 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2527 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002528 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002529 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002530 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002531 return ConfigurationMismatch;
2532 break;
2533 }
2534
2535 case PREPROCESSOR_OPTIONS: {
2536 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2537 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002538 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002539 ParsePreprocessorOptions(Record, Complain, *Listener,
2540 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002541 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002542 return ConfigurationMismatch;
2543 break;
2544 }
2545
2546 case ORIGINAL_FILE:
2547 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002548 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002549 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002550 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002551 break;
2552
2553 case ORIGINAL_FILE_ID:
2554 F.OriginalSourceFileID = FileID::get(Record[0]);
2555 break;
2556
2557 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002558 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002559 break;
2560
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002561 case MODULE_NAME:
2562 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002563 if (Listener)
2564 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002565 break;
2566
Richard Smith223d3f22014-12-06 03:21:08 +00002567 case MODULE_DIRECTORY: {
2568 assert(!F.ModuleName.empty() &&
2569 "MODULE_DIRECTORY found before MODULE_NAME");
2570 // If we've already loaded a module map file covering this module, we may
2571 // have a better path for it (relative to the current build).
2572 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2573 if (M && M->Directory) {
2574 // If we're implicitly loading a module, the base directory can't
2575 // change between the build and use.
2576 if (F.Kind != MK_ExplicitModule) {
2577 const DirectoryEntry *BuildDir =
2578 PP.getFileManager().getDirectory(Blob);
2579 if (!BuildDir || BuildDir != M->Directory) {
2580 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2581 Diag(diag::err_imported_module_relocated)
2582 << F.ModuleName << Blob << M->Directory->getName();
2583 return OutOfDate;
2584 }
2585 }
2586 F.BaseDirectory = M->Directory->getName();
2587 } else {
2588 F.BaseDirectory = Blob;
2589 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002590 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002591 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002592
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002593 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002594 if (ASTReadResult Result =
2595 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2596 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002597 break;
2598
Guy Benyei11169dd2012-12-18 14:30:41 +00002599 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002600 NumInputs = Record[0];
2601 NumUserInputs = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00002602 F.InputFileOffsets = (const uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002603 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002604 break;
2605 }
2606 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002607}
2608
Ben Langmuir2c9af442014-04-10 17:57:43 +00002609ASTReader::ASTReadResult
2610ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002611 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002612
2613 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2614 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002615 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002616 }
2617
2618 // Read all of the records and blocks for the AST file.
2619 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002620 while (1) {
2621 llvm::BitstreamEntry Entry = Stream.advance();
2622
2623 switch (Entry.Kind) {
2624 case llvm::BitstreamEntry::Error:
2625 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002626 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002627 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002628 // Outside of C++, we do not store a lookup map for the translation unit.
2629 // Instead, mark it as needing a lookup map to be built if this module
2630 // contains any declarations lexically within it (which it always does!).
2631 // This usually has no cost, since we very rarely need the lookup map for
2632 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002633 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002634 if (DC->hasExternalLexicalStorage() &&
2635 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002636 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002637
Ben Langmuir2c9af442014-04-10 17:57:43 +00002638 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002639 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002640 case llvm::BitstreamEntry::SubBlock:
2641 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002642 case DECLTYPES_BLOCK_ID:
2643 // We lazily load the decls block, but we want to set up the
2644 // DeclsCursor cursor to point into it. Clone our current bitcode
2645 // cursor to it, enter the block and read the abbrevs in that block.
2646 // With the main cursor, we just skip over it.
2647 F.DeclsCursor = Stream;
2648 if (Stream.SkipBlock() || // Skip with the main cursor.
2649 // Read the abbrevs.
2650 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2651 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002652 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002653 }
2654 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002655
Guy Benyei11169dd2012-12-18 14:30:41 +00002656 case PREPROCESSOR_BLOCK_ID:
2657 F.MacroCursor = Stream;
2658 if (!PP.getExternalSource())
2659 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002660
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 if (Stream.SkipBlock() ||
2662 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2663 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002664 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 }
2666 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2667 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002668
Guy Benyei11169dd2012-12-18 14:30:41 +00002669 case PREPROCESSOR_DETAIL_BLOCK_ID:
2670 F.PreprocessorDetailCursor = Stream;
2671 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002672 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002673 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002674 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002675 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002676 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002677 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002678 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2679
Guy Benyei11169dd2012-12-18 14:30:41 +00002680 if (!PP.getPreprocessingRecord())
2681 PP.createPreprocessingRecord();
2682 if (!PP.getPreprocessingRecord()->getExternalSource())
2683 PP.getPreprocessingRecord()->SetExternalSource(*this);
2684 break;
2685
2686 case SOURCE_MANAGER_BLOCK_ID:
2687 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002688 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002689 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002690
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002692 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2693 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002694 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002695
Guy Benyei11169dd2012-12-18 14:30:41 +00002696 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002697 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002698 if (Stream.SkipBlock() ||
2699 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2700 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002701 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002702 }
2703 CommentsCursors.push_back(std::make_pair(C, &F));
2704 break;
2705 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002706
Guy Benyei11169dd2012-12-18 14:30:41 +00002707 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002708 if (Stream.SkipBlock()) {
2709 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002710 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002711 }
2712 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002713 }
2714 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002715
2716 case llvm::BitstreamEntry::Record:
2717 // The interesting case.
2718 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002719 }
2720
2721 // Read and process a record.
2722 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002723 StringRef Blob;
2724 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002725 default: // Default behavior: ignore.
2726 break;
2727
2728 case TYPE_OFFSET: {
2729 if (F.LocalNumTypes != 0) {
2730 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002731 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002732 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002733 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002734 F.LocalNumTypes = Record[0];
2735 unsigned LocalBaseTypeIndex = Record[1];
2736 F.BaseTypeIndex = getTotalNumTypes();
2737
2738 if (F.LocalNumTypes > 0) {
2739 // Introduce the global -> local mapping for types within this module.
2740 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2741
2742 // Introduce the local -> global mapping for types within this module.
2743 F.TypeRemap.insertOrReplace(
2744 std::make_pair(LocalBaseTypeIndex,
2745 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002746
2747 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002748 }
2749 break;
2750 }
2751
2752 case DECL_OFFSET: {
2753 if (F.LocalNumDecls != 0) {
2754 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002755 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002756 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002757 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002758 F.LocalNumDecls = Record[0];
2759 unsigned LocalBaseDeclID = Record[1];
2760 F.BaseDeclID = getTotalNumDecls();
2761
2762 if (F.LocalNumDecls > 0) {
2763 // Introduce the global -> local mapping for declarations within this
2764 // module.
2765 GlobalDeclMap.insert(
2766 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2767
2768 // Introduce the local -> global mapping for declarations within this
2769 // module.
2770 F.DeclRemap.insertOrReplace(
2771 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2772
2773 // Introduce the global -> local mapping for declarations within this
2774 // module.
2775 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002776
Ben Langmuir52ca6782014-10-20 16:27:32 +00002777 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2778 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002779 break;
2780 }
2781
2782 case TU_UPDATE_LEXICAL: {
2783 DeclContext *TU = Context.getTranslationUnitDecl();
2784 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002785 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002786 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002787 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002788 TU->setHasExternalLexicalStorage(true);
2789 break;
2790 }
2791
2792 case UPDATE_VISIBLE: {
2793 unsigned Idx = 0;
2794 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2795 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002796 ASTDeclContextNameLookupTable::Create(
2797 (const unsigned char *)Blob.data() + Record[Idx++],
2798 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2799 (const unsigned char *)Blob.data(),
2800 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002801 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002802 auto *DC = cast<DeclContext>(D);
2803 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002804 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2805 delete LookupTable;
2806 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002807 } else
2808 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2809 break;
2810 }
2811
2812 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002813 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002814 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002815 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2816 (const unsigned char *)F.IdentifierTableData + Record[0],
2817 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2818 (const unsigned char *)F.IdentifierTableData,
2819 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002820
2821 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2822 }
2823 break;
2824
2825 case IDENTIFIER_OFFSET: {
2826 if (F.LocalNumIdentifiers != 0) {
2827 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002828 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002829 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002830 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002831 F.LocalNumIdentifiers = Record[0];
2832 unsigned LocalBaseIdentifierID = Record[1];
2833 F.BaseIdentifierID = getTotalNumIdentifiers();
2834
2835 if (F.LocalNumIdentifiers > 0) {
2836 // Introduce the global -> local mapping for identifiers within this
2837 // module.
2838 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2839 &F));
2840
2841 // Introduce the local -> global mapping for identifiers within this
2842 // module.
2843 F.IdentifierRemap.insertOrReplace(
2844 std::make_pair(LocalBaseIdentifierID,
2845 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002846
Ben Langmuir52ca6782014-10-20 16:27:32 +00002847 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2848 + F.LocalNumIdentifiers);
2849 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002850 break;
2851 }
2852
Ben Langmuir332aafe2014-01-31 01:06:56 +00002853 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002854 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002855 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002856 break;
2857
2858 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002859 if (SpecialTypes.empty()) {
2860 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2861 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2862 break;
2863 }
2864
2865 if (SpecialTypes.size() != Record.size()) {
2866 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002867 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002868 }
2869
2870 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2871 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2872 if (!SpecialTypes[I])
2873 SpecialTypes[I] = ID;
2874 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2875 // merge step?
2876 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002877 break;
2878
2879 case STATISTICS:
2880 TotalNumStatements += Record[0];
2881 TotalNumMacros += Record[1];
2882 TotalLexicalDeclContexts += Record[2];
2883 TotalVisibleDeclContexts += Record[3];
2884 break;
2885
2886 case UNUSED_FILESCOPED_DECLS:
2887 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2888 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2889 break;
2890
2891 case DELEGATING_CTORS:
2892 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2893 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2894 break;
2895
2896 case WEAK_UNDECLARED_IDENTIFIERS:
2897 if (Record.size() % 4 != 0) {
2898 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002899 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002900 }
2901
2902 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2903 // files. This isn't the way to do it :)
2904 WeakUndeclaredIdentifiers.clear();
2905
2906 // Translate the weak, undeclared identifiers into global IDs.
2907 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2908 WeakUndeclaredIdentifiers.push_back(
2909 getGlobalIdentifierID(F, Record[I++]));
2910 WeakUndeclaredIdentifiers.push_back(
2911 getGlobalIdentifierID(F, Record[I++]));
2912 WeakUndeclaredIdentifiers.push_back(
2913 ReadSourceLocation(F, Record, I).getRawEncoding());
2914 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2915 }
2916 break;
2917
Richard Smith78165b52013-01-10 23:43:47 +00002918 case LOCALLY_SCOPED_EXTERN_C_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002919 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Richard Smith78165b52013-01-10 23:43:47 +00002920 LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002921 break;
2922
2923 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002924 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002925 F.LocalNumSelectors = Record[0];
2926 unsigned LocalBaseSelectorID = Record[1];
2927 F.BaseSelectorID = getTotalNumSelectors();
2928
2929 if (F.LocalNumSelectors > 0) {
2930 // Introduce the global -> local mapping for selectors within this
2931 // module.
2932 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2933
2934 // Introduce the local -> global mapping for selectors within this
2935 // module.
2936 F.SelectorRemap.insertOrReplace(
2937 std::make_pair(LocalBaseSelectorID,
2938 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002939
2940 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002941 }
2942 break;
2943 }
2944
2945 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002946 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002947 if (Record[0])
2948 F.SelectorLookupTable
2949 = ASTSelectorLookupTable::Create(
2950 F.SelectorLookupTableData + Record[0],
2951 F.SelectorLookupTableData,
2952 ASTSelectorLookupTrait(*this, F));
2953 TotalNumMethodPoolEntries += Record[1];
2954 break;
2955
2956 case REFERENCED_SELECTOR_POOL:
2957 if (!Record.empty()) {
2958 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2959 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2960 Record[Idx++]));
2961 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2962 getRawEncoding());
2963 }
2964 }
2965 break;
2966
2967 case PP_COUNTER_VALUE:
2968 if (!Record.empty() && Listener)
2969 Listener->ReadCounter(F, Record[0]);
2970 break;
2971
2972 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002973 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002974 F.NumFileSortedDecls = Record[0];
2975 break;
2976
2977 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002978 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002979 F.LocalNumSLocEntries = Record[0];
2980 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002981 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002982 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002983 SLocSpaceSize);
2984 // Make our entry in the range map. BaseID is negative and growing, so
2985 // we invert it. Because we invert it, though, we need the other end of
2986 // the range.
2987 unsigned RangeStart =
2988 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2989 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2990 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2991
2992 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2993 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2994 GlobalSLocOffsetMap.insert(
2995 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2996 - SLocSpaceSize,&F));
2997
2998 // Initialize the remapping table.
2999 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003000 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00003001 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003002 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00003003 static_cast<int>(F.SLocEntryBaseOffset - 2)));
3004
3005 TotalNumSLocEntries += F.LocalNumSLocEntries;
3006 break;
3007 }
3008
3009 case MODULE_OFFSET_MAP: {
3010 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00003011 const unsigned char *Data = (const unsigned char*)Blob.data();
3012 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00003013
3014 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3015 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3016 F.SLocRemap.insert(std::make_pair(0U, 0));
3017 F.SLocRemap.insert(std::make_pair(2U, 1));
3018 }
3019
Guy Benyei11169dd2012-12-18 14:30:41 +00003020 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00003021 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
3022 RemapBuilder;
3023 RemapBuilder SLocRemap(F.SLocRemap);
3024 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3025 RemapBuilder MacroRemap(F.MacroRemap);
3026 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3027 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3028 RemapBuilder SelectorRemap(F.SelectorRemap);
3029 RemapBuilder DeclRemap(F.DeclRemap);
3030 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00003031
3032 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00003033 using namespace llvm::support;
3034 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00003035 StringRef Name = StringRef((const char*)Data, Len);
3036 Data += Len;
3037 ModuleFile *OM = ModuleMgr.lookup(Name);
3038 if (!OM) {
3039 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003040 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003041 }
3042
Justin Bogner57ba0b22014-03-28 22:03:24 +00003043 uint32_t SLocOffset =
3044 endian::readNext<uint32_t, little, unaligned>(Data);
3045 uint32_t IdentifierIDOffset =
3046 endian::readNext<uint32_t, little, unaligned>(Data);
3047 uint32_t MacroIDOffset =
3048 endian::readNext<uint32_t, little, unaligned>(Data);
3049 uint32_t PreprocessedEntityIDOffset =
3050 endian::readNext<uint32_t, little, unaligned>(Data);
3051 uint32_t SubmoduleIDOffset =
3052 endian::readNext<uint32_t, little, unaligned>(Data);
3053 uint32_t SelectorIDOffset =
3054 endian::readNext<uint32_t, little, unaligned>(Data);
3055 uint32_t DeclIDOffset =
3056 endian::readNext<uint32_t, little, unaligned>(Data);
3057 uint32_t TypeIndexOffset =
3058 endian::readNext<uint32_t, little, unaligned>(Data);
3059
Ben Langmuir785180e2014-10-20 16:27:30 +00003060 uint32_t None = std::numeric_limits<uint32_t>::max();
3061
3062 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3063 RemapBuilder &Remap) {
3064 if (Offset != None)
3065 Remap.insert(std::make_pair(Offset,
3066 static_cast<int>(BaseOffset - Offset)));
3067 };
3068 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3069 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3070 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3071 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3072 PreprocessedEntityRemap);
3073 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3074 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3075 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3076 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00003077
3078 // Global -> local mappings.
3079 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3080 }
3081 break;
3082 }
3083
3084 case SOURCE_MANAGER_LINE_TABLE:
3085 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003086 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003087 break;
3088
3089 case SOURCE_LOCATION_PRELOADS: {
3090 // Need to transform from the local view (1-based IDs) to the global view,
3091 // which is based off F.SLocEntryBaseID.
3092 if (!F.PreloadSLocEntries.empty()) {
3093 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003094 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003095 }
3096
3097 F.PreloadSLocEntries.swap(Record);
3098 break;
3099 }
3100
3101 case EXT_VECTOR_DECLS:
3102 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3103 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3104 break;
3105
3106 case VTABLE_USES:
3107 if (Record.size() % 3 != 0) {
3108 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003109 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003110 }
3111
3112 // Later tables overwrite earlier ones.
3113 // FIXME: Modules will have some trouble with this. This is clearly not
3114 // the right way to do this.
3115 VTableUses.clear();
3116
3117 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3118 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3119 VTableUses.push_back(
3120 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3121 VTableUses.push_back(Record[Idx++]);
3122 }
3123 break;
3124
3125 case DYNAMIC_CLASSES:
3126 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3127 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
3128 break;
3129
3130 case PENDING_IMPLICIT_INSTANTIATIONS:
3131 if (PendingInstantiations.size() % 2 != 0) {
3132 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003133 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003134 }
3135
3136 if (Record.size() % 2 != 0) {
3137 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003138 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003139 }
3140
3141 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3142 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3143 PendingInstantiations.push_back(
3144 ReadSourceLocation(F, Record, I).getRawEncoding());
3145 }
3146 break;
3147
3148 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00003149 if (Record.size() != 2) {
3150 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003151 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003152 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003153 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3154 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3155 break;
3156
3157 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003158 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3159 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3160 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003161
3162 unsigned LocalBasePreprocessedEntityID = Record[0];
3163
3164 unsigned StartingID;
3165 if (!PP.getPreprocessingRecord())
3166 PP.createPreprocessingRecord();
3167 if (!PP.getPreprocessingRecord()->getExternalSource())
3168 PP.getPreprocessingRecord()->SetExternalSource(*this);
3169 StartingID
3170 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003171 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003172 F.BasePreprocessedEntityID = StartingID;
3173
3174 if (F.NumPreprocessedEntities > 0) {
3175 // Introduce the global -> local mapping for preprocessed entities in
3176 // this module.
3177 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3178
3179 // Introduce the local -> global mapping for preprocessed entities in
3180 // this module.
3181 F.PreprocessedEntityRemap.insertOrReplace(
3182 std::make_pair(LocalBasePreprocessedEntityID,
3183 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3184 }
3185
3186 break;
3187 }
3188
3189 case DECL_UPDATE_OFFSETS: {
3190 if (Record.size() % 2 != 0) {
3191 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003192 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003193 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003194 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3195 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3196 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3197
3198 // If we've already loaded the decl, perform the updates when we finish
3199 // loading this block.
3200 if (Decl *D = GetExistingDecl(ID))
3201 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3202 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003203 break;
3204 }
3205
3206 case DECL_REPLACEMENTS: {
3207 if (Record.size() % 3 != 0) {
3208 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003209 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003210 }
3211 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3212 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3213 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3214 break;
3215 }
3216
3217 case OBJC_CATEGORIES_MAP: {
3218 if (F.LocalNumObjCCategoriesInMap != 0) {
3219 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003220 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003221 }
3222
3223 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003224 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003225 break;
3226 }
3227
3228 case OBJC_CATEGORIES:
3229 F.ObjCCategories.swap(Record);
3230 break;
3231
3232 case CXX_BASE_SPECIFIER_OFFSETS: {
3233 if (F.LocalNumCXXBaseSpecifiers != 0) {
3234 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003235 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003236 }
3237
3238 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003239 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003240 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
3241 break;
3242 }
3243
3244 case DIAG_PRAGMA_MAPPINGS:
3245 if (F.PragmaDiagMappings.empty())
3246 F.PragmaDiagMappings.swap(Record);
3247 else
3248 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3249 Record.begin(), Record.end());
3250 break;
3251
3252 case CUDA_SPECIAL_DECL_REFS:
3253 // Later tables overwrite earlier ones.
3254 // FIXME: Modules will have trouble with this.
3255 CUDASpecialDeclRefs.clear();
3256 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3257 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3258 break;
3259
3260 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003261 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003262 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003263 if (Record[0]) {
3264 F.HeaderFileInfoTable
3265 = HeaderFileInfoLookupTable::Create(
3266 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3267 (const unsigned char *)F.HeaderFileInfoTableData,
3268 HeaderFileInfoTrait(*this, F,
3269 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003270 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003271
3272 PP.getHeaderSearchInfo().SetExternalSource(this);
3273 if (!PP.getHeaderSearchInfo().getExternalLookup())
3274 PP.getHeaderSearchInfo().SetExternalLookup(this);
3275 }
3276 break;
3277 }
3278
3279 case FP_PRAGMA_OPTIONS:
3280 // Later tables overwrite earlier ones.
3281 FPPragmaOptions.swap(Record);
3282 break;
3283
3284 case OPENCL_EXTENSIONS:
3285 // Later tables overwrite earlier ones.
3286 OpenCLExtensions.swap(Record);
3287 break;
3288
3289 case TENTATIVE_DEFINITIONS:
3290 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3291 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3292 break;
3293
3294 case KNOWN_NAMESPACES:
3295 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3296 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3297 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003298
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003299 case UNDEFINED_BUT_USED:
3300 if (UndefinedButUsed.size() % 2 != 0) {
3301 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003302 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003303 }
3304
3305 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003306 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003307 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003308 }
3309 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003310 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3311 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003312 ReadSourceLocation(F, Record, I).getRawEncoding());
3313 }
3314 break;
3315
Guy Benyei11169dd2012-12-18 14:30:41 +00003316 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003317 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003318 // If we aren't loading a module (which has its own exports), make
3319 // all of the imported modules visible.
3320 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003321 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3322 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3323 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3324 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003325 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003326 }
3327 }
3328 break;
3329 }
3330
3331 case LOCAL_REDECLARATIONS: {
3332 F.RedeclarationChains.swap(Record);
3333 break;
3334 }
3335
3336 case LOCAL_REDECLARATIONS_MAP: {
3337 if (F.LocalNumRedeclarationsInMap != 0) {
3338 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003339 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003340 }
3341
3342 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003343 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003344 break;
3345 }
3346
3347 case MERGED_DECLARATIONS: {
3348 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3349 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3350 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3351 for (unsigned N = Record[Idx++]; N > 0; --N)
3352 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3353 }
3354 break;
3355 }
3356
3357 case MACRO_OFFSET: {
3358 if (F.LocalNumMacros != 0) {
3359 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003360 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003361 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003362 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003363 F.LocalNumMacros = Record[0];
3364 unsigned LocalBaseMacroID = Record[1];
3365 F.BaseMacroID = getTotalNumMacros();
3366
3367 if (F.LocalNumMacros > 0) {
3368 // Introduce the global -> local mapping for macros within this module.
3369 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3370
3371 // Introduce the local -> global mapping for macros within this module.
3372 F.MacroRemap.insertOrReplace(
3373 std::make_pair(LocalBaseMacroID,
3374 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003375
3376 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003377 }
3378 break;
3379 }
3380
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003381 case MACRO_TABLE: {
3382 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00003383 break;
3384 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00003385
3386 case LATE_PARSED_TEMPLATE: {
3387 LateParsedTemplates.append(Record.begin(), Record.end());
3388 break;
3389 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003390
3391 case OPTIMIZE_PRAGMA_OPTIONS:
3392 if (Record.size() != 1) {
3393 Error("invalid pragma optimize record");
3394 return Failure;
3395 }
3396 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3397 break;
Nico Weber72889432014-09-06 01:25:55 +00003398
3399 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3400 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3401 UnusedLocalTypedefNameCandidates.push_back(
3402 getGlobalDeclID(F, Record[I]));
3403 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003404 }
3405 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003406}
3407
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003408ASTReader::ASTReadResult
3409ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3410 const ModuleFile *ImportedBy,
3411 unsigned ClientLoadCapabilities) {
3412 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003413 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003414
Richard Smithe842a472014-10-22 02:05:46 +00003415 if (F.Kind == MK_ExplicitModule) {
3416 // For an explicitly-loaded module, we don't care whether the original
3417 // module map file exists or matches.
3418 return Success;
3419 }
3420
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003421 // Try to resolve ModuleName in the current header search context and
3422 // verify that it is found in the same module map file as we saved. If the
3423 // top-level AST file is a main file, skip this check because there is no
3424 // usable header search context.
3425 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003426 "MODULE_NAME should come before MODULE_MAP_FILE");
3427 if (F.Kind == MK_ImplicitModule &&
3428 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3429 // An implicitly-loaded module file should have its module listed in some
3430 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003431 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003432 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3433 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3434 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003435 assert(ImportedBy && "top-level import should be verified");
3436 if ((ClientLoadCapabilities & ARR_Missing) == 0)
Richard Smithe842a472014-10-22 02:05:46 +00003437 Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3438 << ImportedBy->FileName
3439 << F.ModuleMapPath;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003440 return Missing;
3441 }
3442
Richard Smithe842a472014-10-22 02:05:46 +00003443 assert(M->Name == F.ModuleName && "found module with different name");
3444
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003445 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003446 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003447 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3448 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003449 assert(ImportedBy && "top-level import should be verified");
3450 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3451 Diag(diag::err_imported_module_modmap_changed)
3452 << F.ModuleName << ImportedBy->FileName
3453 << ModMap->getName() << F.ModuleMapPath;
3454 return OutOfDate;
3455 }
3456
3457 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3458 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3459 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003460 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003461 const FileEntry *F =
3462 FileMgr.getFile(Filename, false, false);
3463 if (F == nullptr) {
3464 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3465 Error("could not find file '" + Filename +"' referenced by AST file");
3466 return OutOfDate;
3467 }
3468 AdditionalStoredMaps.insert(F);
3469 }
3470
3471 // Check any additional module map files (e.g. module.private.modulemap)
3472 // that are not in the pcm.
3473 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3474 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3475 // Remove files that match
3476 // Note: SmallPtrSet::erase is really remove
3477 if (!AdditionalStoredMaps.erase(ModMap)) {
3478 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3479 Diag(diag::err_module_different_modmap)
3480 << F.ModuleName << /*new*/0 << ModMap->getName();
3481 return OutOfDate;
3482 }
3483 }
3484 }
3485
3486 // Check any additional module map files that are in the pcm, but not
3487 // found in header search. Cases that match are already removed.
3488 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3489 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3490 Diag(diag::err_module_different_modmap)
3491 << F.ModuleName << /*not new*/1 << ModMap->getName();
3492 return OutOfDate;
3493 }
3494 }
3495
3496 if (Listener)
3497 Listener->ReadModuleMapFile(F.ModuleMapPath);
3498 return Success;
3499}
3500
3501
Douglas Gregorc1489562013-02-12 23:36:21 +00003502/// \brief Move the given method to the back of the global list of methods.
3503static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3504 // Find the entry for this selector in the method pool.
3505 Sema::GlobalMethodPool::iterator Known
3506 = S.MethodPool.find(Method->getSelector());
3507 if (Known == S.MethodPool.end())
3508 return;
3509
3510 // Retrieve the appropriate method list.
3511 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3512 : Known->second.second;
3513 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003514 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003515 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003516 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003517 Found = true;
3518 } else {
3519 // Keep searching.
3520 continue;
3521 }
3522 }
3523
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003524 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003525 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003526 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003527 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003528 }
3529}
3530
Richard Smithe657bbd2014-07-18 22:13:40 +00003531void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner,
3532 bool FromFinalization) {
3533 // FIXME: Only do this if Owner->NameVisibility == AllVisible.
Richard Smith57721ac2014-07-21 04:10:40 +00003534 for (Decl *D : Names.HiddenDecls) {
Richard Smith49f906a2014-03-01 00:08:04 +00003535 bool wasHidden = D->Hidden;
3536 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003537
Richard Smith49f906a2014-03-01 00:08:04 +00003538 if (wasHidden && SemaObj) {
3539 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3540 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003541 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003542 }
3543 }
Richard Smith49f906a2014-03-01 00:08:04 +00003544
Richard Smithe657bbd2014-07-18 22:13:40 +00003545 assert((FromFinalization || Owner->NameVisibility >= Module::MacrosVisible) &&
3546 "nothing to make visible?");
Richard Smithdaa69e02014-07-25 04:40:03 +00003547 for (const auto &Macro : Names.HiddenMacros) {
3548 if (FromFinalization)
3549 PP.appendMacroDirective(Macro.first,
3550 Macro.second->import(PP, SourceLocation()));
3551 else
3552 installImportedMacro(Macro.first, Macro.second, Owner);
3553 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003554}
3555
Richard Smith49f906a2014-03-01 00:08:04 +00003556void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003557 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003558 SourceLocation ImportLoc,
3559 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003560 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003561 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003562 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003563 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003564 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003565
3566 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003567 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003568 // there is nothing more to do.
3569 continue;
3570 }
Richard Smith49f906a2014-03-01 00:08:04 +00003571
Guy Benyei11169dd2012-12-18 14:30:41 +00003572 if (!Mod->isAvailable()) {
3573 // Modules that aren't available cannot be made visible.
3574 continue;
3575 }
3576
3577 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003578 if (NameVisibility >= Module::MacrosVisible &&
3579 Mod->NameVisibility < Module::MacrosVisible)
3580 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003581 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003582
Guy Benyei11169dd2012-12-18 14:30:41 +00003583 // If we've already deserialized any names from this module,
3584 // mark them as visible.
3585 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3586 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003587 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003588 HiddenNamesMap.erase(Hidden);
Richard Smith57721ac2014-07-21 04:10:40 +00003589 makeNamesVisible(HiddenNames.second, HiddenNames.first,
3590 /*FromFinalization*/false);
3591 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3592 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003593 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003594
Guy Benyei11169dd2012-12-18 14:30:41 +00003595 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003596 SmallVector<Module *, 16> Exports;
3597 Mod->getExportedModules(Exports);
3598 for (SmallVectorImpl<Module *>::iterator
3599 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3600 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003601 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003602 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003603 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003604
3605 // Detect any conflicts.
3606 if (Complain) {
3607 assert(ImportLoc.isValid() && "Missing import location");
3608 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3609 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3610 Diag(ImportLoc, diag::warn_module_conflict)
3611 << Mod->getFullModuleName()
3612 << Mod->Conflicts[I].Other->getFullModuleName()
3613 << Mod->Conflicts[I].Message;
3614 // FIXME: Need note where the other module was imported.
3615 }
3616 }
3617 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003618 }
3619}
3620
Douglas Gregore060e572013-01-25 01:03:03 +00003621bool ASTReader::loadGlobalIndex() {
3622 if (GlobalIndex)
3623 return false;
3624
3625 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3626 !Context.getLangOpts().Modules)
3627 return true;
3628
3629 // Try to load the global index.
3630 TriedLoadingGlobalIndex = true;
3631 StringRef ModuleCachePath
3632 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3633 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003634 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003635 if (!Result.first)
3636 return true;
3637
3638 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003639 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003640 return false;
3641}
3642
3643bool ASTReader::isGlobalIndexUnavailable() const {
3644 return Context.getLangOpts().Modules && UseGlobalIndex &&
3645 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3646}
3647
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003648static void updateModuleTimestamp(ModuleFile &MF) {
3649 // Overwrite the timestamp file contents so that file's mtime changes.
3650 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003651 std::error_code EC;
3652 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3653 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003654 return;
3655 OS << "Timestamp file\n";
3656}
3657
Guy Benyei11169dd2012-12-18 14:30:41 +00003658ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3659 ModuleKind Type,
3660 SourceLocation ImportLoc,
3661 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003662 llvm::SaveAndRestore<SourceLocation>
3663 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3664
Richard Smithd1c46742014-04-30 02:24:17 +00003665 // Defer any pending actions until we get to the end of reading the AST file.
3666 Deserializing AnASTFile(this);
3667
Guy Benyei11169dd2012-12-18 14:30:41 +00003668 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003669 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003670
3671 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003672 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003673 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003674 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003675 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003676 ClientLoadCapabilities)) {
3677 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003678 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003679 case OutOfDate:
3680 case VersionMismatch:
3681 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003682 case HadErrors: {
3683 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3684 for (const ImportedModule &IM : Loaded)
3685 LoadedSet.insert(IM.Mod);
3686
Douglas Gregor7029ce12013-03-19 00:28:20 +00003687 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003688 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003689 Context.getLangOpts().Modules
3690 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003691 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003692
3693 // If we find that any modules are unusable, the global index is going
3694 // to be out-of-date. Just remove it.
3695 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003696 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003697 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003698 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003699 case Success:
3700 break;
3701 }
3702
3703 // Here comes stuff that we only do once the entire chain is loaded.
3704
3705 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003706 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3707 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003708 M != MEnd; ++M) {
3709 ModuleFile &F = *M->Mod;
3710
3711 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003712 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3713 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003714
3715 // Once read, set the ModuleFile bit base offset and update the size in
3716 // bits of all files we've seen.
3717 F.GlobalBitOffset = TotalModulesSizeInBits;
3718 TotalModulesSizeInBits += F.SizeInBits;
3719 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3720
3721 // Preload SLocEntries.
3722 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3723 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3724 // Load it through the SourceManager and don't call ReadSLocEntry()
3725 // directly because the entry may have already been loaded in which case
3726 // calling ReadSLocEntry() directly would trigger an assertion in
3727 // SourceManager.
3728 SourceMgr.getLoadedSLocEntryByID(Index);
3729 }
3730 }
3731
Douglas Gregor603cd862013-03-22 18:50:14 +00003732 // Setup the import locations and notify the module manager that we've
3733 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003734 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3735 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003736 M != MEnd; ++M) {
3737 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003738
3739 ModuleMgr.moduleFileAccepted(&F);
3740
3741 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003742 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003743 if (!M->ImportedBy)
3744 F.ImportLoc = M->ImportLoc;
3745 else
3746 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3747 M->ImportLoc.getRawEncoding());
3748 }
3749
3750 // Mark all of the identifiers in the identifier table as being out of date,
3751 // so that various accessors know to check the loaded modules when the
3752 // identifier is used.
3753 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3754 IdEnd = PP.getIdentifierTable().end();
3755 Id != IdEnd; ++Id)
3756 Id->second->setOutOfDate(true);
3757
3758 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003759 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3760 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003761 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3762 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003763
3764 switch (Unresolved.Kind) {
3765 case UnresolvedModuleRef::Conflict:
3766 if (ResolvedMod) {
3767 Module::Conflict Conflict;
3768 Conflict.Other = ResolvedMod;
3769 Conflict.Message = Unresolved.String.str();
3770 Unresolved.Mod->Conflicts.push_back(Conflict);
3771 }
3772 continue;
3773
3774 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003775 if (ResolvedMod)
3776 Unresolved.Mod->Imports.push_back(ResolvedMod);
3777 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003778
Douglas Gregorfb912652013-03-20 21:10:35 +00003779 case UnresolvedModuleRef::Export:
3780 if (ResolvedMod || Unresolved.IsWildcard)
3781 Unresolved.Mod->Exports.push_back(
3782 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3783 continue;
3784 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003785 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003786 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003787
3788 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3789 // Might be unnecessary as use declarations are only used to build the
3790 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003791
3792 InitializeContext();
3793
Richard Smith3d8e97e2013-10-18 06:54:39 +00003794 if (SemaObj)
3795 UpdateSema();
3796
Guy Benyei11169dd2012-12-18 14:30:41 +00003797 if (DeserializationListener)
3798 DeserializationListener->ReaderInitialized(this);
3799
3800 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3801 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3802 PrimaryModule.OriginalSourceFileID
3803 = FileID::get(PrimaryModule.SLocEntryBaseID
3804 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3805
3806 // If this AST file is a precompiled preamble, then set the
3807 // preamble file ID of the source manager to the file source file
3808 // from which the preamble was built.
3809 if (Type == MK_Preamble) {
3810 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3811 } else if (Type == MK_MainFile) {
3812 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3813 }
3814 }
3815
3816 // For any Objective-C class definitions we have already loaded, make sure
3817 // that we load any additional categories.
3818 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3819 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3820 ObjCClassesLoaded[I],
3821 PreviousGeneration);
3822 }
Douglas Gregore060e572013-01-25 01:03:03 +00003823
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003824 if (PP.getHeaderSearchInfo()
3825 .getHeaderSearchOpts()
3826 .ModulesValidateOncePerBuildSession) {
3827 // Now we are certain that the module and all modules it depends on are
3828 // up to date. Create or update timestamp files for modules that are
3829 // located in the module cache (not for PCH files that could be anywhere
3830 // in the filesystem).
3831 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3832 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003833 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003834 updateModuleTimestamp(*M.Mod);
3835 }
3836 }
3837 }
3838
Guy Benyei11169dd2012-12-18 14:30:41 +00003839 return Success;
3840}
3841
Ben Langmuir487ea142014-10-23 18:05:36 +00003842static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3843
Guy Benyei11169dd2012-12-18 14:30:41 +00003844ASTReader::ASTReadResult
3845ASTReader::ReadASTCore(StringRef FileName,
3846 ModuleKind Type,
3847 SourceLocation ImportLoc,
3848 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003849 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003850 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003851 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003852 unsigned ClientLoadCapabilities) {
3853 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003854 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003855 ModuleManager::AddModuleResult AddResult
3856 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003857 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003858 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003859 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003860
Douglas Gregor7029ce12013-03-19 00:28:20 +00003861 switch (AddResult) {
3862 case ModuleManager::AlreadyLoaded:
3863 return Success;
3864
3865 case ModuleManager::NewlyLoaded:
3866 // Load module file below.
3867 break;
3868
3869 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003870 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003871 // it.
3872 if (ClientLoadCapabilities & ARR_Missing)
3873 return Missing;
3874
3875 // Otherwise, return an error.
3876 {
3877 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3878 + ErrorStr;
3879 Error(Msg);
3880 }
3881 return Failure;
3882
3883 case ModuleManager::OutOfDate:
3884 // We couldn't load the module file because it is out-of-date. If the
3885 // client can handle out-of-date, return it.
3886 if (ClientLoadCapabilities & ARR_OutOfDate)
3887 return OutOfDate;
3888
3889 // Otherwise, return an error.
3890 {
3891 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3892 + ErrorStr;
3893 Error(Msg);
3894 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003895 return Failure;
3896 }
3897
Douglas Gregor7029ce12013-03-19 00:28:20 +00003898 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003899
3900 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3901 // module?
3902 if (FileName != "-") {
3903 CurrentDir = llvm::sys::path::parent_path(FileName);
3904 if (CurrentDir.empty()) CurrentDir = ".";
3905 }
3906
3907 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003908 BitstreamCursor &Stream = F.Stream;
Adrian Prantlc4091aa2015-02-20 19:44:52 +00003909 InitStreamFileWithModule(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003910 Stream.init(&F.StreamFile);
Adrian Prantlc4091aa2015-02-20 19:44:52 +00003911 F.SizeInBits = F.StreamFile.getBitcodeBytes().getExtent() * 8;
3912
Guy Benyei11169dd2012-12-18 14:30:41 +00003913 // Sniff for the signature.
3914 if (Stream.Read(8) != 'C' ||
3915 Stream.Read(8) != 'P' ||
3916 Stream.Read(8) != 'C' ||
3917 Stream.Read(8) != 'H') {
3918 Diag(diag::err_not_a_pch_file) << FileName;
3919 return Failure;
3920 }
3921
3922 // This is used for compatibility with older PCH formats.
3923 bool HaveReadControlBlock = false;
3924
Chris Lattnerefa77172013-01-20 00:00:22 +00003925 while (1) {
3926 llvm::BitstreamEntry Entry = Stream.advance();
3927
3928 switch (Entry.Kind) {
3929 case llvm::BitstreamEntry::Error:
3930 case llvm::BitstreamEntry::EndBlock:
3931 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003932 Error("invalid record at top-level of AST file");
3933 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003934
3935 case llvm::BitstreamEntry::SubBlock:
3936 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003937 }
3938
Guy Benyei11169dd2012-12-18 14:30:41 +00003939 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003940 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003941 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3942 if (Stream.ReadBlockInfoBlock()) {
3943 Error("malformed BlockInfoBlock in AST file");
3944 return Failure;
3945 }
3946 break;
3947 case CONTROL_BLOCK_ID:
3948 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003949 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003950 case Success:
3951 break;
3952
3953 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003954 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003955 case OutOfDate: return OutOfDate;
3956 case VersionMismatch: return VersionMismatch;
3957 case ConfigurationMismatch: return ConfigurationMismatch;
3958 case HadErrors: return HadErrors;
3959 }
3960 break;
3961 case AST_BLOCK_ID:
3962 if (!HaveReadControlBlock) {
3963 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003964 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003965 return VersionMismatch;
3966 }
3967
3968 // Record that we've loaded this module.
3969 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3970 return Success;
3971
3972 default:
3973 if (Stream.SkipBlock()) {
3974 Error("malformed block record in AST file");
3975 return Failure;
3976 }
3977 break;
3978 }
3979 }
3980
3981 return Success;
3982}
3983
3984void ASTReader::InitializeContext() {
3985 // If there's a listener, notify them that we "read" the translation unit.
3986 if (DeserializationListener)
3987 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3988 Context.getTranslationUnitDecl());
3989
Guy Benyei11169dd2012-12-18 14:30:41 +00003990 // FIXME: Find a better way to deal with collisions between these
3991 // built-in types. Right now, we just ignore the problem.
3992
3993 // Load the special types.
3994 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3995 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3996 if (!Context.CFConstantStringTypeDecl)
3997 Context.setCFConstantStringType(GetType(String));
3998 }
3999
4000 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4001 QualType FileType = GetType(File);
4002 if (FileType.isNull()) {
4003 Error("FILE type is NULL");
4004 return;
4005 }
4006
4007 if (!Context.FILEDecl) {
4008 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4009 Context.setFILEDecl(Typedef->getDecl());
4010 else {
4011 const TagType *Tag = FileType->getAs<TagType>();
4012 if (!Tag) {
4013 Error("Invalid FILE type in AST file");
4014 return;
4015 }
4016 Context.setFILEDecl(Tag->getDecl());
4017 }
4018 }
4019 }
4020
4021 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4022 QualType Jmp_bufType = GetType(Jmp_buf);
4023 if (Jmp_bufType.isNull()) {
4024 Error("jmp_buf type is NULL");
4025 return;
4026 }
4027
4028 if (!Context.jmp_bufDecl) {
4029 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4030 Context.setjmp_bufDecl(Typedef->getDecl());
4031 else {
4032 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4033 if (!Tag) {
4034 Error("Invalid jmp_buf type in AST file");
4035 return;
4036 }
4037 Context.setjmp_bufDecl(Tag->getDecl());
4038 }
4039 }
4040 }
4041
4042 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4043 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4044 if (Sigjmp_bufType.isNull()) {
4045 Error("sigjmp_buf type is NULL");
4046 return;
4047 }
4048
4049 if (!Context.sigjmp_bufDecl) {
4050 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4051 Context.setsigjmp_bufDecl(Typedef->getDecl());
4052 else {
4053 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4054 assert(Tag && "Invalid sigjmp_buf type in AST file");
4055 Context.setsigjmp_bufDecl(Tag->getDecl());
4056 }
4057 }
4058 }
4059
4060 if (unsigned ObjCIdRedef
4061 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4062 if (Context.ObjCIdRedefinitionType.isNull())
4063 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4064 }
4065
4066 if (unsigned ObjCClassRedef
4067 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4068 if (Context.ObjCClassRedefinitionType.isNull())
4069 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4070 }
4071
4072 if (unsigned ObjCSelRedef
4073 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4074 if (Context.ObjCSelRedefinitionType.isNull())
4075 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4076 }
4077
4078 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4079 QualType Ucontext_tType = GetType(Ucontext_t);
4080 if (Ucontext_tType.isNull()) {
4081 Error("ucontext_t type is NULL");
4082 return;
4083 }
4084
4085 if (!Context.ucontext_tDecl) {
4086 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4087 Context.setucontext_tDecl(Typedef->getDecl());
4088 else {
4089 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4090 assert(Tag && "Invalid ucontext_t type in AST file");
4091 Context.setucontext_tDecl(Tag->getDecl());
4092 }
4093 }
4094 }
4095 }
4096
4097 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4098
4099 // If there were any CUDA special declarations, deserialize them.
4100 if (!CUDASpecialDeclRefs.empty()) {
4101 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4102 Context.setcudaConfigureCallDecl(
4103 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4104 }
Richard Smith56be7542014-03-21 00:33:59 +00004105
Guy Benyei11169dd2012-12-18 14:30:41 +00004106 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00004107 // FIXME: This does not make macro-only imports visible again. It also doesn't
4108 // make #includes mapped to module imports visible.
4109 for (auto &Import : ImportedModules) {
4110 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004111 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00004112 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00004113 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00004114 }
4115 ImportedModules.clear();
4116}
4117
4118void ASTReader::finalizeForWriting() {
Richard Smith57721ac2014-07-21 04:10:40 +00004119 while (!HiddenNamesMap.empty()) {
4120 auto HiddenNames = std::move(*HiddenNamesMap.begin());
4121 HiddenNamesMap.erase(HiddenNamesMap.begin());
4122 makeNamesVisible(HiddenNames.second, HiddenNames.first,
4123 /*FromFinalization*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004124 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004125}
4126
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004127/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
4128/// cursor into the start of the given block ID, returning false on success and
4129/// true on failure.
4130static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004131 while (1) {
4132 llvm::BitstreamEntry Entry = Cursor.advance();
4133 switch (Entry.Kind) {
4134 case llvm::BitstreamEntry::Error:
4135 case llvm::BitstreamEntry::EndBlock:
4136 return true;
4137
4138 case llvm::BitstreamEntry::Record:
4139 // Ignore top-level records.
4140 Cursor.skipRecord(Entry.ID);
4141 break;
4142
4143 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004144 if (Entry.ID == BlockID) {
4145 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004146 return true;
4147 // Found it!
4148 return false;
4149 }
4150
4151 if (Cursor.SkipBlock())
4152 return true;
4153 }
4154 }
4155}
4156
Ben Langmuir487ea142014-10-23 18:05:36 +00004157static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
4158 BitstreamCursor Stream(StreamFile);
4159 if (Stream.Read(8) != 'C' ||
4160 Stream.Read(8) != 'P' ||
4161 Stream.Read(8) != 'C' ||
4162 Stream.Read(8) != 'H') {
4163 return 0;
4164 }
4165
4166 // Scan for the CONTROL_BLOCK_ID block.
4167 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4168 return 0;
4169
4170 // Scan for SIGNATURE inside the control block.
4171 ASTReader::RecordData Record;
4172 while (1) {
4173 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4174 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
4175 Entry.Kind != llvm::BitstreamEntry::Record)
4176 return 0;
4177
4178 Record.clear();
4179 StringRef Blob;
4180 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4181 return Record[0];
4182 }
4183}
4184
Guy Benyei11169dd2012-12-18 14:30:41 +00004185/// \brief Retrieve the name of the original source file name
4186/// directly from the AST file, without actually loading the AST
4187/// file.
4188std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
4189 FileManager &FileMgr,
4190 DiagnosticsEngine &Diags) {
4191 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004192 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004193 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004194 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4195 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004196 return std::string();
4197 }
4198
4199 // Initialize the stream
4200 llvm::BitstreamReader StreamFile;
Adrian Prantlc4091aa2015-02-20 19:44:52 +00004201 InitStreamFileWithModule((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004202 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004203
4204 // Sniff for the signature.
4205 if (Stream.Read(8) != 'C' ||
4206 Stream.Read(8) != 'P' ||
4207 Stream.Read(8) != 'C' ||
4208 Stream.Read(8) != 'H') {
4209 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4210 return std::string();
4211 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004212
Chris Lattnere7b154b2013-01-19 21:39:22 +00004213 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004214 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004215 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4216 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004217 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004218
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004219 // Scan for ORIGINAL_FILE inside the control block.
4220 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004221 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004222 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004223 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4224 return std::string();
4225
4226 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4227 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4228 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004229 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004230
Guy Benyei11169dd2012-12-18 14:30:41 +00004231 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004232 StringRef Blob;
4233 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4234 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004235 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004236}
4237
4238namespace {
4239 class SimplePCHValidator : public ASTReaderListener {
4240 const LangOptions &ExistingLangOpts;
4241 const TargetOptions &ExistingTargetOpts;
4242 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004243 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004244 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004245
Guy Benyei11169dd2012-12-18 14:30:41 +00004246 public:
4247 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4248 const TargetOptions &ExistingTargetOpts,
4249 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004250 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004251 FileManager &FileMgr)
4252 : ExistingLangOpts(ExistingLangOpts),
4253 ExistingTargetOpts(ExistingTargetOpts),
4254 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004255 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004256 FileMgr(FileMgr)
4257 {
4258 }
4259
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004260 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4261 bool AllowCompatibleDifferences) override {
4262 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4263 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004264 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004265 bool ReadTargetOptions(const TargetOptions &TargetOpts,
4266 bool Complain) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004267 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004268 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004269 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4270 StringRef SpecificModuleCachePath,
4271 bool Complain) override {
4272 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4273 ExistingModuleCachePath,
4274 nullptr, ExistingLangOpts);
4275 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004276 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4277 bool Complain,
4278 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004279 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004280 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004281 }
4282 };
4283}
4284
4285bool ASTReader::readASTFileControlBlock(StringRef Filename,
4286 FileManager &FileMgr,
4287 ASTReaderListener &Listener) {
4288 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004289 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004290 if (!Buffer) {
4291 return true;
4292 }
4293
4294 // Initialize the stream
4295 llvm::BitstreamReader StreamFile;
Adrian Prantlc4091aa2015-02-20 19:44:52 +00004296 InitStreamFileWithModule((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004297 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004298
4299 // Sniff for the signature.
4300 if (Stream.Read(8) != 'C' ||
4301 Stream.Read(8) != 'P' ||
4302 Stream.Read(8) != 'C' ||
4303 Stream.Read(8) != 'H') {
4304 return true;
4305 }
4306
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004307 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004308 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004309 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004310
4311 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004312 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004313 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004314 BitstreamCursor InputFilesCursor;
4315 if (NeedsInputFiles) {
4316 InputFilesCursor = Stream;
4317 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4318 return true;
4319
4320 // Read the abbreviations
4321 while (true) {
4322 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4323 unsigned Code = InputFilesCursor.ReadCode();
4324
4325 // We expect all abbrevs to be at the start of the block.
4326 if (Code != llvm::bitc::DEFINE_ABBREV) {
4327 InputFilesCursor.JumpToBit(Offset);
4328 break;
4329 }
4330 InputFilesCursor.ReadAbbrevRecord();
4331 }
4332 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004333
4334 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004335 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004336 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004337 while (1) {
4338 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4339 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4340 return false;
4341
4342 if (Entry.Kind != llvm::BitstreamEntry::Record)
4343 return true;
4344
Guy Benyei11169dd2012-12-18 14:30:41 +00004345 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004346 StringRef Blob;
4347 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004348 switch ((ControlRecordTypes)RecCode) {
4349 case METADATA: {
4350 if (Record[0] != VERSION_MAJOR)
4351 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004352
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004353 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004354 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004355
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004356 break;
4357 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004358 case MODULE_NAME:
4359 Listener.ReadModuleName(Blob);
4360 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004361 case MODULE_DIRECTORY:
4362 ModuleDir = Blob;
4363 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004364 case MODULE_MAP_FILE: {
4365 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004366 auto Path = ReadString(Record, Idx);
4367 ResolveImportedPath(Path, ModuleDir);
4368 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004369 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004370 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004371 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004372 if (ParseLanguageOptions(Record, false, Listener,
4373 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004374 return true;
4375 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004376
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004377 case TARGET_OPTIONS:
4378 if (ParseTargetOptions(Record, false, Listener))
4379 return true;
4380 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004381
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004382 case DIAGNOSTIC_OPTIONS:
4383 if (ParseDiagnosticOptions(Record, false, Listener))
4384 return true;
4385 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004386
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004387 case FILE_SYSTEM_OPTIONS:
4388 if (ParseFileSystemOptions(Record, false, Listener))
4389 return true;
4390 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004391
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004392 case HEADER_SEARCH_OPTIONS:
4393 if (ParseHeaderSearchOptions(Record, false, Listener))
4394 return true;
4395 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004396
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004397 case PREPROCESSOR_OPTIONS: {
4398 std::string IgnoredSuggestedPredefines;
4399 if (ParsePreprocessorOptions(Record, false, Listener,
4400 IgnoredSuggestedPredefines))
4401 return true;
4402 break;
4403 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004404
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004405 case INPUT_FILE_OFFSETS: {
4406 if (!NeedsInputFiles)
4407 break;
4408
4409 unsigned NumInputFiles = Record[0];
4410 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004411 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004412 for (unsigned I = 0; I != NumInputFiles; ++I) {
4413 // Go find this input file.
4414 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004415
4416 if (isSystemFile && !NeedsSystemInputFiles)
4417 break; // the rest are system input files
4418
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004419 BitstreamCursor &Cursor = InputFilesCursor;
4420 SavedStreamPosition SavedPosition(Cursor);
4421 Cursor.JumpToBit(InputFileOffs[I]);
4422
4423 unsigned Code = Cursor.ReadCode();
4424 RecordData Record;
4425 StringRef Blob;
4426 bool shouldContinue = false;
4427 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4428 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004429 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004430 std::string Filename = Blob;
4431 ResolveImportedPath(Filename, ModuleDir);
4432 shouldContinue =
4433 Listener.visitInputFile(Filename, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004434 break;
4435 }
4436 if (!shouldContinue)
4437 break;
4438 }
4439 break;
4440 }
4441
Richard Smithd4b230b2014-10-27 23:01:16 +00004442 case IMPORTS: {
4443 if (!NeedsImports)
4444 break;
4445
4446 unsigned Idx = 0, N = Record.size();
4447 while (Idx < N) {
4448 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004449 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004450 std::string Filename = ReadString(Record, Idx);
4451 ResolveImportedPath(Filename, ModuleDir);
4452 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004453 }
4454 break;
4455 }
4456
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004457 default:
4458 // No other validation to perform.
4459 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004460 }
4461 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004462}
4463
4464
4465bool ASTReader::isAcceptableASTFile(StringRef Filename,
4466 FileManager &FileMgr,
4467 const LangOptions &LangOpts,
4468 const TargetOptions &TargetOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004469 const PreprocessorOptions &PPOpts,
4470 std::string ExistingModuleCachePath) {
4471 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4472 ExistingModuleCachePath, FileMgr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004473 return !readASTFileControlBlock(Filename, FileMgr, validator);
4474}
4475
Ben Langmuir2c9af442014-04-10 17:57:43 +00004476ASTReader::ASTReadResult
4477ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004478 // Enter the submodule block.
4479 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4480 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004481 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004482 }
4483
4484 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4485 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004486 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004487 RecordData Record;
4488 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004489 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4490
4491 switch (Entry.Kind) {
4492 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4493 case llvm::BitstreamEntry::Error:
4494 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004495 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004496 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004497 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004498 case llvm::BitstreamEntry::Record:
4499 // The interesting case.
4500 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004501 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004502
Guy Benyei11169dd2012-12-18 14:30:41 +00004503 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004504 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004505 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004506 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4507
4508 if ((Kind == SUBMODULE_METADATA) != First) {
4509 Error("submodule metadata record should be at beginning of block");
4510 return Failure;
4511 }
4512 First = false;
4513
4514 // Submodule information is only valid if we have a current module.
4515 // FIXME: Should we error on these cases?
4516 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4517 Kind != SUBMODULE_DEFINITION)
4518 continue;
4519
4520 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004521 default: // Default behavior: ignore.
4522 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004523
Richard Smith03478d92014-10-23 22:12:14 +00004524 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004525 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004526 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004527 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004528 }
Richard Smith03478d92014-10-23 22:12:14 +00004529
Chris Lattner0e6c9402013-01-20 02:38:54 +00004530 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004531 unsigned Idx = 0;
4532 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4533 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4534 bool IsFramework = Record[Idx++];
4535 bool IsExplicit = Record[Idx++];
4536 bool IsSystem = Record[Idx++];
4537 bool IsExternC = Record[Idx++];
4538 bool InferSubmodules = Record[Idx++];
4539 bool InferExplicitSubmodules = Record[Idx++];
4540 bool InferExportWildcard = Record[Idx++];
4541 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004542
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004543 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004544 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004546
Guy Benyei11169dd2012-12-18 14:30:41 +00004547 // Retrieve this (sub)module from the module map, creating it if
4548 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004549 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004550 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004551
4552 // FIXME: set the definition loc for CurrentModule, or call
4553 // ModMap.setInferredModuleAllowedBy()
4554
Guy Benyei11169dd2012-12-18 14:30:41 +00004555 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4556 if (GlobalIndex >= SubmodulesLoaded.size() ||
4557 SubmodulesLoaded[GlobalIndex]) {
4558 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004559 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004560 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004561
Douglas Gregor7029ce12013-03-19 00:28:20 +00004562 if (!ParentModule) {
4563 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4564 if (CurFile != F.File) {
4565 if (!Diags.isDiagnosticInFlight()) {
4566 Diag(diag::err_module_file_conflict)
4567 << CurrentModule->getTopLevelModuleName()
4568 << CurFile->getName()
4569 << F.File->getName();
4570 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004571 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004572 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004573 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004574
4575 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004576 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004577
Guy Benyei11169dd2012-12-18 14:30:41 +00004578 CurrentModule->IsFromModuleFile = true;
4579 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004580 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004581 CurrentModule->InferSubmodules = InferSubmodules;
4582 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4583 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004584 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004585 if (DeserializationListener)
4586 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4587
4588 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004589
Douglas Gregorfb912652013-03-20 21:10:35 +00004590 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004591 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004592 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004593 CurrentModule->UnresolvedConflicts.clear();
4594 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004595 break;
4596 }
4597
4598 case SUBMODULE_UMBRELLA_HEADER: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004599 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004600 if (!CurrentModule->getUmbrellaHeader())
4601 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4602 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004603 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4604 Error("mismatched umbrella headers in submodule");
4605 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004606 }
4607 }
4608 break;
4609 }
4610
Richard Smith202210b2014-10-24 20:23:01 +00004611 case SUBMODULE_HEADER:
4612 case SUBMODULE_EXCLUDED_HEADER:
4613 case SUBMODULE_PRIVATE_HEADER:
4614 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004615 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4616 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004617 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004618
Richard Smith202210b2014-10-24 20:23:01 +00004619 case SUBMODULE_TEXTUAL_HEADER:
4620 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4621 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4622 // them here.
4623 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004624
Guy Benyei11169dd2012-12-18 14:30:41 +00004625 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004626 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004627 break;
4628 }
4629
4630 case SUBMODULE_UMBRELLA_DIR: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004631 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004632 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004633 if (!CurrentModule->getUmbrellaDir())
4634 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4635 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004636 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4637 Error("mismatched umbrella directories in submodule");
4638 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004639 }
4640 }
4641 break;
4642 }
4643
4644 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004645 F.BaseSubmoduleID = getTotalNumSubmodules();
4646 F.LocalNumSubmodules = Record[0];
4647 unsigned LocalBaseSubmoduleID = Record[1];
4648 if (F.LocalNumSubmodules > 0) {
4649 // Introduce the global -> local mapping for submodules within this
4650 // module.
4651 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4652
4653 // Introduce the local -> global mapping for submodules within this
4654 // module.
4655 F.SubmoduleRemap.insertOrReplace(
4656 std::make_pair(LocalBaseSubmoduleID,
4657 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004658
Ben Langmuir52ca6782014-10-20 16:27:32 +00004659 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4660 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004661 break;
4662 }
4663
4664 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004665 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004666 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004667 Unresolved.File = &F;
4668 Unresolved.Mod = CurrentModule;
4669 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004670 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004671 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004672 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004673 }
4674 break;
4675 }
4676
4677 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004678 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004679 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004680 Unresolved.File = &F;
4681 Unresolved.Mod = CurrentModule;
4682 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004683 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004684 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004685 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004686 }
4687
4688 // Once we've loaded the set of exports, there's no reason to keep
4689 // the parsed, unresolved exports around.
4690 CurrentModule->UnresolvedExports.clear();
4691 break;
4692 }
4693 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004694 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004695 Context.getTargetInfo());
4696 break;
4697 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004698
4699 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004700 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004701 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004702 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004703
4704 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004705 CurrentModule->ConfigMacros.push_back(Blob.str());
4706 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004707
4708 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004709 UnresolvedModuleRef Unresolved;
4710 Unresolved.File = &F;
4711 Unresolved.Mod = CurrentModule;
4712 Unresolved.ID = Record[0];
4713 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4714 Unresolved.IsWildcard = false;
4715 Unresolved.String = Blob;
4716 UnresolvedModuleRefs.push_back(Unresolved);
4717 break;
4718 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004719 }
4720 }
4721}
4722
4723/// \brief Parse the record that corresponds to a LangOptions data
4724/// structure.
4725///
4726/// This routine parses the language options from the AST file and then gives
4727/// them to the AST listener if one is set.
4728///
4729/// \returns true if the listener deems the file unacceptable, false otherwise.
4730bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4731 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004732 ASTReaderListener &Listener,
4733 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004734 LangOptions LangOpts;
4735 unsigned Idx = 0;
4736#define LANGOPT(Name, Bits, Default, Description) \
4737 LangOpts.Name = Record[Idx++];
4738#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4739 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4740#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004741#define SANITIZER(NAME, ID) \
4742 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004743#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004744
4745 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4746 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4747 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4748
4749 unsigned Length = Record[Idx++];
4750 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4751 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004752
4753 Idx += Length;
4754
4755 // Comment options.
4756 for (unsigned N = Record[Idx++]; N; --N) {
4757 LangOpts.CommentOpts.BlockCommandNames.push_back(
4758 ReadString(Record, Idx));
4759 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004760 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004761
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004762 return Listener.ReadLanguageOptions(LangOpts, Complain,
4763 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004764}
4765
4766bool ASTReader::ParseTargetOptions(const RecordData &Record,
4767 bool Complain,
4768 ASTReaderListener &Listener) {
4769 unsigned Idx = 0;
4770 TargetOptions TargetOpts;
4771 TargetOpts.Triple = ReadString(Record, Idx);
4772 TargetOpts.CPU = ReadString(Record, Idx);
4773 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004774 for (unsigned N = Record[Idx++]; N; --N) {
4775 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4776 }
4777 for (unsigned N = Record[Idx++]; N; --N) {
4778 TargetOpts.Features.push_back(ReadString(Record, Idx));
4779 }
4780
4781 return Listener.ReadTargetOptions(TargetOpts, Complain);
4782}
4783
4784bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4785 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004786 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004787 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004788#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004789#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004790 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004791#include "clang/Basic/DiagnosticOptions.def"
4792
Richard Smith3be1cb22014-08-07 00:24:21 +00004793 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004794 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004795 for (unsigned N = Record[Idx++]; N; --N)
4796 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004797
4798 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4799}
4800
4801bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4802 ASTReaderListener &Listener) {
4803 FileSystemOptions FSOpts;
4804 unsigned Idx = 0;
4805 FSOpts.WorkingDir = ReadString(Record, Idx);
4806 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4807}
4808
4809bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4810 bool Complain,
4811 ASTReaderListener &Listener) {
4812 HeaderSearchOptions HSOpts;
4813 unsigned Idx = 0;
4814 HSOpts.Sysroot = ReadString(Record, Idx);
4815
4816 // Include entries.
4817 for (unsigned N = Record[Idx++]; N; --N) {
4818 std::string Path = ReadString(Record, Idx);
4819 frontend::IncludeDirGroup Group
4820 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004821 bool IsFramework = Record[Idx++];
4822 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004823 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004824 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004825 }
4826
4827 // System header prefixes.
4828 for (unsigned N = Record[Idx++]; N; --N) {
4829 std::string Prefix = ReadString(Record, Idx);
4830 bool IsSystemHeader = Record[Idx++];
4831 HSOpts.SystemHeaderPrefixes.push_back(
4832 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4833 }
4834
4835 HSOpts.ResourceDir = ReadString(Record, Idx);
4836 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004837 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004838 HSOpts.DisableModuleHash = Record[Idx++];
4839 HSOpts.UseBuiltinIncludes = Record[Idx++];
4840 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4841 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4842 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004843 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004844
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004845 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4846 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004847}
4848
4849bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4850 bool Complain,
4851 ASTReaderListener &Listener,
4852 std::string &SuggestedPredefines) {
4853 PreprocessorOptions PPOpts;
4854 unsigned Idx = 0;
4855
4856 // Macro definitions/undefs
4857 for (unsigned N = Record[Idx++]; N; --N) {
4858 std::string Macro = ReadString(Record, Idx);
4859 bool IsUndef = Record[Idx++];
4860 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4861 }
4862
4863 // Includes
4864 for (unsigned N = Record[Idx++]; N; --N) {
4865 PPOpts.Includes.push_back(ReadString(Record, Idx));
4866 }
4867
4868 // Macro Includes
4869 for (unsigned N = Record[Idx++]; N; --N) {
4870 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4871 }
4872
4873 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004874 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004875 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4876 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4877 PPOpts.ObjCXXARCStandardLibrary =
4878 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4879 SuggestedPredefines.clear();
4880 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4881 SuggestedPredefines);
4882}
4883
4884std::pair<ModuleFile *, unsigned>
4885ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4886 GlobalPreprocessedEntityMapType::iterator
4887 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4888 assert(I != GlobalPreprocessedEntityMap.end() &&
4889 "Corrupted global preprocessed entity map");
4890 ModuleFile *M = I->second;
4891 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4892 return std::make_pair(M, LocalIndex);
4893}
4894
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004895llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004896ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4897 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4898 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4899 Mod.NumPreprocessedEntities);
4900
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004901 return llvm::make_range(PreprocessingRecord::iterator(),
4902 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004903}
4904
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004905llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004906ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004907 return llvm::make_range(
4908 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4909 ModuleDeclIterator(this, &Mod,
4910 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004911}
4912
4913PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4914 PreprocessedEntityID PPID = Index+1;
4915 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4916 ModuleFile &M = *PPInfo.first;
4917 unsigned LocalIndex = PPInfo.second;
4918 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4919
Guy Benyei11169dd2012-12-18 14:30:41 +00004920 if (!PP.getPreprocessingRecord()) {
4921 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004922 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004923 }
4924
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004925 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4926 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4927
4928 llvm::BitstreamEntry Entry =
4929 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4930 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004931 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004932
Guy Benyei11169dd2012-12-18 14:30:41 +00004933 // Read the record.
4934 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4935 ReadSourceLocation(M, PPOffs.End));
4936 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004937 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004938 RecordData Record;
4939 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004940 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4941 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004942 switch (RecType) {
4943 case PPD_MACRO_EXPANSION: {
4944 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004945 IdentifierInfo *Name = nullptr;
4946 MacroDefinition *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004947 if (isBuiltin)
4948 Name = getLocalIdentifier(M, Record[1]);
4949 else {
4950 PreprocessedEntityID
4951 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4952 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4953 }
4954
4955 MacroExpansion *ME;
4956 if (isBuiltin)
4957 ME = new (PPRec) MacroExpansion(Name, Range);
4958 else
4959 ME = new (PPRec) MacroExpansion(Def, Range);
4960
4961 return ME;
4962 }
4963
4964 case PPD_MACRO_DEFINITION: {
4965 // Decode the identifier info and then check again; if the macro is
4966 // still defined and associated with the identifier,
4967 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4968 MacroDefinition *MD
4969 = new (PPRec) MacroDefinition(II, Range);
4970
4971 if (DeserializationListener)
4972 DeserializationListener->MacroDefinitionRead(PPID, MD);
4973
4974 return MD;
4975 }
4976
4977 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004978 const char *FullFileNameStart = Blob.data() + Record[0];
4979 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004980 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004981 if (!FullFileName.empty())
4982 File = PP.getFileManager().getFile(FullFileName);
4983
4984 // FIXME: Stable encoding
4985 InclusionDirective::InclusionKind Kind
4986 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4987 InclusionDirective *ID
4988 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004989 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004990 Record[1], Record[3],
4991 File,
4992 Range);
4993 return ID;
4994 }
4995 }
4996
4997 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4998}
4999
5000/// \brief \arg SLocMapI points at a chunk of a module that contains no
5001/// preprocessed entities or the entities it contains are not the ones we are
5002/// looking for. Find the next module that contains entities and return the ID
5003/// of the first entry.
5004PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5005 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5006 ++SLocMapI;
5007 for (GlobalSLocOffsetMapType::const_iterator
5008 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5009 ModuleFile &M = *SLocMapI->second;
5010 if (M.NumPreprocessedEntities)
5011 return M.BasePreprocessedEntityID;
5012 }
5013
5014 return getTotalNumPreprocessedEntities();
5015}
5016
5017namespace {
5018
5019template <unsigned PPEntityOffset::*PPLoc>
5020struct PPEntityComp {
5021 const ASTReader &Reader;
5022 ModuleFile &M;
5023
5024 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5025
5026 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5027 SourceLocation LHS = getLoc(L);
5028 SourceLocation RHS = getLoc(R);
5029 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5030 }
5031
5032 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5033 SourceLocation LHS = getLoc(L);
5034 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5035 }
5036
5037 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5038 SourceLocation RHS = getLoc(R);
5039 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5040 }
5041
5042 SourceLocation getLoc(const PPEntityOffset &PPE) const {
5043 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
5044 }
5045};
5046
5047}
5048
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005049PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5050 bool EndsAfter) const {
5051 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005052 return getTotalNumPreprocessedEntities();
5053
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005054 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5055 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005056 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5057 "Corrupted global sloc offset map");
5058
5059 if (SLocMapI->second->NumPreprocessedEntities == 0)
5060 return findNextPreprocessedEntity(SLocMapI);
5061
5062 ModuleFile &M = *SLocMapI->second;
5063 typedef const PPEntityOffset *pp_iterator;
5064 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5065 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5066
5067 size_t Count = M.NumPreprocessedEntities;
5068 size_t Half;
5069 pp_iterator First = pp_begin;
5070 pp_iterator PPI;
5071
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005072 if (EndsAfter) {
5073 PPI = std::upper_bound(pp_begin, pp_end, Loc,
5074 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
5075 } else {
5076 // Do a binary search manually instead of using std::lower_bound because
5077 // The end locations of entities may be unordered (when a macro expansion
5078 // is inside another macro argument), but for this case it is not important
5079 // whether we get the first macro expansion or its containing macro.
5080 while (Count > 0) {
5081 Half = Count / 2;
5082 PPI = First;
5083 std::advance(PPI, Half);
5084 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
5085 Loc)) {
5086 First = PPI;
5087 ++First;
5088 Count = Count - Half - 1;
5089 } else
5090 Count = Half;
5091 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005092 }
5093
5094 if (PPI == pp_end)
5095 return findNextPreprocessedEntity(SLocMapI);
5096
5097 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5098}
5099
Guy Benyei11169dd2012-12-18 14:30:41 +00005100/// \brief Returns a pair of [Begin, End) indices of preallocated
5101/// preprocessed entities that \arg Range encompasses.
5102std::pair<unsigned, unsigned>
5103 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5104 if (Range.isInvalid())
5105 return std::make_pair(0,0);
5106 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5107
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005108 PreprocessedEntityID BeginID =
5109 findPreprocessedEntity(Range.getBegin(), false);
5110 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005111 return std::make_pair(BeginID, EndID);
5112}
5113
5114/// \brief Optionally returns true or false if the preallocated preprocessed
5115/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005116Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005117 FileID FID) {
5118 if (FID.isInvalid())
5119 return false;
5120
5121 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5122 ModuleFile &M = *PPInfo.first;
5123 unsigned LocalIndex = PPInfo.second;
5124 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5125
5126 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
5127 if (Loc.isInvalid())
5128 return false;
5129
5130 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5131 return true;
5132 else
5133 return false;
5134}
5135
5136namespace {
5137 /// \brief Visitor used to search for information about a header file.
5138 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005139 const FileEntry *FE;
5140
David Blaikie05785d12013-02-20 22:23:23 +00005141 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005142
5143 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005144 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5145 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00005146
5147 static bool visit(ModuleFile &M, void *UserData) {
5148 HeaderFileInfoVisitor *This
5149 = static_cast<HeaderFileInfoVisitor *>(UserData);
5150
Guy Benyei11169dd2012-12-18 14:30:41 +00005151 HeaderFileInfoLookupTable *Table
5152 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5153 if (!Table)
5154 return false;
5155
5156 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00005157 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005158 if (Pos == Table->end())
5159 return false;
5160
5161 This->HFI = *Pos;
5162 return true;
5163 }
5164
David Blaikie05785d12013-02-20 22:23:23 +00005165 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005166 };
5167}
5168
5169HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005170 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005171 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005172 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005173 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005174
5175 return HeaderFileInfo();
5176}
5177
5178void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5179 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005180 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005181 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5182 ModuleFile &F = *(*I);
5183 unsigned Idx = 0;
5184 DiagStates.clear();
5185 assert(!Diag.DiagStates.empty());
5186 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5187 while (Idx < F.PragmaDiagMappings.size()) {
5188 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5189 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5190 if (DiagStateID != 0) {
5191 Diag.DiagStatePoints.push_back(
5192 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5193 FullSourceLoc(Loc, SourceMgr)));
5194 continue;
5195 }
5196
5197 assert(DiagStateID == 0);
5198 // A new DiagState was created here.
5199 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5200 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5201 DiagStates.push_back(NewState);
5202 Diag.DiagStatePoints.push_back(
5203 DiagnosticsEngine::DiagStatePoint(NewState,
5204 FullSourceLoc(Loc, SourceMgr)));
5205 while (1) {
5206 assert(Idx < F.PragmaDiagMappings.size() &&
5207 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5208 if (Idx >= F.PragmaDiagMappings.size()) {
5209 break; // Something is messed up but at least avoid infinite loop in
5210 // release build.
5211 }
5212 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5213 if (DiagID == (unsigned)-1) {
5214 break; // no more diag/map pairs for this location.
5215 }
Alp Tokerc726c362014-06-10 09:31:37 +00005216 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5217 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5218 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005219 }
5220 }
5221 }
5222}
5223
5224/// \brief Get the correct cursor and offset for loading a type.
5225ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5226 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5227 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5228 ModuleFile *M = I->second;
5229 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5230}
5231
5232/// \brief Read and return the type with the given index..
5233///
5234/// The index is the type ID, shifted and minus the number of predefs. This
5235/// routine actually reads the record corresponding to the type at the given
5236/// location. It is a helper routine for GetType, which deals with reading type
5237/// IDs.
5238QualType ASTReader::readTypeRecord(unsigned Index) {
5239 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005240 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005241
5242 // Keep track of where we are in the stream, then jump back there
5243 // after reading this type.
5244 SavedStreamPosition SavedPosition(DeclsCursor);
5245
5246 ReadingKindTracker ReadingKind(Read_Type, *this);
5247
5248 // Note that we are loading a type record.
5249 Deserializing AType(this);
5250
5251 unsigned Idx = 0;
5252 DeclsCursor.JumpToBit(Loc.Offset);
5253 RecordData Record;
5254 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005255 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005256 case TYPE_EXT_QUAL: {
5257 if (Record.size() != 2) {
5258 Error("Incorrect encoding of extended qualifier type");
5259 return QualType();
5260 }
5261 QualType Base = readType(*Loc.F, Record, Idx);
5262 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5263 return Context.getQualifiedType(Base, Quals);
5264 }
5265
5266 case TYPE_COMPLEX: {
5267 if (Record.size() != 1) {
5268 Error("Incorrect encoding of complex type");
5269 return QualType();
5270 }
5271 QualType ElemType = readType(*Loc.F, Record, Idx);
5272 return Context.getComplexType(ElemType);
5273 }
5274
5275 case TYPE_POINTER: {
5276 if (Record.size() != 1) {
5277 Error("Incorrect encoding of pointer type");
5278 return QualType();
5279 }
5280 QualType PointeeType = readType(*Loc.F, Record, Idx);
5281 return Context.getPointerType(PointeeType);
5282 }
5283
Reid Kleckner8a365022013-06-24 17:51:48 +00005284 case TYPE_DECAYED: {
5285 if (Record.size() != 1) {
5286 Error("Incorrect encoding of decayed type");
5287 return QualType();
5288 }
5289 QualType OriginalType = readType(*Loc.F, Record, Idx);
5290 QualType DT = Context.getAdjustedParameterType(OriginalType);
5291 if (!isa<DecayedType>(DT))
5292 Error("Decayed type does not decay");
5293 return DT;
5294 }
5295
Reid Kleckner0503a872013-12-05 01:23:43 +00005296 case TYPE_ADJUSTED: {
5297 if (Record.size() != 2) {
5298 Error("Incorrect encoding of adjusted type");
5299 return QualType();
5300 }
5301 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5302 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5303 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5304 }
5305
Guy Benyei11169dd2012-12-18 14:30:41 +00005306 case TYPE_BLOCK_POINTER: {
5307 if (Record.size() != 1) {
5308 Error("Incorrect encoding of block pointer type");
5309 return QualType();
5310 }
5311 QualType PointeeType = readType(*Loc.F, Record, Idx);
5312 return Context.getBlockPointerType(PointeeType);
5313 }
5314
5315 case TYPE_LVALUE_REFERENCE: {
5316 if (Record.size() != 2) {
5317 Error("Incorrect encoding of lvalue reference type");
5318 return QualType();
5319 }
5320 QualType PointeeType = readType(*Loc.F, Record, Idx);
5321 return Context.getLValueReferenceType(PointeeType, Record[1]);
5322 }
5323
5324 case TYPE_RVALUE_REFERENCE: {
5325 if (Record.size() != 1) {
5326 Error("Incorrect encoding of rvalue reference type");
5327 return QualType();
5328 }
5329 QualType PointeeType = readType(*Loc.F, Record, Idx);
5330 return Context.getRValueReferenceType(PointeeType);
5331 }
5332
5333 case TYPE_MEMBER_POINTER: {
5334 if (Record.size() != 2) {
5335 Error("Incorrect encoding of member pointer type");
5336 return QualType();
5337 }
5338 QualType PointeeType = readType(*Loc.F, Record, Idx);
5339 QualType ClassType = readType(*Loc.F, Record, Idx);
5340 if (PointeeType.isNull() || ClassType.isNull())
5341 return QualType();
5342
5343 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5344 }
5345
5346 case TYPE_CONSTANT_ARRAY: {
5347 QualType ElementType = readType(*Loc.F, Record, Idx);
5348 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5349 unsigned IndexTypeQuals = Record[2];
5350 unsigned Idx = 3;
5351 llvm::APInt Size = ReadAPInt(Record, Idx);
5352 return Context.getConstantArrayType(ElementType, Size,
5353 ASM, IndexTypeQuals);
5354 }
5355
5356 case TYPE_INCOMPLETE_ARRAY: {
5357 QualType ElementType = readType(*Loc.F, Record, Idx);
5358 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5359 unsigned IndexTypeQuals = Record[2];
5360 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5361 }
5362
5363 case TYPE_VARIABLE_ARRAY: {
5364 QualType ElementType = readType(*Loc.F, Record, Idx);
5365 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5366 unsigned IndexTypeQuals = Record[2];
5367 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5368 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5369 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5370 ASM, IndexTypeQuals,
5371 SourceRange(LBLoc, RBLoc));
5372 }
5373
5374 case TYPE_VECTOR: {
5375 if (Record.size() != 3) {
5376 Error("incorrect encoding of vector type in AST file");
5377 return QualType();
5378 }
5379
5380 QualType ElementType = readType(*Loc.F, Record, Idx);
5381 unsigned NumElements = Record[1];
5382 unsigned VecKind = Record[2];
5383 return Context.getVectorType(ElementType, NumElements,
5384 (VectorType::VectorKind)VecKind);
5385 }
5386
5387 case TYPE_EXT_VECTOR: {
5388 if (Record.size() != 3) {
5389 Error("incorrect encoding of extended vector type in AST file");
5390 return QualType();
5391 }
5392
5393 QualType ElementType = readType(*Loc.F, Record, Idx);
5394 unsigned NumElements = Record[1];
5395 return Context.getExtVectorType(ElementType, NumElements);
5396 }
5397
5398 case TYPE_FUNCTION_NO_PROTO: {
5399 if (Record.size() != 6) {
5400 Error("incorrect encoding of no-proto function type");
5401 return QualType();
5402 }
5403 QualType ResultType = readType(*Loc.F, Record, Idx);
5404 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5405 (CallingConv)Record[4], Record[5]);
5406 return Context.getFunctionNoProtoType(ResultType, Info);
5407 }
5408
5409 case TYPE_FUNCTION_PROTO: {
5410 QualType ResultType = readType(*Loc.F, Record, Idx);
5411
5412 FunctionProtoType::ExtProtoInfo EPI;
5413 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5414 /*hasregparm*/ Record[2],
5415 /*regparm*/ Record[3],
5416 static_cast<CallingConv>(Record[4]),
5417 /*produces*/ Record[5]);
5418
5419 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005420
5421 EPI.Variadic = Record[Idx++];
5422 EPI.HasTrailingReturn = Record[Idx++];
5423 EPI.TypeQuals = Record[Idx++];
5424 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005425 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005426 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005427
5428 unsigned NumParams = Record[Idx++];
5429 SmallVector<QualType, 16> ParamTypes;
5430 for (unsigned I = 0; I != NumParams; ++I)
5431 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5432
Jordan Rose5c382722013-03-08 21:51:21 +00005433 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005434 }
5435
5436 case TYPE_UNRESOLVED_USING: {
5437 unsigned Idx = 0;
5438 return Context.getTypeDeclType(
5439 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5440 }
5441
5442 case TYPE_TYPEDEF: {
5443 if (Record.size() != 2) {
5444 Error("incorrect encoding of typedef type");
5445 return QualType();
5446 }
5447 unsigned Idx = 0;
5448 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5449 QualType Canonical = readType(*Loc.F, Record, Idx);
5450 if (!Canonical.isNull())
5451 Canonical = Context.getCanonicalType(Canonical);
5452 return Context.getTypedefType(Decl, Canonical);
5453 }
5454
5455 case TYPE_TYPEOF_EXPR:
5456 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5457
5458 case TYPE_TYPEOF: {
5459 if (Record.size() != 1) {
5460 Error("incorrect encoding of typeof(type) in AST file");
5461 return QualType();
5462 }
5463 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5464 return Context.getTypeOfType(UnderlyingType);
5465 }
5466
5467 case TYPE_DECLTYPE: {
5468 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5469 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5470 }
5471
5472 case TYPE_UNARY_TRANSFORM: {
5473 QualType BaseType = readType(*Loc.F, Record, Idx);
5474 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5475 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5476 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5477 }
5478
Richard Smith74aeef52013-04-26 16:15:35 +00005479 case TYPE_AUTO: {
5480 QualType Deduced = readType(*Loc.F, Record, Idx);
5481 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005482 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005483 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005484 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005485
5486 case TYPE_RECORD: {
5487 if (Record.size() != 2) {
5488 Error("incorrect encoding of record type");
5489 return QualType();
5490 }
5491 unsigned Idx = 0;
5492 bool IsDependent = Record[Idx++];
5493 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5494 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5495 QualType T = Context.getRecordType(RD);
5496 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5497 return T;
5498 }
5499
5500 case TYPE_ENUM: {
5501 if (Record.size() != 2) {
5502 Error("incorrect encoding of enum type");
5503 return QualType();
5504 }
5505 unsigned Idx = 0;
5506 bool IsDependent = Record[Idx++];
5507 QualType T
5508 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5509 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5510 return T;
5511 }
5512
5513 case TYPE_ATTRIBUTED: {
5514 if (Record.size() != 3) {
5515 Error("incorrect encoding of attributed type");
5516 return QualType();
5517 }
5518 QualType modifiedType = readType(*Loc.F, Record, Idx);
5519 QualType equivalentType = readType(*Loc.F, Record, Idx);
5520 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5521 return Context.getAttributedType(kind, modifiedType, equivalentType);
5522 }
5523
5524 case TYPE_PAREN: {
5525 if (Record.size() != 1) {
5526 Error("incorrect encoding of paren type");
5527 return QualType();
5528 }
5529 QualType InnerType = readType(*Loc.F, Record, Idx);
5530 return Context.getParenType(InnerType);
5531 }
5532
5533 case TYPE_PACK_EXPANSION: {
5534 if (Record.size() != 2) {
5535 Error("incorrect encoding of pack expansion type");
5536 return QualType();
5537 }
5538 QualType Pattern = readType(*Loc.F, Record, Idx);
5539 if (Pattern.isNull())
5540 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005541 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005542 if (Record[1])
5543 NumExpansions = Record[1] - 1;
5544 return Context.getPackExpansionType(Pattern, NumExpansions);
5545 }
5546
5547 case TYPE_ELABORATED: {
5548 unsigned Idx = 0;
5549 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5550 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5551 QualType NamedType = readType(*Loc.F, Record, Idx);
5552 return Context.getElaboratedType(Keyword, NNS, NamedType);
5553 }
5554
5555 case TYPE_OBJC_INTERFACE: {
5556 unsigned Idx = 0;
5557 ObjCInterfaceDecl *ItfD
5558 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5559 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5560 }
5561
5562 case TYPE_OBJC_OBJECT: {
5563 unsigned Idx = 0;
5564 QualType Base = readType(*Loc.F, Record, Idx);
5565 unsigned NumProtos = Record[Idx++];
5566 SmallVector<ObjCProtocolDecl*, 4> Protos;
5567 for (unsigned I = 0; I != NumProtos; ++I)
5568 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5569 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5570 }
5571
5572 case TYPE_OBJC_OBJECT_POINTER: {
5573 unsigned Idx = 0;
5574 QualType Pointee = readType(*Loc.F, Record, Idx);
5575 return Context.getObjCObjectPointerType(Pointee);
5576 }
5577
5578 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5579 unsigned Idx = 0;
5580 QualType Parm = readType(*Loc.F, Record, Idx);
5581 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005582 return Context.getSubstTemplateTypeParmType(
5583 cast<TemplateTypeParmType>(Parm),
5584 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005585 }
5586
5587 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5588 unsigned Idx = 0;
5589 QualType Parm = readType(*Loc.F, Record, Idx);
5590 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5591 return Context.getSubstTemplateTypeParmPackType(
5592 cast<TemplateTypeParmType>(Parm),
5593 ArgPack);
5594 }
5595
5596 case TYPE_INJECTED_CLASS_NAME: {
5597 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5598 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5599 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5600 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005601 const Type *T = nullptr;
5602 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5603 if (const Type *Existing = DI->getTypeForDecl()) {
5604 T = Existing;
5605 break;
5606 }
5607 }
5608 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005609 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005610 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5611 DI->setTypeForDecl(T);
5612 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005613 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005614 }
5615
5616 case TYPE_TEMPLATE_TYPE_PARM: {
5617 unsigned Idx = 0;
5618 unsigned Depth = Record[Idx++];
5619 unsigned Index = Record[Idx++];
5620 bool Pack = Record[Idx++];
5621 TemplateTypeParmDecl *D
5622 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5623 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5624 }
5625
5626 case TYPE_DEPENDENT_NAME: {
5627 unsigned Idx = 0;
5628 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5629 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5630 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5631 QualType Canon = readType(*Loc.F, Record, Idx);
5632 if (!Canon.isNull())
5633 Canon = Context.getCanonicalType(Canon);
5634 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5635 }
5636
5637 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5638 unsigned Idx = 0;
5639 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5640 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5641 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5642 unsigned NumArgs = Record[Idx++];
5643 SmallVector<TemplateArgument, 8> Args;
5644 Args.reserve(NumArgs);
5645 while (NumArgs--)
5646 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5647 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5648 Args.size(), Args.data());
5649 }
5650
5651 case TYPE_DEPENDENT_SIZED_ARRAY: {
5652 unsigned Idx = 0;
5653
5654 // ArrayType
5655 QualType ElementType = readType(*Loc.F, Record, Idx);
5656 ArrayType::ArraySizeModifier ASM
5657 = (ArrayType::ArraySizeModifier)Record[Idx++];
5658 unsigned IndexTypeQuals = Record[Idx++];
5659
5660 // DependentSizedArrayType
5661 Expr *NumElts = ReadExpr(*Loc.F);
5662 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5663
5664 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5665 IndexTypeQuals, Brackets);
5666 }
5667
5668 case TYPE_TEMPLATE_SPECIALIZATION: {
5669 unsigned Idx = 0;
5670 bool IsDependent = Record[Idx++];
5671 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5672 SmallVector<TemplateArgument, 8> Args;
5673 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5674 QualType Underlying = readType(*Loc.F, Record, Idx);
5675 QualType T;
5676 if (Underlying.isNull())
5677 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5678 Args.size());
5679 else
5680 T = Context.getTemplateSpecializationType(Name, Args.data(),
5681 Args.size(), Underlying);
5682 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5683 return T;
5684 }
5685
5686 case TYPE_ATOMIC: {
5687 if (Record.size() != 1) {
5688 Error("Incorrect encoding of atomic type");
5689 return QualType();
5690 }
5691 QualType ValueType = readType(*Loc.F, Record, Idx);
5692 return Context.getAtomicType(ValueType);
5693 }
5694 }
5695 llvm_unreachable("Invalid TypeCode!");
5696}
5697
Richard Smith564417a2014-03-20 21:47:22 +00005698void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5699 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005700 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005701 const RecordData &Record, unsigned &Idx) {
5702 ExceptionSpecificationType EST =
5703 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005704 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005705 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005706 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005707 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005708 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005709 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005710 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005711 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005712 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5713 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005714 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005715 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005716 }
5717}
5718
Guy Benyei11169dd2012-12-18 14:30:41 +00005719class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5720 ASTReader &Reader;
5721 ModuleFile &F;
5722 const ASTReader::RecordData &Record;
5723 unsigned &Idx;
5724
5725 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5726 unsigned &I) {
5727 return Reader.ReadSourceLocation(F, R, I);
5728 }
5729
5730 template<typename T>
5731 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5732 return Reader.ReadDeclAs<T>(F, Record, Idx);
5733 }
5734
5735public:
5736 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5737 const ASTReader::RecordData &Record, unsigned &Idx)
5738 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5739 { }
5740
5741 // We want compile-time assurance that we've enumerated all of
5742 // these, so unfortunately we have to declare them first, then
5743 // define them out-of-line.
5744#define ABSTRACT_TYPELOC(CLASS, PARENT)
5745#define TYPELOC(CLASS, PARENT) \
5746 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5747#include "clang/AST/TypeLocNodes.def"
5748
5749 void VisitFunctionTypeLoc(FunctionTypeLoc);
5750 void VisitArrayTypeLoc(ArrayTypeLoc);
5751};
5752
5753void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5754 // nothing to do
5755}
5756void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5757 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5758 if (TL.needsExtraLocalData()) {
5759 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5760 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5761 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5762 TL.setModeAttr(Record[Idx++]);
5763 }
5764}
5765void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5766 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5767}
5768void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5769 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5770}
Reid Kleckner8a365022013-06-24 17:51:48 +00005771void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5772 // nothing to do
5773}
Reid Kleckner0503a872013-12-05 01:23:43 +00005774void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5775 // nothing to do
5776}
Guy Benyei11169dd2012-12-18 14:30:41 +00005777void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5778 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5779}
5780void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5781 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5782}
5783void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5784 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5785}
5786void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5787 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5788 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5789}
5790void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5791 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5792 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5793 if (Record[Idx++])
5794 TL.setSizeExpr(Reader.ReadExpr(F));
5795 else
Craig Toppera13603a2014-05-22 05:54:18 +00005796 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005797}
5798void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5799 VisitArrayTypeLoc(TL);
5800}
5801void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5802 VisitArrayTypeLoc(TL);
5803}
5804void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5805 VisitArrayTypeLoc(TL);
5806}
5807void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5808 DependentSizedArrayTypeLoc TL) {
5809 VisitArrayTypeLoc(TL);
5810}
5811void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5812 DependentSizedExtVectorTypeLoc TL) {
5813 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5814}
5815void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5816 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5817}
5818void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5819 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5820}
5821void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5822 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5823 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5824 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5825 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005826 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5827 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005828 }
5829}
5830void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5831 VisitFunctionTypeLoc(TL);
5832}
5833void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5834 VisitFunctionTypeLoc(TL);
5835}
5836void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5837 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5838}
5839void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5840 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5841}
5842void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5843 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5844 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5845 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5846}
5847void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5848 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5849 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5850 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5851 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5852}
5853void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5854 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5855}
5856void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5857 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5858 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5859 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5860 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5861}
5862void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5863 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5864}
5865void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5866 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5867}
5868void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5869 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5870}
5871void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5872 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5873 if (TL.hasAttrOperand()) {
5874 SourceRange range;
5875 range.setBegin(ReadSourceLocation(Record, Idx));
5876 range.setEnd(ReadSourceLocation(Record, Idx));
5877 TL.setAttrOperandParensRange(range);
5878 }
5879 if (TL.hasAttrExprOperand()) {
5880 if (Record[Idx++])
5881 TL.setAttrExprOperand(Reader.ReadExpr(F));
5882 else
Craig Toppera13603a2014-05-22 05:54:18 +00005883 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005884 } else if (TL.hasAttrEnumOperand())
5885 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5886}
5887void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5888 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5889}
5890void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5891 SubstTemplateTypeParmTypeLoc TL) {
5892 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5893}
5894void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5895 SubstTemplateTypeParmPackTypeLoc TL) {
5896 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5897}
5898void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5899 TemplateSpecializationTypeLoc TL) {
5900 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5901 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5902 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5903 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5904 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5905 TL.setArgLocInfo(i,
5906 Reader.GetTemplateArgumentLocInfo(F,
5907 TL.getTypePtr()->getArg(i).getKind(),
5908 Record, Idx));
5909}
5910void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5911 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5912 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5913}
5914void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5915 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5916 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5917}
5918void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5919 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5920}
5921void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5922 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5923 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5924 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5925}
5926void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5927 DependentTemplateSpecializationTypeLoc TL) {
5928 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5929 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5930 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5931 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5932 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5933 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5934 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5935 TL.setArgLocInfo(I,
5936 Reader.GetTemplateArgumentLocInfo(F,
5937 TL.getTypePtr()->getArg(I).getKind(),
5938 Record, Idx));
5939}
5940void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5941 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5942}
5943void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5944 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5945}
5946void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5947 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5948 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5949 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5950 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5951 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5952}
5953void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5954 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5955}
5956void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5957 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5958 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5959 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5960}
5961
5962TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5963 const RecordData &Record,
5964 unsigned &Idx) {
5965 QualType InfoTy = readType(F, Record, Idx);
5966 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005967 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005968
5969 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5970 TypeLocReader TLR(*this, F, Record, Idx);
5971 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5972 TLR.Visit(TL);
5973 return TInfo;
5974}
5975
5976QualType ASTReader::GetType(TypeID ID) {
5977 unsigned FastQuals = ID & Qualifiers::FastMask;
5978 unsigned Index = ID >> Qualifiers::FastWidth;
5979
5980 if (Index < NUM_PREDEF_TYPE_IDS) {
5981 QualType T;
5982 switch ((PredefinedTypeIDs)Index) {
5983 case PREDEF_TYPE_NULL_ID: return QualType();
5984 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5985 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5986
5987 case PREDEF_TYPE_CHAR_U_ID:
5988 case PREDEF_TYPE_CHAR_S_ID:
5989 // FIXME: Check that the signedness of CharTy is correct!
5990 T = Context.CharTy;
5991 break;
5992
5993 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5994 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5995 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5996 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5997 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5998 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5999 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
6000 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
6001 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
6002 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
6003 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
6004 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
6005 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
6006 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
6007 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
6008 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
6009 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
6010 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
6011 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
6012 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
6013 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
6014 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
6015 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
6016 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
6017 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
6018 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
6019 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
6020 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00006021 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
6022 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
6023 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
6024 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
6025 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
6026 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00006027 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006028 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006029 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
6030
6031 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6032 T = Context.getAutoRRefDeductType();
6033 break;
6034
6035 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6036 T = Context.ARCUnbridgedCastTy;
6037 break;
6038
6039 case PREDEF_TYPE_VA_LIST_TAG:
6040 T = Context.getVaListTagType();
6041 break;
6042
6043 case PREDEF_TYPE_BUILTIN_FN:
6044 T = Context.BuiltinFnTy;
6045 break;
6046 }
6047
6048 assert(!T.isNull() && "Unknown predefined type");
6049 return T.withFastQualifiers(FastQuals);
6050 }
6051
6052 Index -= NUM_PREDEF_TYPE_IDS;
6053 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6054 if (TypesLoaded[Index].isNull()) {
6055 TypesLoaded[Index] = readTypeRecord(Index);
6056 if (TypesLoaded[Index].isNull())
6057 return QualType();
6058
6059 TypesLoaded[Index]->setFromAST();
6060 if (DeserializationListener)
6061 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6062 TypesLoaded[Index]);
6063 }
6064
6065 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6066}
6067
6068QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6069 return GetType(getGlobalTypeID(F, LocalID));
6070}
6071
6072serialization::TypeID
6073ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6074 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6075 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6076
6077 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6078 return LocalID;
6079
6080 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6081 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6082 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6083
6084 unsigned GlobalIndex = LocalIndex + I->second;
6085 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6086}
6087
6088TemplateArgumentLocInfo
6089ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6090 TemplateArgument::ArgKind Kind,
6091 const RecordData &Record,
6092 unsigned &Index) {
6093 switch (Kind) {
6094 case TemplateArgument::Expression:
6095 return ReadExpr(F);
6096 case TemplateArgument::Type:
6097 return GetTypeSourceInfo(F, Record, Index);
6098 case TemplateArgument::Template: {
6099 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6100 Index);
6101 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6102 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6103 SourceLocation());
6104 }
6105 case TemplateArgument::TemplateExpansion: {
6106 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6107 Index);
6108 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6109 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6110 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6111 EllipsisLoc);
6112 }
6113 case TemplateArgument::Null:
6114 case TemplateArgument::Integral:
6115 case TemplateArgument::Declaration:
6116 case TemplateArgument::NullPtr:
6117 case TemplateArgument::Pack:
6118 // FIXME: Is this right?
6119 return TemplateArgumentLocInfo();
6120 }
6121 llvm_unreachable("unexpected template argument loc");
6122}
6123
6124TemplateArgumentLoc
6125ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6126 const RecordData &Record, unsigned &Index) {
6127 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6128
6129 if (Arg.getKind() == TemplateArgument::Expression) {
6130 if (Record[Index++]) // bool InfoHasSameExpr.
6131 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6132 }
6133 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6134 Record, Index));
6135}
6136
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006137const ASTTemplateArgumentListInfo*
6138ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6139 const RecordData &Record,
6140 unsigned &Index) {
6141 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6142 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6143 unsigned NumArgsAsWritten = Record[Index++];
6144 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6145 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6146 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6147 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6148}
6149
Guy Benyei11169dd2012-12-18 14:30:41 +00006150Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6151 return GetDecl(ID);
6152}
6153
Richard Smith50895422015-01-31 03:04:55 +00006154template<typename TemplateSpecializationDecl>
6155static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6156 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6157 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6158}
6159
Richard Smith053f6c62014-05-16 23:01:30 +00006160void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006161 if (NumCurrentElementsDeserializing) {
6162 // We arrange to not care about the complete redeclaration chain while we're
6163 // deserializing. Just remember that the AST has marked this one as complete
6164 // but that it's not actually complete yet, so we know we still need to
6165 // complete it later.
6166 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6167 return;
6168 }
6169
Richard Smith053f6c62014-05-16 23:01:30 +00006170 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6171
Richard Smith053f6c62014-05-16 23:01:30 +00006172 // If this is a named declaration, complete it by looking it up
6173 // within its context.
6174 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006175 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006176 // all mergeable entities within it.
6177 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6178 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6179 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
6180 auto *II = Name.getAsIdentifierInfo();
6181 if (isa<TranslationUnitDecl>(DC) && II) {
6182 // Outside of C++, we don't have a lookup table for the TU, so update
6183 // the identifier instead. In C++, either way should work fine.
6184 if (II->isOutOfDate())
6185 updateOutOfDateIdentifier(*II);
6186 } else
6187 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006188 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
6189 // FIXME: It'd be nice to do something a bit more targeted here.
6190 D->getDeclContext()->decls_begin();
Richard Smith053f6c62014-05-16 23:01:30 +00006191 }
6192 }
Richard Smith50895422015-01-31 03:04:55 +00006193
6194 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6195 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6196 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6197 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6198 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6199 if (auto *Template = FD->getPrimaryTemplate())
6200 Template->LoadLazySpecializations();
6201 }
Richard Smith053f6c62014-05-16 23:01:30 +00006202}
6203
Richard Smithcd45dbc2014-04-19 03:48:30 +00006204uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6205 const RecordData &Record,
6206 unsigned &Idx) {
6207 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6208 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006209 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006210 }
6211
Guy Benyei11169dd2012-12-18 14:30:41 +00006212 unsigned LocalID = Record[Idx++];
6213 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6214}
6215
6216CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6217 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006218 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006219 SavedStreamPosition SavedPosition(Cursor);
6220 Cursor.JumpToBit(Loc.Offset);
6221 ReadingKindTracker ReadingKind(Read_Decl, *this);
6222 RecordData Record;
6223 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006224 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006225 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006226 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006227 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006228 }
6229
6230 unsigned Idx = 0;
6231 unsigned NumBases = Record[Idx++];
6232 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6233 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6234 for (unsigned I = 0; I != NumBases; ++I)
6235 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6236 return Bases;
6237}
6238
6239serialization::DeclID
6240ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6241 if (LocalID < NUM_PREDEF_DECL_IDS)
6242 return LocalID;
6243
6244 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6245 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6246 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6247
6248 return LocalID + I->second;
6249}
6250
6251bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6252 ModuleFile &M) const {
6253 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6254 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6255 return &M == I->second;
6256}
6257
Douglas Gregor9f782892013-01-21 15:25:38 +00006258ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006259 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006260 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006261 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6262 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6263 return I->second;
6264}
6265
6266SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6267 if (ID < NUM_PREDEF_DECL_IDS)
6268 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006269
Guy Benyei11169dd2012-12-18 14:30:41 +00006270 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6271
6272 if (Index > DeclsLoaded.size()) {
6273 Error("declaration ID out-of-range for AST file");
6274 return SourceLocation();
6275 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006276
Guy Benyei11169dd2012-12-18 14:30:41 +00006277 if (Decl *D = DeclsLoaded[Index])
6278 return D->getLocation();
6279
6280 unsigned RawLocation = 0;
6281 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6282 return ReadSourceLocation(*Rec.F, RawLocation);
6283}
6284
Richard Smithcd45dbc2014-04-19 03:48:30 +00006285Decl *ASTReader::GetExistingDecl(DeclID ID) {
6286 if (ID < NUM_PREDEF_DECL_IDS) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006287 switch ((PredefinedDeclIDs)ID) {
6288 case PREDEF_DECL_NULL_ID:
Craig Toppera13603a2014-05-22 05:54:18 +00006289 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006290
Guy Benyei11169dd2012-12-18 14:30:41 +00006291 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6292 return Context.getTranslationUnitDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006293
Guy Benyei11169dd2012-12-18 14:30:41 +00006294 case PREDEF_DECL_OBJC_ID_ID:
6295 return Context.getObjCIdDecl();
6296
6297 case PREDEF_DECL_OBJC_SEL_ID:
6298 return Context.getObjCSelDecl();
6299
6300 case PREDEF_DECL_OBJC_CLASS_ID:
6301 return Context.getObjCClassDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006302
Guy Benyei11169dd2012-12-18 14:30:41 +00006303 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6304 return Context.getObjCProtocolDecl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006305
Guy Benyei11169dd2012-12-18 14:30:41 +00006306 case PREDEF_DECL_INT_128_ID:
6307 return Context.getInt128Decl();
6308
6309 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6310 return Context.getUInt128Decl();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006311
Guy Benyei11169dd2012-12-18 14:30:41 +00006312 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6313 return Context.getObjCInstanceTypeDecl();
6314
6315 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6316 return Context.getBuiltinVaListDecl();
6317 }
6318 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006319
Guy Benyei11169dd2012-12-18 14:30:41 +00006320 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6321
6322 if (Index >= DeclsLoaded.size()) {
6323 assert(0 && "declaration ID out-of-range for AST file");
6324 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006325 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006326 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006327
6328 return DeclsLoaded[Index];
6329}
6330
6331Decl *ASTReader::GetDecl(DeclID ID) {
6332 if (ID < NUM_PREDEF_DECL_IDS)
6333 return GetExistingDecl(ID);
6334
6335 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6336
6337 if (Index >= DeclsLoaded.size()) {
6338 assert(0 && "declaration ID out-of-range for AST file");
6339 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006340 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006341 }
6342
Guy Benyei11169dd2012-12-18 14:30:41 +00006343 if (!DeclsLoaded[Index]) {
6344 ReadDeclRecord(ID);
6345 if (DeserializationListener)
6346 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6347 }
6348
6349 return DeclsLoaded[Index];
6350}
6351
6352DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6353 DeclID GlobalID) {
6354 if (GlobalID < NUM_PREDEF_DECL_IDS)
6355 return GlobalID;
6356
6357 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6358 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6359 ModuleFile *Owner = I->second;
6360
6361 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6362 = M.GlobalToLocalDeclIDs.find(Owner);
6363 if (Pos == M.GlobalToLocalDeclIDs.end())
6364 return 0;
6365
6366 return GlobalID - Owner->BaseDeclID + Pos->second;
6367}
6368
6369serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6370 const RecordData &Record,
6371 unsigned &Idx) {
6372 if (Idx >= Record.size()) {
6373 Error("Corrupted AST file");
6374 return 0;
6375 }
6376
6377 return getGlobalDeclID(F, Record[Idx++]);
6378}
6379
6380/// \brief Resolve the offset of a statement into a statement.
6381///
6382/// This operation will read a new statement from the external
6383/// source each time it is called, and is meant to be used via a
6384/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6385Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6386 // Switch case IDs are per Decl.
6387 ClearSwitchCaseIDs();
6388
6389 // Offset here is a global offset across the entire chain.
6390 RecordLocation Loc = getLocalBitOffset(Offset);
6391 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6392 return ReadStmtFromStream(*Loc.F);
6393}
6394
6395namespace {
6396 class FindExternalLexicalDeclsVisitor {
6397 ASTReader &Reader;
6398 const DeclContext *DC;
6399 bool (*isKindWeWant)(Decl::Kind);
6400
6401 SmallVectorImpl<Decl*> &Decls;
6402 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6403
6404 public:
6405 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6406 bool (*isKindWeWant)(Decl::Kind),
6407 SmallVectorImpl<Decl*> &Decls)
6408 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6409 {
6410 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6411 PredefsVisited[I] = false;
6412 }
6413
6414 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6415 if (Preorder)
6416 return false;
6417
6418 FindExternalLexicalDeclsVisitor *This
6419 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6420
6421 ModuleFile::DeclContextInfosMap::iterator Info
6422 = M.DeclContextInfos.find(This->DC);
6423 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6424 return false;
6425
6426 // Load all of the declaration IDs
6427 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6428 *IDE = ID + Info->second.NumLexicalDecls;
6429 ID != IDE; ++ID) {
6430 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6431 continue;
6432
6433 // Don't add predefined declarations to the lexical context more
6434 // than once.
6435 if (ID->second < NUM_PREDEF_DECL_IDS) {
6436 if (This->PredefsVisited[ID->second])
6437 continue;
6438
6439 This->PredefsVisited[ID->second] = true;
6440 }
6441
6442 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6443 if (!This->DC->isDeclInLexicalTraversal(D))
6444 This->Decls.push_back(D);
6445 }
6446 }
6447
6448 return false;
6449 }
6450 };
6451}
6452
6453ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6454 bool (*isKindWeWant)(Decl::Kind),
6455 SmallVectorImpl<Decl*> &Decls) {
6456 // There might be lexical decls in multiple modules, for the TU at
6457 // least. Walk all of the modules in the order they were loaded.
6458 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6459 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6460 ++NumLexicalDeclContextsRead;
6461 return ELR_Success;
6462}
6463
6464namespace {
6465
6466class DeclIDComp {
6467 ASTReader &Reader;
6468 ModuleFile &Mod;
6469
6470public:
6471 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6472
6473 bool operator()(LocalDeclID L, LocalDeclID R) const {
6474 SourceLocation LHS = getLocation(L);
6475 SourceLocation RHS = getLocation(R);
6476 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6477 }
6478
6479 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6480 SourceLocation RHS = getLocation(R);
6481 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6482 }
6483
6484 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6485 SourceLocation LHS = getLocation(L);
6486 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6487 }
6488
6489 SourceLocation getLocation(LocalDeclID ID) const {
6490 return Reader.getSourceManager().getFileLoc(
6491 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6492 }
6493};
6494
6495}
6496
6497void ASTReader::FindFileRegionDecls(FileID File,
6498 unsigned Offset, unsigned Length,
6499 SmallVectorImpl<Decl *> &Decls) {
6500 SourceManager &SM = getSourceManager();
6501
6502 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6503 if (I == FileDeclIDs.end())
6504 return;
6505
6506 FileDeclsInfo &DInfo = I->second;
6507 if (DInfo.Decls.empty())
6508 return;
6509
6510 SourceLocation
6511 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6512 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6513
6514 DeclIDComp DIDComp(*this, *DInfo.Mod);
6515 ArrayRef<serialization::LocalDeclID>::iterator
6516 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6517 BeginLoc, DIDComp);
6518 if (BeginIt != DInfo.Decls.begin())
6519 --BeginIt;
6520
6521 // If we are pointing at a top-level decl inside an objc container, we need
6522 // to backtrack until we find it otherwise we will fail to report that the
6523 // region overlaps with an objc container.
6524 while (BeginIt != DInfo.Decls.begin() &&
6525 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6526 ->isTopLevelDeclInObjCContainer())
6527 --BeginIt;
6528
6529 ArrayRef<serialization::LocalDeclID>::iterator
6530 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6531 EndLoc, DIDComp);
6532 if (EndIt != DInfo.Decls.end())
6533 ++EndIt;
6534
6535 for (ArrayRef<serialization::LocalDeclID>::iterator
6536 DIt = BeginIt; DIt != EndIt; ++DIt)
6537 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6538}
6539
6540namespace {
6541 /// \brief ModuleFile visitor used to perform name lookup into a
6542 /// declaration context.
6543 class DeclContextNameLookupVisitor {
6544 ASTReader &Reader;
Richard Smith8c913ec2014-08-14 02:21:01 +00006545 ArrayRef<const DeclContext *> Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006546 DeclarationName Name;
6547 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006548 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006549
6550 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006551 DeclContextNameLookupVisitor(ASTReader &Reader,
6552 ArrayRef<const DeclContext *> Contexts,
Guy Benyei11169dd2012-12-18 14:30:41 +00006553 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006554 SmallVectorImpl<NamedDecl *> &Decls,
6555 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
6556 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls),
6557 DeclSet(DeclSet) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006558
6559 static bool visit(ModuleFile &M, void *UserData) {
6560 DeclContextNameLookupVisitor *This
6561 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6562
6563 // Check whether we have any visible declaration information for
6564 // this context in this module.
6565 ModuleFile::DeclContextInfosMap::iterator Info;
6566 bool FoundInfo = false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006567 for (auto *DC : This->Contexts) {
6568 Info = M.DeclContextInfos.find(DC);
6569 if (Info != M.DeclContextInfos.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006570 Info->second.NameLookupTableData) {
6571 FoundInfo = true;
6572 break;
6573 }
6574 }
6575
6576 if (!FoundInfo)
6577 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006578
Guy Benyei11169dd2012-12-18 14:30:41 +00006579 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006580 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006581 Info->second.NameLookupTableData;
6582 ASTDeclContextNameLookupTable::iterator Pos
6583 = LookupTable->find(This->Name);
6584 if (Pos == LookupTable->end())
6585 return false;
6586
6587 bool FoundAnything = false;
6588 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6589 for (; Data.first != Data.second; ++Data.first) {
6590 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6591 if (!ND)
6592 continue;
6593
6594 if (ND->getDeclName() != This->Name) {
6595 // A name might be null because the decl's redeclarable part is
6596 // currently read before reading its name. The lookup is triggered by
6597 // building that decl (likely indirectly), and so it is later in the
6598 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006599 // FIXME: This should not happen; deserializing declarations should
6600 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006601 continue;
6602 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006603
Guy Benyei11169dd2012-12-18 14:30:41 +00006604 // Record this declaration.
6605 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006606 if (This->DeclSet.insert(ND).second)
6607 This->Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006608 }
6609
6610 return FoundAnything;
6611 }
6612 };
6613}
6614
Douglas Gregor9f782892013-01-21 15:25:38 +00006615/// \brief Retrieve the "definitive" module file for the definition of the
6616/// given declaration context, if there is one.
6617///
6618/// The "definitive" module file is the only place where we need to look to
6619/// find information about the declarations within the given declaration
6620/// context. For example, C++ and Objective-C classes, C structs/unions, and
6621/// Objective-C protocols, categories, and extensions are all defined in a
6622/// single place in the source code, so they have definitive module files
6623/// associated with them. C++ namespaces, on the other hand, can have
6624/// definitions in multiple different module files.
6625///
6626/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6627/// NDEBUG checking.
6628static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6629 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006630 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6631 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006632
Craig Toppera13603a2014-05-22 05:54:18 +00006633 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006634}
6635
Richard Smith9ce12e32013-02-07 03:30:24 +00006636bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006637ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6638 DeclarationName Name) {
6639 assert(DC->hasExternalVisibleStorage() &&
6640 "DeclContext has no visible decls in storage");
6641 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006642 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006643
Richard Smith8c913ec2014-08-14 02:21:01 +00006644 Deserializing LookupResults(this);
6645
Guy Benyei11169dd2012-12-18 14:30:41 +00006646 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006647 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006648
Guy Benyei11169dd2012-12-18 14:30:41 +00006649 // Compute the declaration contexts we need to look into. Multiple such
6650 // declaration contexts occur when two declaration contexts from disjoint
6651 // modules get merged, e.g., when two namespaces with the same name are
6652 // independently defined in separate modules.
6653 SmallVector<const DeclContext *, 2> Contexts;
6654 Contexts.push_back(DC);
Richard Smith8c913ec2014-08-14 02:21:01 +00006655
Guy Benyei11169dd2012-12-18 14:30:41 +00006656 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006657 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006658 if (Merged != MergedDecls.end()) {
6659 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6660 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6661 }
6662 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006663
6664 auto LookUpInContexts = [&](ArrayRef<const DeclContext*> Contexts) {
Richard Smith52874ec2015-02-13 20:17:14 +00006665 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls, DeclSet);
Richard Smith8c913ec2014-08-14 02:21:01 +00006666
6667 // If we can definitively determine which module file to look into,
6668 // only look there. Otherwise, look in all module files.
6669 ModuleFile *Definitive;
6670 if (Contexts.size() == 1 &&
6671 (Definitive = getDefinitiveModuleFileFor(Contexts[0], *this))) {
6672 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6673 } else {
6674 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6675 }
6676 };
6677
6678 LookUpInContexts(Contexts);
6679
6680 // If this might be an implicit special member function, then also search
6681 // all merged definitions of the surrounding class. We need to search them
6682 // individually, because finding an entity in one of them doesn't imply that
6683 // we can't find a different entity in another one.
Richard Smithcd45dbc2014-04-19 03:48:30 +00006684 if (isa<CXXRecordDecl>(DC)) {
Richard Smith8c913ec2014-08-14 02:21:01 +00006685 auto Kind = Name.getNameKind();
6686 if (Kind == DeclarationName::CXXConstructorName ||
6687 Kind == DeclarationName::CXXDestructorName ||
6688 (Kind == DeclarationName::CXXOperatorName &&
6689 Name.getCXXOverloadedOperator() == OO_Equal)) {
6690 auto Merged = MergedLookups.find(DC);
Richard Smithe0612472014-11-21 05:16:13 +00006691 if (Merged != MergedLookups.end()) {
6692 for (unsigned I = 0; I != Merged->second.size(); ++I) {
Daniel Jasperc0b7c802015-02-18 14:13:46 +00006693 const DeclContext *Context = Merged->second[I];
6694 LookUpInContexts(Context);
Richard Smithe0612472014-11-21 05:16:13 +00006695 // We might have just added some more merged lookups. If so, our
6696 // iterator is now invalid, so grab a fresh one before continuing.
6697 Merged = MergedLookups.find(DC);
6698 }
6699 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006700 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006701 }
6702
Guy Benyei11169dd2012-12-18 14:30:41 +00006703 ++NumVisibleDeclContextsRead;
6704 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006705 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006706}
6707
6708namespace {
6709 /// \brief ModuleFile visitor used to retrieve all visible names in a
6710 /// declaration context.
6711 class DeclContextAllNamesVisitor {
6712 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006713 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006714 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006715 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006716 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006717
6718 public:
6719 DeclContextAllNamesVisitor(ASTReader &Reader,
6720 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006721 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006722 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006723
6724 static bool visit(ModuleFile &M, void *UserData) {
6725 DeclContextAllNamesVisitor *This
6726 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6727
6728 // Check whether we have any visible declaration information for
6729 // this context in this module.
6730 ModuleFile::DeclContextInfosMap::iterator Info;
6731 bool FoundInfo = false;
6732 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6733 Info = M.DeclContextInfos.find(This->Contexts[I]);
6734 if (Info != M.DeclContextInfos.end() &&
6735 Info->second.NameLookupTableData) {
6736 FoundInfo = true;
6737 break;
6738 }
6739 }
6740
6741 if (!FoundInfo)
6742 return false;
6743
Richard Smith52e3fba2014-03-11 07:17:35 +00006744 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006745 Info->second.NameLookupTableData;
6746 bool FoundAnything = false;
6747 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006748 I = LookupTable->data_begin(), E = LookupTable->data_end();
6749 I != E;
6750 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006751 ASTDeclContextNameLookupTrait::data_type Data = *I;
6752 for (; Data.first != Data.second; ++Data.first) {
6753 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6754 *Data.first);
6755 if (!ND)
6756 continue;
6757
6758 // Record this declaration.
6759 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006760 if (This->DeclSet.insert(ND).second)
6761 This->Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006762 }
6763 }
6764
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006765 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006766 }
6767 };
6768}
6769
6770void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6771 if (!DC->hasExternalVisibleStorage())
6772 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006773 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006774
6775 // Compute the declaration contexts we need to look into. Multiple such
6776 // declaration contexts occur when two declaration contexts from disjoint
6777 // modules get merged, e.g., when two namespaces with the same name are
6778 // independently defined in separate modules.
6779 SmallVector<const DeclContext *, 2> Contexts;
6780 Contexts.push_back(DC);
6781
6782 if (DC->isNamespace()) {
6783 MergedDeclsMap::iterator Merged
6784 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6785 if (Merged != MergedDecls.end()) {
6786 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6787 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6788 }
6789 }
6790
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006791 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6792 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006793 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6794 ++NumVisibleDeclContextsRead;
6795
Craig Topper79be4cd2013-07-05 04:33:53 +00006796 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006797 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6798 }
6799 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6800}
6801
6802/// \brief Under non-PCH compilation the consumer receives the objc methods
6803/// before receiving the implementation, and codegen depends on this.
6804/// We simulate this by deserializing and passing to consumer the methods of the
6805/// implementation before passing the deserialized implementation decl.
6806static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6807 ASTConsumer *Consumer) {
6808 assert(ImplD && Consumer);
6809
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006810 for (auto *I : ImplD->methods())
6811 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006812
6813 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6814}
6815
6816void ASTReader::PassInterestingDeclsToConsumer() {
6817 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006818
6819 if (PassingDeclsToConsumer)
6820 return;
6821
6822 // Guard variable to avoid recursively redoing the process of passing
6823 // decls to consumer.
6824 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6825 true);
6826
Guy Benyei11169dd2012-12-18 14:30:41 +00006827 while (!InterestingDecls.empty()) {
6828 Decl *D = InterestingDecls.front();
6829 InterestingDecls.pop_front();
6830
6831 PassInterestingDeclToConsumer(D);
6832 }
6833}
6834
6835void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6836 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6837 PassObjCImplDeclToConsumer(ImplD, Consumer);
6838 else
6839 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6840}
6841
6842void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6843 this->Consumer = Consumer;
6844
6845 if (!Consumer)
6846 return;
6847
Ben Langmuir332aafe2014-01-31 01:06:56 +00006848 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006849 // Force deserialization of this decl, which will cause it to be queued for
6850 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006851 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006852 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006853 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006854
6855 PassInterestingDeclsToConsumer();
6856}
6857
6858void ASTReader::PrintStats() {
6859 std::fprintf(stderr, "*** AST File Statistics:\n");
6860
6861 unsigned NumTypesLoaded
6862 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6863 QualType());
6864 unsigned NumDeclsLoaded
6865 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006866 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006867 unsigned NumIdentifiersLoaded
6868 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6869 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006870 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006871 unsigned NumMacrosLoaded
6872 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6873 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006874 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006875 unsigned NumSelectorsLoaded
6876 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6877 SelectorsLoaded.end(),
6878 Selector());
6879
6880 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6881 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6882 NumSLocEntriesRead, TotalNumSLocEntries,
6883 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6884 if (!TypesLoaded.empty())
6885 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6886 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6887 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6888 if (!DeclsLoaded.empty())
6889 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6890 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6891 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6892 if (!IdentifiersLoaded.empty())
6893 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6894 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6895 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6896 if (!MacrosLoaded.empty())
6897 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6898 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6899 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6900 if (!SelectorsLoaded.empty())
6901 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6902 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6903 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6904 if (TotalNumStatements)
6905 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6906 NumStatementsRead, TotalNumStatements,
6907 ((float)NumStatementsRead/TotalNumStatements * 100));
6908 if (TotalNumMacros)
6909 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6910 NumMacrosRead, TotalNumMacros,
6911 ((float)NumMacrosRead/TotalNumMacros * 100));
6912 if (TotalLexicalDeclContexts)
6913 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6914 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6915 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6916 * 100));
6917 if (TotalVisibleDeclContexts)
6918 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6919 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6920 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6921 * 100));
6922 if (TotalNumMethodPoolEntries) {
6923 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6924 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6925 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6926 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006927 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006928 if (NumMethodPoolLookups) {
6929 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6930 NumMethodPoolHits, NumMethodPoolLookups,
6931 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6932 }
6933 if (NumMethodPoolTableLookups) {
6934 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6935 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6936 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6937 * 100.0));
6938 }
6939
Douglas Gregor00a50f72013-01-25 00:38:33 +00006940 if (NumIdentifierLookupHits) {
6941 std::fprintf(stderr,
6942 " %u / %u identifier table lookups succeeded (%f%%)\n",
6943 NumIdentifierLookupHits, NumIdentifierLookups,
6944 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6945 }
6946
Douglas Gregore060e572013-01-25 01:03:03 +00006947 if (GlobalIndex) {
6948 std::fprintf(stderr, "\n");
6949 GlobalIndex->printStats();
6950 }
6951
Guy Benyei11169dd2012-12-18 14:30:41 +00006952 std::fprintf(stderr, "\n");
6953 dump();
6954 std::fprintf(stderr, "\n");
6955}
6956
6957template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6958static void
6959dumpModuleIDMap(StringRef Name,
6960 const ContinuousRangeMap<Key, ModuleFile *,
6961 InitialCapacity> &Map) {
6962 if (Map.begin() == Map.end())
6963 return;
6964
6965 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6966 llvm::errs() << Name << ":\n";
6967 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6968 I != IEnd; ++I) {
6969 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6970 << "\n";
6971 }
6972}
6973
6974void ASTReader::dump() {
6975 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6976 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6977 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6978 dumpModuleIDMap("Global type map", GlobalTypeMap);
6979 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6980 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6981 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6982 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6983 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6984 dumpModuleIDMap("Global preprocessed entity map",
6985 GlobalPreprocessedEntityMap);
6986
6987 llvm::errs() << "\n*** PCH/Modules Loaded:";
6988 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6989 MEnd = ModuleMgr.end();
6990 M != MEnd; ++M)
6991 (*M)->dump();
6992}
6993
6994/// Return the amount of memory used by memory buffers, breaking down
6995/// by heap-backed versus mmap'ed memory.
6996void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6997 for (ModuleConstIterator I = ModuleMgr.begin(),
6998 E = ModuleMgr.end(); I != E; ++I) {
6999 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
7000 size_t bytes = buf->getBufferSize();
7001 switch (buf->getBufferKind()) {
7002 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7003 sizes.malloc_bytes += bytes;
7004 break;
7005 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7006 sizes.mmap_bytes += bytes;
7007 break;
7008 }
7009 }
7010 }
7011}
7012
7013void ASTReader::InitializeSema(Sema &S) {
7014 SemaObj = &S;
7015 S.addExternalSource(this);
7016
7017 // Makes sure any declarations that were deserialized "too early"
7018 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00007019 for (uint64_t ID : PreloadedDeclIDs) {
7020 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7021 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007022 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007023 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007024
Richard Smith3d8e97e2013-10-18 06:54:39 +00007025 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007026 if (!FPPragmaOptions.empty()) {
7027 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7028 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
7029 }
7030
Richard Smith3d8e97e2013-10-18 06:54:39 +00007031 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007032 if (!OpenCLExtensions.empty()) {
7033 unsigned I = 0;
7034#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
7035#include "clang/Basic/OpenCLExtensions.def"
7036
7037 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
7038 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00007039
7040 UpdateSema();
7041}
7042
7043void ASTReader::UpdateSema() {
7044 assert(SemaObj && "no Sema to update");
7045
7046 // Load the offsets of the declarations that Sema references.
7047 // They will be lazily deserialized when needed.
7048 if (!SemaDeclRefs.empty()) {
7049 assert(SemaDeclRefs.size() % 2 == 0);
7050 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
7051 if (!SemaObj->StdNamespace)
7052 SemaObj->StdNamespace = SemaDeclRefs[I];
7053 if (!SemaObj->StdBadAlloc)
7054 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
7055 }
7056 SemaDeclRefs.clear();
7057 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007058
7059 // Update the state of 'pragma clang optimize'. Use the same API as if we had
7060 // encountered the pragma in the source.
7061 if(OptimizeOffPragmaLocation.isValid())
7062 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00007063}
7064
7065IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
7066 // Note that we are loading an identifier.
7067 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007068 StringRef Name(NameStart, NameEnd - NameStart);
7069
7070 // If there is a global index, look there first to determine which modules
7071 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00007072 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00007073 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00007074 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00007075 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7076 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00007077 }
7078 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00007079 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007080 NumIdentifierLookups,
7081 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00007082 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007083 IdentifierInfo *II = Visitor.getIdentifierInfo();
7084 markIdentifierUpToDate(II);
7085 return II;
7086}
7087
7088namespace clang {
7089 /// \brief An identifier-lookup iterator that enumerates all of the
7090 /// identifiers stored within a set of AST files.
7091 class ASTIdentifierIterator : public IdentifierIterator {
7092 /// \brief The AST reader whose identifiers are being enumerated.
7093 const ASTReader &Reader;
7094
7095 /// \brief The current index into the chain of AST files stored in
7096 /// the AST reader.
7097 unsigned Index;
7098
7099 /// \brief The current position within the identifier lookup table
7100 /// of the current AST file.
7101 ASTIdentifierLookupTable::key_iterator Current;
7102
7103 /// \brief The end position within the identifier lookup table of
7104 /// the current AST file.
7105 ASTIdentifierLookupTable::key_iterator End;
7106
7107 public:
7108 explicit ASTIdentifierIterator(const ASTReader &Reader);
7109
Craig Topper3e89dfe2014-03-13 02:13:41 +00007110 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007111 };
7112}
7113
7114ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
7115 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
7116 ASTIdentifierLookupTable *IdTable
7117 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
7118 Current = IdTable->key_begin();
7119 End = IdTable->key_end();
7120}
7121
7122StringRef ASTIdentifierIterator::Next() {
7123 while (Current == End) {
7124 // If we have exhausted all of our AST files, we're done.
7125 if (Index == 0)
7126 return StringRef();
7127
7128 --Index;
7129 ASTIdentifierLookupTable *IdTable
7130 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
7131 IdentifierLookupTable;
7132 Current = IdTable->key_begin();
7133 End = IdTable->key_end();
7134 }
7135
7136 // We have any identifiers remaining in the current AST file; return
7137 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007138 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007139 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007140 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007141}
7142
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007143IdentifierIterator *ASTReader::getIdentifiers() {
7144 if (!loadGlobalIndex())
7145 return GlobalIndex->createIdentifierIterator();
7146
Guy Benyei11169dd2012-12-18 14:30:41 +00007147 return new ASTIdentifierIterator(*this);
7148}
7149
7150namespace clang { namespace serialization {
7151 class ReadMethodPoolVisitor {
7152 ASTReader &Reader;
7153 Selector Sel;
7154 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007155 unsigned InstanceBits;
7156 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007157 bool InstanceHasMoreThanOneDecl;
7158 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007159 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7160 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007161
7162 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007163 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007164 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007165 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007166 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7167 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007168
Guy Benyei11169dd2012-12-18 14:30:41 +00007169 static bool visit(ModuleFile &M, void *UserData) {
7170 ReadMethodPoolVisitor *This
7171 = static_cast<ReadMethodPoolVisitor *>(UserData);
7172
7173 if (!M.SelectorLookupTable)
7174 return false;
7175
7176 // If we've already searched this module file, skip it now.
7177 if (M.Generation <= This->PriorGeneration)
7178 return true;
7179
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007180 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007181 ASTSelectorLookupTable *PoolTable
7182 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
7183 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
7184 if (Pos == PoolTable->end())
7185 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007186
7187 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00007188 ++This->Reader.NumSelectorsRead;
7189 // FIXME: Not quite happy with the statistics here. We probably should
7190 // disable this tracking when called via LoadSelector.
7191 // Also, should entries without methods count as misses?
7192 ++This->Reader.NumMethodPoolEntriesRead;
7193 ASTSelectorLookupTrait::data_type Data = *Pos;
7194 if (This->Reader.DeserializationListener)
7195 This->Reader.DeserializationListener->SelectorRead(Data.ID,
7196 This->Sel);
7197
7198 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7199 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007200 This->InstanceBits = Data.InstanceBits;
7201 This->FactoryBits = Data.FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007202 This->InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7203 This->FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007204 return true;
7205 }
7206
7207 /// \brief Retrieve the instance methods found by this visitor.
7208 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7209 return InstanceMethods;
7210 }
7211
7212 /// \brief Retrieve the instance methods found by this visitor.
7213 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7214 return FactoryMethods;
7215 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007216
7217 unsigned getInstanceBits() const { return InstanceBits; }
7218 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007219 bool instanceHasMoreThanOneDecl() const {
7220 return InstanceHasMoreThanOneDecl;
7221 }
7222 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007223 };
7224} } // end namespace clang::serialization
7225
7226/// \brief Add the given set of methods to the method list.
7227static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7228 ObjCMethodList &List) {
7229 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7230 S.addMethodToGlobalList(&List, Methods[I]);
7231 }
7232}
7233
7234void ASTReader::ReadMethodPool(Selector Sel) {
7235 // Get the selector generation and update it to the current generation.
7236 unsigned &Generation = SelectorGeneration[Sel];
7237 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007238 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007239
7240 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007241 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007242 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7243 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
7244
7245 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007246 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007247 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007248
7249 ++NumMethodPoolHits;
7250
Guy Benyei11169dd2012-12-18 14:30:41 +00007251 if (!getSema())
7252 return;
7253
7254 Sema &S = *getSema();
7255 Sema::GlobalMethodPool::iterator Pos
7256 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007257
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007258 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007259 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007260 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007261 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007262
7263 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7264 // when building a module we keep every method individually and may need to
7265 // update hasMoreThanOneDecl as we add the methods.
7266 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7267 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007268}
7269
7270void ASTReader::ReadKnownNamespaces(
7271 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7272 Namespaces.clear();
7273
7274 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7275 if (NamespaceDecl *Namespace
7276 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7277 Namespaces.push_back(Namespace);
7278 }
7279}
7280
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007281void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007282 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007283 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7284 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007285 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007286 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007287 Undefined.insert(std::make_pair(D, Loc));
7288 }
7289}
Nick Lewycky8334af82013-01-26 00:35:08 +00007290
Guy Benyei11169dd2012-12-18 14:30:41 +00007291void ASTReader::ReadTentativeDefinitions(
7292 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7293 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7294 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7295 if (Var)
7296 TentativeDefs.push_back(Var);
7297 }
7298 TentativeDefinitions.clear();
7299}
7300
7301void ASTReader::ReadUnusedFileScopedDecls(
7302 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7303 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7304 DeclaratorDecl *D
7305 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7306 if (D)
7307 Decls.push_back(D);
7308 }
7309 UnusedFileScopedDecls.clear();
7310}
7311
7312void ASTReader::ReadDelegatingConstructors(
7313 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7314 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7315 CXXConstructorDecl *D
7316 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7317 if (D)
7318 Decls.push_back(D);
7319 }
7320 DelegatingCtorDecls.clear();
7321}
7322
7323void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7324 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7325 TypedefNameDecl *D
7326 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7327 if (D)
7328 Decls.push_back(D);
7329 }
7330 ExtVectorDecls.clear();
7331}
7332
7333void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
7334 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
7335 CXXRecordDecl *D
7336 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
7337 if (D)
7338 Decls.push_back(D);
7339 }
7340 DynamicClasses.clear();
7341}
7342
Nico Weber72889432014-09-06 01:25:55 +00007343void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7344 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7345 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7346 ++I) {
7347 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7348 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7349 if (D)
7350 Decls.insert(D);
7351 }
7352 UnusedLocalTypedefNameCandidates.clear();
7353}
7354
Guy Benyei11169dd2012-12-18 14:30:41 +00007355void
Richard Smith78165b52013-01-10 23:43:47 +00007356ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
7357 for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
7358 NamedDecl *D
7359 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00007360 if (D)
7361 Decls.push_back(D);
7362 }
Richard Smith78165b52013-01-10 23:43:47 +00007363 LocallyScopedExternCDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007364}
7365
7366void ASTReader::ReadReferencedSelectors(
7367 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7368 if (ReferencedSelectorsData.empty())
7369 return;
7370
7371 // If there are @selector references added them to its pool. This is for
7372 // implementation of -Wselector.
7373 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7374 unsigned I = 0;
7375 while (I < DataSize) {
7376 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7377 SourceLocation SelLoc
7378 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7379 Sels.push_back(std::make_pair(Sel, SelLoc));
7380 }
7381 ReferencedSelectorsData.clear();
7382}
7383
7384void ASTReader::ReadWeakUndeclaredIdentifiers(
7385 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7386 if (WeakUndeclaredIdentifiers.empty())
7387 return;
7388
7389 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7390 IdentifierInfo *WeakId
7391 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7392 IdentifierInfo *AliasId
7393 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7394 SourceLocation Loc
7395 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7396 bool Used = WeakUndeclaredIdentifiers[I++];
7397 WeakInfo WI(AliasId, Loc);
7398 WI.setUsed(Used);
7399 WeakIDs.push_back(std::make_pair(WeakId, WI));
7400 }
7401 WeakUndeclaredIdentifiers.clear();
7402}
7403
7404void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7405 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7406 ExternalVTableUse VT;
7407 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7408 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7409 VT.DefinitionRequired = VTableUses[Idx++];
7410 VTables.push_back(VT);
7411 }
7412
7413 VTableUses.clear();
7414}
7415
7416void ASTReader::ReadPendingInstantiations(
7417 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7418 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7419 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7420 SourceLocation Loc
7421 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7422
7423 Pending.push_back(std::make_pair(D, Loc));
7424 }
7425 PendingInstantiations.clear();
7426}
7427
Richard Smithe40f2ba2013-08-07 21:41:30 +00007428void ASTReader::ReadLateParsedTemplates(
7429 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7430 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7431 /* In loop */) {
7432 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7433
7434 LateParsedTemplate *LT = new LateParsedTemplate;
7435 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7436
7437 ModuleFile *F = getOwningModuleFile(LT->D);
7438 assert(F && "No module");
7439
7440 unsigned TokN = LateParsedTemplates[Idx++];
7441 LT->Toks.reserve(TokN);
7442 for (unsigned T = 0; T < TokN; ++T)
7443 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7444
7445 LPTMap[FD] = LT;
7446 }
7447
7448 LateParsedTemplates.clear();
7449}
7450
Guy Benyei11169dd2012-12-18 14:30:41 +00007451void ASTReader::LoadSelector(Selector Sel) {
7452 // It would be complicated to avoid reading the methods anyway. So don't.
7453 ReadMethodPool(Sel);
7454}
7455
7456void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7457 assert(ID && "Non-zero identifier ID required");
7458 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7459 IdentifiersLoaded[ID - 1] = II;
7460 if (DeserializationListener)
7461 DeserializationListener->IdentifierRead(ID, II);
7462}
7463
7464/// \brief Set the globally-visible declarations associated with the given
7465/// identifier.
7466///
7467/// If the AST reader is currently in a state where the given declaration IDs
7468/// cannot safely be resolved, they are queued until it is safe to resolve
7469/// them.
7470///
7471/// \param II an IdentifierInfo that refers to one or more globally-visible
7472/// declarations.
7473///
7474/// \param DeclIDs the set of declaration IDs with the name @p II that are
7475/// visible at global scope.
7476///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007477/// \param Decls if non-null, this vector will be populated with the set of
7478/// deserialized declarations. These declarations will not be pushed into
7479/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007480void
7481ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7482 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007483 SmallVectorImpl<Decl *> *Decls) {
7484 if (NumCurrentElementsDeserializing && !Decls) {
7485 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007486 return;
7487 }
7488
7489 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007490 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007491 // Queue this declaration so that it will be added to the
7492 // translation unit scope and identifier's declaration chain
7493 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007494 PreloadedDeclIDs.push_back(DeclIDs[I]);
7495 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007496 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007497
7498 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7499
7500 // If we're simply supposed to record the declarations, do so now.
7501 if (Decls) {
7502 Decls->push_back(D);
7503 continue;
7504 }
7505
7506 // Introduce this declaration into the translation-unit scope
7507 // and add it to the declaration chain for this identifier, so
7508 // that (unqualified) name lookup will find it.
7509 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007510 }
7511}
7512
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007513IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007514 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007515 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007516
7517 if (IdentifiersLoaded.empty()) {
7518 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007519 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007520 }
7521
7522 ID -= 1;
7523 if (!IdentifiersLoaded[ID]) {
7524 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7525 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7526 ModuleFile *M = I->second;
7527 unsigned Index = ID - M->BaseIdentifierID;
7528 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7529
7530 // All of the strings in the AST file are preceded by a 16-bit length.
7531 // Extract that 16-bit length to avoid having to execute strlen().
7532 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7533 // unsigned integers. This is important to avoid integer overflow when
7534 // we cast them to 'unsigned'.
7535 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7536 unsigned StrLen = (((unsigned) StrLenPtr[0])
7537 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007538 IdentifiersLoaded[ID]
7539 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007540 if (DeserializationListener)
7541 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7542 }
7543
7544 return IdentifiersLoaded[ID];
7545}
7546
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007547IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7548 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007549}
7550
7551IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7552 if (LocalID < NUM_PREDEF_IDENT_IDS)
7553 return LocalID;
7554
7555 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7556 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7557 assert(I != M.IdentifierRemap.end()
7558 && "Invalid index into identifier index remap");
7559
7560 return LocalID + I->second;
7561}
7562
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007563MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007564 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007565 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007566
7567 if (MacrosLoaded.empty()) {
7568 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007569 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007570 }
7571
7572 ID -= NUM_PREDEF_MACRO_IDS;
7573 if (!MacrosLoaded[ID]) {
7574 GlobalMacroMapType::iterator I
7575 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7576 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7577 ModuleFile *M = I->second;
7578 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007579 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7580
7581 if (DeserializationListener)
7582 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7583 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007584 }
7585
7586 return MacrosLoaded[ID];
7587}
7588
7589MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7590 if (LocalID < NUM_PREDEF_MACRO_IDS)
7591 return LocalID;
7592
7593 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7594 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7595 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7596
7597 return LocalID + I->second;
7598}
7599
7600serialization::SubmoduleID
7601ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7602 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7603 return LocalID;
7604
7605 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7606 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7607 assert(I != M.SubmoduleRemap.end()
7608 && "Invalid index into submodule index remap");
7609
7610 return LocalID + I->second;
7611}
7612
7613Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7614 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7615 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007616 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007617 }
7618
7619 if (GlobalID > SubmodulesLoaded.size()) {
7620 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007621 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007622 }
7623
7624 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7625}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007626
7627Module *ASTReader::getModule(unsigned ID) {
7628 return getSubmodule(ID);
7629}
7630
Guy Benyei11169dd2012-12-18 14:30:41 +00007631Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7632 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7633}
7634
7635Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7636 if (ID == 0)
7637 return Selector();
7638
7639 if (ID > SelectorsLoaded.size()) {
7640 Error("selector ID out of range in AST file");
7641 return Selector();
7642 }
7643
Craig Toppera13603a2014-05-22 05:54:18 +00007644 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007645 // Load this selector from the selector table.
7646 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7647 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7648 ModuleFile &M = *I->second;
7649 ASTSelectorLookupTrait Trait(*this, M);
7650 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7651 SelectorsLoaded[ID - 1] =
7652 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7653 if (DeserializationListener)
7654 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7655 }
7656
7657 return SelectorsLoaded[ID - 1];
7658}
7659
7660Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7661 return DecodeSelector(ID);
7662}
7663
7664uint32_t ASTReader::GetNumExternalSelectors() {
7665 // ID 0 (the null selector) is considered an external selector.
7666 return getTotalNumSelectors() + 1;
7667}
7668
7669serialization::SelectorID
7670ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7671 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7672 return LocalID;
7673
7674 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7675 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7676 assert(I != M.SelectorRemap.end()
7677 && "Invalid index into selector index remap");
7678
7679 return LocalID + I->second;
7680}
7681
7682DeclarationName
7683ASTReader::ReadDeclarationName(ModuleFile &F,
7684 const RecordData &Record, unsigned &Idx) {
7685 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7686 switch (Kind) {
7687 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007688 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007689
7690 case DeclarationName::ObjCZeroArgSelector:
7691 case DeclarationName::ObjCOneArgSelector:
7692 case DeclarationName::ObjCMultiArgSelector:
7693 return DeclarationName(ReadSelector(F, Record, Idx));
7694
7695 case DeclarationName::CXXConstructorName:
7696 return Context.DeclarationNames.getCXXConstructorName(
7697 Context.getCanonicalType(readType(F, Record, Idx)));
7698
7699 case DeclarationName::CXXDestructorName:
7700 return Context.DeclarationNames.getCXXDestructorName(
7701 Context.getCanonicalType(readType(F, Record, Idx)));
7702
7703 case DeclarationName::CXXConversionFunctionName:
7704 return Context.DeclarationNames.getCXXConversionFunctionName(
7705 Context.getCanonicalType(readType(F, Record, Idx)));
7706
7707 case DeclarationName::CXXOperatorName:
7708 return Context.DeclarationNames.getCXXOperatorName(
7709 (OverloadedOperatorKind)Record[Idx++]);
7710
7711 case DeclarationName::CXXLiteralOperatorName:
7712 return Context.DeclarationNames.getCXXLiteralOperatorName(
7713 GetIdentifierInfo(F, Record, Idx));
7714
7715 case DeclarationName::CXXUsingDirective:
7716 return DeclarationName::getUsingDirectiveName();
7717 }
7718
7719 llvm_unreachable("Invalid NameKind!");
7720}
7721
7722void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7723 DeclarationNameLoc &DNLoc,
7724 DeclarationName Name,
7725 const RecordData &Record, unsigned &Idx) {
7726 switch (Name.getNameKind()) {
7727 case DeclarationName::CXXConstructorName:
7728 case DeclarationName::CXXDestructorName:
7729 case DeclarationName::CXXConversionFunctionName:
7730 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7731 break;
7732
7733 case DeclarationName::CXXOperatorName:
7734 DNLoc.CXXOperatorName.BeginOpNameLoc
7735 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7736 DNLoc.CXXOperatorName.EndOpNameLoc
7737 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7738 break;
7739
7740 case DeclarationName::CXXLiteralOperatorName:
7741 DNLoc.CXXLiteralOperatorName.OpNameLoc
7742 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7743 break;
7744
7745 case DeclarationName::Identifier:
7746 case DeclarationName::ObjCZeroArgSelector:
7747 case DeclarationName::ObjCOneArgSelector:
7748 case DeclarationName::ObjCMultiArgSelector:
7749 case DeclarationName::CXXUsingDirective:
7750 break;
7751 }
7752}
7753
7754void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7755 DeclarationNameInfo &NameInfo,
7756 const RecordData &Record, unsigned &Idx) {
7757 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7758 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7759 DeclarationNameLoc DNLoc;
7760 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7761 NameInfo.setInfo(DNLoc);
7762}
7763
7764void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7765 const RecordData &Record, unsigned &Idx) {
7766 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7767 unsigned NumTPLists = Record[Idx++];
7768 Info.NumTemplParamLists = NumTPLists;
7769 if (NumTPLists) {
7770 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7771 for (unsigned i=0; i != NumTPLists; ++i)
7772 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7773 }
7774}
7775
7776TemplateName
7777ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7778 unsigned &Idx) {
7779 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7780 switch (Kind) {
7781 case TemplateName::Template:
7782 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7783
7784 case TemplateName::OverloadedTemplate: {
7785 unsigned size = Record[Idx++];
7786 UnresolvedSet<8> Decls;
7787 while (size--)
7788 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7789
7790 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7791 }
7792
7793 case TemplateName::QualifiedTemplate: {
7794 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7795 bool hasTemplKeyword = Record[Idx++];
7796 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7797 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7798 }
7799
7800 case TemplateName::DependentTemplate: {
7801 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7802 if (Record[Idx++]) // isIdentifier
7803 return Context.getDependentTemplateName(NNS,
7804 GetIdentifierInfo(F, Record,
7805 Idx));
7806 return Context.getDependentTemplateName(NNS,
7807 (OverloadedOperatorKind)Record[Idx++]);
7808 }
7809
7810 case TemplateName::SubstTemplateTemplateParm: {
7811 TemplateTemplateParmDecl *param
7812 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7813 if (!param) return TemplateName();
7814 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7815 return Context.getSubstTemplateTemplateParm(param, replacement);
7816 }
7817
7818 case TemplateName::SubstTemplateTemplateParmPack: {
7819 TemplateTemplateParmDecl *Param
7820 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7821 if (!Param)
7822 return TemplateName();
7823
7824 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7825 if (ArgPack.getKind() != TemplateArgument::Pack)
7826 return TemplateName();
7827
7828 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7829 }
7830 }
7831
7832 llvm_unreachable("Unhandled template name kind!");
7833}
7834
7835TemplateArgument
7836ASTReader::ReadTemplateArgument(ModuleFile &F,
7837 const RecordData &Record, unsigned &Idx) {
7838 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7839 switch (Kind) {
7840 case TemplateArgument::Null:
7841 return TemplateArgument();
7842 case TemplateArgument::Type:
7843 return TemplateArgument(readType(F, Record, Idx));
7844 case TemplateArgument::Declaration: {
7845 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007846 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007847 }
7848 case TemplateArgument::NullPtr:
7849 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7850 case TemplateArgument::Integral: {
7851 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7852 QualType T = readType(F, Record, Idx);
7853 return TemplateArgument(Context, Value, T);
7854 }
7855 case TemplateArgument::Template:
7856 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7857 case TemplateArgument::TemplateExpansion: {
7858 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007859 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007860 if (unsigned NumExpansions = Record[Idx++])
7861 NumTemplateExpansions = NumExpansions - 1;
7862 return TemplateArgument(Name, NumTemplateExpansions);
7863 }
7864 case TemplateArgument::Expression:
7865 return TemplateArgument(ReadExpr(F));
7866 case TemplateArgument::Pack: {
7867 unsigned NumArgs = Record[Idx++];
7868 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7869 for (unsigned I = 0; I != NumArgs; ++I)
7870 Args[I] = ReadTemplateArgument(F, Record, Idx);
7871 return TemplateArgument(Args, NumArgs);
7872 }
7873 }
7874
7875 llvm_unreachable("Unhandled template argument kind!");
7876}
7877
7878TemplateParameterList *
7879ASTReader::ReadTemplateParameterList(ModuleFile &F,
7880 const RecordData &Record, unsigned &Idx) {
7881 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7882 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7883 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7884
7885 unsigned NumParams = Record[Idx++];
7886 SmallVector<NamedDecl *, 16> Params;
7887 Params.reserve(NumParams);
7888 while (NumParams--)
7889 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7890
7891 TemplateParameterList* TemplateParams =
7892 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7893 Params.data(), Params.size(), RAngleLoc);
7894 return TemplateParams;
7895}
7896
7897void
7898ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007899ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007900 ModuleFile &F, const RecordData &Record,
7901 unsigned &Idx) {
7902 unsigned NumTemplateArgs = Record[Idx++];
7903 TemplArgs.reserve(NumTemplateArgs);
7904 while (NumTemplateArgs--)
7905 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7906}
7907
7908/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007909void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007910 const RecordData &Record, unsigned &Idx) {
7911 unsigned NumDecls = Record[Idx++];
7912 Set.reserve(Context, NumDecls);
7913 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007914 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007915 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007916 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007917 }
7918}
7919
7920CXXBaseSpecifier
7921ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7922 const RecordData &Record, unsigned &Idx) {
7923 bool isVirtual = static_cast<bool>(Record[Idx++]);
7924 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7925 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7926 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7927 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7928 SourceRange Range = ReadSourceRange(F, Record, Idx);
7929 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7930 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7931 EllipsisLoc);
7932 Result.setInheritConstructors(inheritConstructors);
7933 return Result;
7934}
7935
7936std::pair<CXXCtorInitializer **, unsigned>
7937ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7938 unsigned &Idx) {
Craig Toppera13603a2014-05-22 05:54:18 +00007939 CXXCtorInitializer **CtorInitializers = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007940 unsigned NumInitializers = Record[Idx++];
7941 if (NumInitializers) {
7942 CtorInitializers
7943 = new (Context) CXXCtorInitializer*[NumInitializers];
7944 for (unsigned i=0; i != NumInitializers; ++i) {
Craig Toppera13603a2014-05-22 05:54:18 +00007945 TypeSourceInfo *TInfo = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007946 bool IsBaseVirtual = false;
Craig Toppera13603a2014-05-22 05:54:18 +00007947 FieldDecl *Member = nullptr;
7948 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007949
7950 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7951 switch (Type) {
7952 case CTOR_INITIALIZER_BASE:
7953 TInfo = GetTypeSourceInfo(F, Record, Idx);
7954 IsBaseVirtual = Record[Idx++];
7955 break;
7956
7957 case CTOR_INITIALIZER_DELEGATING:
7958 TInfo = GetTypeSourceInfo(F, Record, Idx);
7959 break;
7960
7961 case CTOR_INITIALIZER_MEMBER:
7962 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7963 break;
7964
7965 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7966 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7967 break;
7968 }
7969
7970 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7971 Expr *Init = ReadExpr(F);
7972 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7973 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7974 bool IsWritten = Record[Idx++];
7975 unsigned SourceOrderOrNumArrayIndices;
7976 SmallVector<VarDecl *, 8> Indices;
7977 if (IsWritten) {
7978 SourceOrderOrNumArrayIndices = Record[Idx++];
7979 } else {
7980 SourceOrderOrNumArrayIndices = Record[Idx++];
7981 Indices.reserve(SourceOrderOrNumArrayIndices);
7982 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7983 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7984 }
7985
7986 CXXCtorInitializer *BOMInit;
7987 if (Type == CTOR_INITIALIZER_BASE) {
7988 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7989 LParenLoc, Init, RParenLoc,
7990 MemberOrEllipsisLoc);
7991 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7992 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7993 Init, RParenLoc);
7994 } else if (IsWritten) {
7995 if (Member)
7996 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7997 LParenLoc, Init, RParenLoc);
7998 else
7999 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
8000 MemberOrEllipsisLoc, LParenLoc,
8001 Init, RParenLoc);
8002 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00008003 if (IndirectMember) {
8004 assert(Indices.empty() && "Indirect field improperly initialized");
8005 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
8006 MemberOrEllipsisLoc, LParenLoc,
8007 Init, RParenLoc);
8008 } else {
8009 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
8010 LParenLoc, Init, RParenLoc,
8011 Indices.data(), Indices.size());
8012 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008013 }
8014
8015 if (IsWritten)
8016 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
8017 CtorInitializers[i] = BOMInit;
8018 }
8019 }
8020
8021 return std::make_pair(CtorInitializers, NumInitializers);
8022}
8023
8024NestedNameSpecifier *
8025ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8026 const RecordData &Record, unsigned &Idx) {
8027 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008028 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008029 for (unsigned I = 0; I != N; ++I) {
8030 NestedNameSpecifier::SpecifierKind Kind
8031 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8032 switch (Kind) {
8033 case NestedNameSpecifier::Identifier: {
8034 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8035 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8036 break;
8037 }
8038
8039 case NestedNameSpecifier::Namespace: {
8040 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8041 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8042 break;
8043 }
8044
8045 case NestedNameSpecifier::NamespaceAlias: {
8046 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8047 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8048 break;
8049 }
8050
8051 case NestedNameSpecifier::TypeSpec:
8052 case NestedNameSpecifier::TypeSpecWithTemplate: {
8053 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8054 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008055 return nullptr;
8056
Guy Benyei11169dd2012-12-18 14:30:41 +00008057 bool Template = Record[Idx++];
8058 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8059 break;
8060 }
8061
8062 case NestedNameSpecifier::Global: {
8063 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8064 // No associated value, and there can't be a prefix.
8065 break;
8066 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008067
8068 case NestedNameSpecifier::Super: {
8069 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8070 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8071 break;
8072 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008073 }
8074 Prev = NNS;
8075 }
8076 return NNS;
8077}
8078
8079NestedNameSpecifierLoc
8080ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8081 unsigned &Idx) {
8082 unsigned N = Record[Idx++];
8083 NestedNameSpecifierLocBuilder Builder;
8084 for (unsigned I = 0; I != N; ++I) {
8085 NestedNameSpecifier::SpecifierKind Kind
8086 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8087 switch (Kind) {
8088 case NestedNameSpecifier::Identifier: {
8089 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8090 SourceRange Range = ReadSourceRange(F, Record, Idx);
8091 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8092 break;
8093 }
8094
8095 case NestedNameSpecifier::Namespace: {
8096 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8097 SourceRange Range = ReadSourceRange(F, Record, Idx);
8098 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8099 break;
8100 }
8101
8102 case NestedNameSpecifier::NamespaceAlias: {
8103 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8104 SourceRange Range = ReadSourceRange(F, Record, Idx);
8105 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8106 break;
8107 }
8108
8109 case NestedNameSpecifier::TypeSpec:
8110 case NestedNameSpecifier::TypeSpecWithTemplate: {
8111 bool Template = Record[Idx++];
8112 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8113 if (!T)
8114 return NestedNameSpecifierLoc();
8115 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8116
8117 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8118 Builder.Extend(Context,
8119 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8120 T->getTypeLoc(), ColonColonLoc);
8121 break;
8122 }
8123
8124 case NestedNameSpecifier::Global: {
8125 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8126 Builder.MakeGlobal(Context, ColonColonLoc);
8127 break;
8128 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008129
8130 case NestedNameSpecifier::Super: {
8131 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8132 SourceRange Range = ReadSourceRange(F, Record, Idx);
8133 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8134 break;
8135 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008136 }
8137 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008138
Guy Benyei11169dd2012-12-18 14:30:41 +00008139 return Builder.getWithLocInContext(Context);
8140}
8141
8142SourceRange
8143ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8144 unsigned &Idx) {
8145 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8146 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8147 return SourceRange(beg, end);
8148}
8149
8150/// \brief Read an integral value
8151llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8152 unsigned BitWidth = Record[Idx++];
8153 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8154 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8155 Idx += NumWords;
8156 return Result;
8157}
8158
8159/// \brief Read a signed integral value
8160llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8161 bool isUnsigned = Record[Idx++];
8162 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8163}
8164
8165/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008166llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8167 const llvm::fltSemantics &Sem,
8168 unsigned &Idx) {
8169 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008170}
8171
8172// \brief Read a string
8173std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8174 unsigned Len = Record[Idx++];
8175 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8176 Idx += Len;
8177 return Result;
8178}
8179
Richard Smith7ed1bc92014-12-05 22:42:13 +00008180std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8181 unsigned &Idx) {
8182 std::string Filename = ReadString(Record, Idx);
8183 ResolveImportedPath(F, Filename);
8184 return Filename;
8185}
8186
Guy Benyei11169dd2012-12-18 14:30:41 +00008187VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8188 unsigned &Idx) {
8189 unsigned Major = Record[Idx++];
8190 unsigned Minor = Record[Idx++];
8191 unsigned Subminor = Record[Idx++];
8192 if (Minor == 0)
8193 return VersionTuple(Major);
8194 if (Subminor == 0)
8195 return VersionTuple(Major, Minor - 1);
8196 return VersionTuple(Major, Minor - 1, Subminor - 1);
8197}
8198
8199CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8200 const RecordData &Record,
8201 unsigned &Idx) {
8202 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8203 return CXXTemporary::Create(Context, Decl);
8204}
8205
8206DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008207 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008208}
8209
8210DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8211 return Diags.Report(Loc, DiagID);
8212}
8213
8214/// \brief Retrieve the identifier table associated with the
8215/// preprocessor.
8216IdentifierTable &ASTReader::getIdentifierTable() {
8217 return PP.getIdentifierTable();
8218}
8219
8220/// \brief Record that the given ID maps to the given switch-case
8221/// statement.
8222void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008223 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008224 "Already have a SwitchCase with this ID");
8225 (*CurrSwitchCaseStmts)[ID] = SC;
8226}
8227
8228/// \brief Retrieve the switch-case statement with the given ID.
8229SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008230 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008231 return (*CurrSwitchCaseStmts)[ID];
8232}
8233
8234void ASTReader::ClearSwitchCaseIDs() {
8235 CurrSwitchCaseStmts->clear();
8236}
8237
8238void ASTReader::ReadComments() {
8239 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008240 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008241 serialization::ModuleFile *> >::iterator
8242 I = CommentsCursors.begin(),
8243 E = CommentsCursors.end();
8244 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008245 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008246 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008247 serialization::ModuleFile &F = *I->second;
8248 SavedStreamPosition SavedPosition(Cursor);
8249
8250 RecordData Record;
8251 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008252 llvm::BitstreamEntry Entry =
8253 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008254
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008255 switch (Entry.Kind) {
8256 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8257 case llvm::BitstreamEntry::Error:
8258 Error("malformed block record in AST file");
8259 return;
8260 case llvm::BitstreamEntry::EndBlock:
8261 goto NextCursor;
8262 case llvm::BitstreamEntry::Record:
8263 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008264 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008265 }
8266
8267 // Read a record.
8268 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008269 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008270 case COMMENTS_RAW_COMMENT: {
8271 unsigned Idx = 0;
8272 SourceRange SR = ReadSourceRange(F, Record, Idx);
8273 RawComment::CommentKind Kind =
8274 (RawComment::CommentKind) Record[Idx++];
8275 bool IsTrailingComment = Record[Idx++];
8276 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008277 Comments.push_back(new (Context) RawComment(
8278 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8279 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008280 break;
8281 }
8282 }
8283 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008284 NextCursor:
8285 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008286 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008287}
8288
Argyrios Kyrtzidis1bde1172014-11-18 05:24:18 +00008289void ASTReader::getInputFiles(ModuleFile &F,
8290 SmallVectorImpl<serialization::InputFile> &Files) {
8291 for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
8292 unsigned ID = I+1;
8293 Files.push_back(getInputFile(F, ID));
8294 }
8295}
8296
Richard Smithcd45dbc2014-04-19 03:48:30 +00008297std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8298 // If we know the owning module, use it.
8299 if (Module *M = D->getOwningModule())
8300 return M->getFullModuleName();
8301
8302 // Otherwise, use the name of the top-level module the decl is within.
8303 if (ModuleFile *M = getOwningModuleFile(D))
8304 return M->ModuleName;
8305
8306 // Not from a module.
8307 return "";
8308}
8309
Guy Benyei11169dd2012-12-18 14:30:41 +00008310void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008311 while (!PendingIdentifierInfos.empty() ||
8312 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008313 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008314 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008315 // If any identifiers with corresponding top-level declarations have
8316 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008317 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8318 TopLevelDeclsMap;
8319 TopLevelDeclsMap TopLevelDecls;
8320
Guy Benyei11169dd2012-12-18 14:30:41 +00008321 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008322 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008323 SmallVector<uint32_t, 4> DeclIDs =
8324 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008325 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008326
8327 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008328 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008329
Richard Smith851072e2014-05-19 20:59:20 +00008330 // For each decl chain that we wanted to complete while deserializing, mark
8331 // it as "still needs to be completed".
8332 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8333 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8334 }
8335 PendingIncompleteDeclChains.clear();
8336
Guy Benyei11169dd2012-12-18 14:30:41 +00008337 // Load pending declaration chains.
8338 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
8339 loadPendingDeclChain(PendingDeclChains[I]);
8340 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
8341 }
8342 PendingDeclChains.clear();
8343
Douglas Gregor6168bd22013-02-18 15:53:43 +00008344 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008345 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8346 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008347 IdentifierInfo *II = TLD->first;
8348 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008349 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008350 }
8351 }
8352
Guy Benyei11169dd2012-12-18 14:30:41 +00008353 // Load any pending macro definitions.
8354 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008355 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8356 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8357 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8358 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008359 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008360 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008361 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008362 if (Info.M->Kind != MK_ImplicitModule &&
8363 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008364 resolvePendingMacro(II, Info);
8365 }
8366 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008367 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008368 ++IDIdx) {
8369 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008370 if (Info.M->Kind == MK_ImplicitModule ||
8371 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008372 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008373 }
8374 }
8375 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008376
8377 // Wire up the DeclContexts for Decls that we delayed setting until
8378 // recursive loading is completed.
8379 while (!PendingDeclContextInfos.empty()) {
8380 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8381 PendingDeclContextInfos.pop_front();
8382 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8383 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8384 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8385 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008386
Richard Smithd1c46742014-04-30 02:24:17 +00008387 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008388 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008389 auto Update = PendingUpdateRecords.pop_back_val();
8390 ReadingKindTracker ReadingKind(Read_Decl, *this);
8391 loadDeclUpdateRecords(Update.first, Update.second);
8392 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008393 }
Richard Smith8a639892015-01-24 01:07:20 +00008394
8395 // At this point, all update records for loaded decls are in place, so any
8396 // fake class definitions should have become real.
8397 assert(PendingFakeDefinitionData.empty() &&
8398 "faked up a class definition but never saw the real one");
8399
Guy Benyei11169dd2012-12-18 14:30:41 +00008400 // If we deserialized any C++ or Objective-C class definitions, any
8401 // Objective-C protocol definitions, or any redeclarable templates, make sure
8402 // that all redeclarations point to the definitions. Note that this can only
8403 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008404 for (Decl *D : PendingDefinitions) {
8405 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008406 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008407 // Make sure that the TagType points at the definition.
8408 const_cast<TagType*>(TagT)->decl = TD;
8409 }
8410
Craig Topperc6914d02014-08-25 04:15:02 +00008411 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith2c381642014-08-27 23:11:59 +00008412 for (auto R : RD->redecls()) {
8413 assert((R == D) == R->isThisDeclarationADefinition() &&
8414 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008415 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008416 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008417 }
8418
8419 continue;
8420 }
8421
Craig Topperc6914d02014-08-25 04:15:02 +00008422 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008423 // Make sure that the ObjCInterfaceType points at the definition.
8424 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8425 ->Decl = ID;
8426
Aaron Ballman86c93902014-03-06 23:45:36 +00008427 for (auto R : ID->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008428 R->Data = ID->Data;
8429
8430 continue;
8431 }
8432
Craig Topperc6914d02014-08-25 04:15:02 +00008433 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Aaron Ballman86c93902014-03-06 23:45:36 +00008434 for (auto R : PD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008435 R->Data = PD->Data;
8436
8437 continue;
8438 }
8439
Craig Topperc6914d02014-08-25 04:15:02 +00008440 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00008441 for (auto R : RTD->redecls())
Guy Benyei11169dd2012-12-18 14:30:41 +00008442 R->Common = RTD->Common;
8443 }
8444 PendingDefinitions.clear();
8445
8446 // Load the bodies of any functions or methods we've encountered. We do
8447 // this now (delayed) so that we can be sure that the declaration chains
8448 // have been fully wired up.
8449 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8450 PBEnd = PendingBodies.end();
8451 PB != PBEnd; ++PB) {
8452 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8453 // FIXME: Check for =delete/=default?
8454 // FIXME: Complain about ODR violations here?
8455 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8456 FD->setLazyBody(PB->second);
8457 continue;
8458 }
8459
8460 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8461 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8462 MD->setLazyBody(PB->second);
8463 }
8464 PendingBodies.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008465}
8466
8467void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008468 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8469 return;
8470
Richard Smitha0ce9c42014-07-29 23:23:27 +00008471 // Trigger the import of the full definition of each class that had any
8472 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008473 // These updates may in turn find and diagnose some ODR failures, so take
8474 // ownership of the set first.
8475 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8476 PendingOdrMergeFailures.clear();
8477 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008478 Merge.first->buildLookup();
8479 Merge.first->decls_begin();
8480 Merge.first->bases_begin();
8481 Merge.first->vbases_begin();
8482 for (auto *RD : Merge.second) {
8483 RD->decls_begin();
8484 RD->bases_begin();
8485 RD->vbases_begin();
8486 }
8487 }
8488
8489 // For each declaration from a merged context, check that the canonical
8490 // definition of that context also contains a declaration of the same
8491 // entity.
8492 //
8493 // Caution: this loop does things that might invalidate iterators into
8494 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8495 while (!PendingOdrMergeChecks.empty()) {
8496 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8497
8498 // FIXME: Skip over implicit declarations for now. This matters for things
8499 // like implicitly-declared special member functions. This isn't entirely
8500 // correct; we can end up with multiple unmerged declarations of the same
8501 // implicit entity.
8502 if (D->isImplicit())
8503 continue;
8504
8505 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008506
8507 bool Found = false;
8508 const Decl *DCanon = D->getCanonicalDecl();
8509
Richard Smith01bdb7a2014-08-28 05:44:07 +00008510 for (auto RI : D->redecls()) {
8511 if (RI->getLexicalDeclContext() == CanonDef) {
8512 Found = true;
8513 break;
8514 }
8515 }
8516 if (Found)
8517 continue;
8518
Richard Smitha0ce9c42014-07-29 23:23:27 +00008519 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith01bdb7a2014-08-28 05:44:07 +00008520 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
Richard Smitha0ce9c42014-07-29 23:23:27 +00008521 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8522 !Found && I != E; ++I) {
8523 for (auto RI : (*I)->redecls()) {
8524 if (RI->getLexicalDeclContext() == CanonDef) {
8525 // This declaration is present in the canonical definition. If it's
8526 // in the same redecl chain, it's the one we're looking for.
8527 if (RI->getCanonicalDecl() == DCanon)
8528 Found = true;
8529 else
8530 Candidates.push_back(cast<NamedDecl>(RI));
8531 break;
8532 }
8533 }
8534 }
8535
8536 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008537 // The AST doesn't like TagDecls becoming invalid after they've been
8538 // completed. We only really need to mark FieldDecls as invalid here.
8539 if (!isa<TagDecl>(D))
8540 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008541
8542 // Ensure we don't accidentally recursively enter deserialization while
8543 // we're producing our diagnostic.
8544 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008545
8546 std::string CanonDefModule =
8547 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8548 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8549 << D << getOwningModuleNameForDiagnostic(D)
8550 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8551
8552 if (Candidates.empty())
8553 Diag(cast<Decl>(CanonDef)->getLocation(),
8554 diag::note_module_odr_violation_no_possible_decls) << D;
8555 else {
8556 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8557 Diag(Candidates[I]->getLocation(),
8558 diag::note_module_odr_violation_possible_decl)
8559 << Candidates[I];
8560 }
8561
8562 DiagnosedOdrMergeFailures.insert(CanonDef);
8563 }
8564 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008565
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008566 if (OdrMergeFailures.empty())
8567 return;
8568
8569 // Ensure we don't accidentally recursively enter deserialization while
8570 // we're producing our diagnostics.
8571 Deserializing RecursionGuard(this);
8572
Richard Smithcd45dbc2014-04-19 03:48:30 +00008573 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008574 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008575 // If we've already pointed out a specific problem with this class, don't
8576 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008577 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008578 continue;
8579
8580 bool Diagnosed = false;
8581 for (auto *RD : Merge.second) {
8582 // Multiple different declarations got merged together; tell the user
8583 // where they came from.
8584 if (Merge.first != RD) {
8585 // FIXME: Walk the definition, figure out what's different,
8586 // and diagnose that.
8587 if (!Diagnosed) {
8588 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8589 Diag(Merge.first->getLocation(),
8590 diag::err_module_odr_violation_different_definitions)
8591 << Merge.first << Module.empty() << Module;
8592 Diagnosed = true;
8593 }
8594
8595 Diag(RD->getLocation(),
8596 diag::note_module_odr_violation_different_definitions)
8597 << getOwningModuleNameForDiagnostic(RD);
8598 }
8599 }
8600
8601 if (!Diagnosed) {
8602 // All definitions are updates to the same declaration. This happens if a
8603 // module instantiates the declaration of a class template specialization
8604 // and two or more other modules instantiate its definition.
8605 //
8606 // FIXME: Indicate which modules had instantiations of this definition.
8607 // FIXME: How can this even happen?
8608 Diag(Merge.first->getLocation(),
8609 diag::err_module_odr_violation_different_instantiations)
8610 << Merge.first;
8611 }
8612 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008613}
8614
8615void ASTReader::FinishedDeserializing() {
8616 assert(NumCurrentElementsDeserializing &&
8617 "FinishedDeserializing not paired with StartedDeserializing");
8618 if (NumCurrentElementsDeserializing == 1) {
8619 // We decrease NumCurrentElementsDeserializing only after pending actions
8620 // are finished, to avoid recursively re-calling finishPendingActions().
8621 finishPendingActions();
8622 }
8623 --NumCurrentElementsDeserializing;
8624
Richard Smitha0ce9c42014-07-29 23:23:27 +00008625 if (NumCurrentElementsDeserializing == 0) {
8626 diagnoseOdrViolations();
8627
Richard Smith04d05b52014-03-23 00:27:18 +00008628 // We are not in recursive loading, so it's safe to pass the "interesting"
8629 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008630 if (Consumer)
8631 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008632 }
8633}
8634
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008635void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00008636 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008637
8638 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8639 SemaObj->TUScope->AddDecl(D);
8640 } else if (SemaObj->TUScope) {
8641 // Adding the decl to IdResolver may have failed because it was already in
8642 // (even though it was not added in scope). If it is already in, make sure
8643 // it gets in the scope as well.
8644 if (std::find(SemaObj->IdResolver.begin(Name),
8645 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8646 SemaObj->TUScope->AddDecl(D);
8647 }
8648}
8649
Nico Weber824285e2014-05-08 04:26:47 +00008650ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8651 bool DisableValidation, bool AllowASTWithCompilerErrors,
8652 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008653 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008654 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008655 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Craig Toppera13603a2014-05-22 05:54:18 +00008656 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
8657 SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
8658 ModuleMgr(PP.getFileManager()), isysroot(isysroot),
8659 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008660 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8661 AllowConfigurationMismatch(AllowConfigurationMismatch),
8662 ValidateSystemInputs(ValidateSystemInputs),
8663 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Richard Smith053f6c62014-05-16 23:01:30 +00008664 CurrSwitchCaseStmts(&SwitchCaseStmts),
Nico Weber824285e2014-05-08 04:26:47 +00008665 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8666 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8667 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8668 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8669 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8670 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8671 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8672 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8673 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8674 PassingDeclsToConsumer(false), NumCXXBaseSpecifiersLoaded(0),
8675 ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008676 SourceMgr.setExternalSLocEntrySource(this);
8677}
8678
8679ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008680 if (OwnsDeserializationListener)
8681 delete DeserializationListener;
8682
Guy Benyei11169dd2012-12-18 14:30:41 +00008683 for (DeclContextVisibleUpdatesPending::iterator
8684 I = PendingVisibleUpdates.begin(),
8685 E = PendingVisibleUpdates.end();
8686 I != E; ++I) {
8687 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8688 F = I->second.end();
8689 J != F; ++J)
8690 delete J->first;
8691 }
8692}