blob: ec14eec2ab3bde60b3f26bf7c1a9a2ce9d3b6fbf [file] [log] [blame]
Nick Lewyckyf0f56162013-01-31 03:23:57 +00001//===--- ASTReader.cpp - AST File Reader ----------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the ASTReader class, which reads AST files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Serialization/ASTReader.h"
15#include "ASTCommon.h"
16#include "ASTReaderInternals.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/NestedNameSpecifier.h"
23#include "clang/AST/Type.h"
24#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000025#include "clang/Basic/DiagnosticOptions.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000026#include "clang/Basic/FileManager.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000027#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/SourceManagerInternals.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Basic/TargetOptions.h"
31#include "clang/Basic/Version.h"
32#include "clang/Basic/VersionTuple.h"
Ben Langmuirb92de022014-04-29 16:25:26 +000033#include "clang/Frontend/Utils.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000034#include "clang/Lex/HeaderSearch.h"
35#include "clang/Lex/HeaderSearchOptions.h"
36#include "clang/Lex/MacroInfo.h"
37#include "clang/Lex/PreprocessingRecord.h"
38#include "clang/Lex/Preprocessor.h"
39#include "clang/Lex/PreprocessorOptions.h"
40#include "clang/Sema/Scope.h"
41#include "clang/Sema/Sema.h"
42#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000043#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000044#include "clang/Serialization/ModuleManager.h"
45#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000046#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000047#include "llvm/ADT/StringExtras.h"
48#include "llvm/Bitcode/BitstreamReader.h"
49#include "llvm/Support/ErrorHandling.h"
50#include "llvm/Support/FileSystem.h"
51#include "llvm/Support/MemoryBuffer.h"
52#include "llvm/Support/Path.h"
53#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000054#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000055#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000056#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000057#include <iterator>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000058#include <system_error>
Guy Benyei11169dd2012-12-18 14:30:41 +000059
60using namespace clang;
61using namespace clang::serialization;
62using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000063using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000064
Ben Langmuircb69b572014-03-07 06:40:32 +000065
66//===----------------------------------------------------------------------===//
67// ChainedASTReaderListener implementation
68//===----------------------------------------------------------------------===//
69
70bool
71ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
72 return First->ReadFullVersionInformation(FullVersion) ||
73 Second->ReadFullVersionInformation(FullVersion);
74}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000075void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
76 First->ReadModuleName(ModuleName);
77 Second->ReadModuleName(ModuleName);
78}
79void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
80 First->ReadModuleMapFile(ModuleMapPath);
81 Second->ReadModuleMapFile(ModuleMapPath);
82}
Richard Smith1e2cf0d2014-10-31 02:28:58 +000083bool
84ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
85 bool Complain,
86 bool AllowCompatibleDifferences) {
87 return First->ReadLanguageOptions(LangOpts, Complain,
88 AllowCompatibleDifferences) ||
89 Second->ReadLanguageOptions(LangOpts, Complain,
90 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000091}
Chandler Carruth0d745bc2015-03-14 04:47:43 +000092bool ChainedASTReaderListener::ReadTargetOptions(
93 const TargetOptions &TargetOpts, bool Complain,
94 bool AllowCompatibleDifferences) {
95 return First->ReadTargetOptions(TargetOpts, Complain,
96 AllowCompatibleDifferences) ||
97 Second->ReadTargetOptions(TargetOpts, Complain,
98 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000099}
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,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000237 DiagnosticsEngine *Diags,
238 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000239#define CHECK_TARGET_OPT(Field, Name) \
240 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
241 if (Diags) \
242 Diags->Report(diag::err_pch_targetopt_mismatch) \
243 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
244 return true; \
245 }
246
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000247 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000248 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000249 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000250
251 // We can tolerate different CPUs in many cases, notably when one CPU
252 // supports a strict superset of another. When allowing compatible
253 // differences skip this check.
254 if (!AllowCompatibleDifferences)
255 CHECK_TARGET_OPT(CPU, "target CPU");
256
Guy Benyei11169dd2012-12-18 14:30:41 +0000257#undef CHECK_TARGET_OPT
258
259 // Compare feature sets.
260 SmallVector<StringRef, 4> ExistingFeatures(
261 ExistingTargetOpts.FeaturesAsWritten.begin(),
262 ExistingTargetOpts.FeaturesAsWritten.end());
263 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
264 TargetOpts.FeaturesAsWritten.end());
265 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
266 std::sort(ReadFeatures.begin(), ReadFeatures.end());
267
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000268 // We compute the set difference in both directions explicitly so that we can
269 // diagnose the differences differently.
270 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
271 std::set_difference(
272 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
273 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
274 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
275 ExistingFeatures.begin(), ExistingFeatures.end(),
276 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000277
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000278 // If we are allowing compatible differences and the read feature set is
279 // a strict subset of the existing feature set, there is nothing to diagnose.
280 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
281 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000282
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000283 if (Diags) {
284 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000285 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000286 << /* is-existing-feature */ false << Feature;
287 for (StringRef Feature : UnmatchedExistingFeatures)
288 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
289 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000290 }
291
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000292 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000293}
294
295bool
296PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000297 bool Complain,
298 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000299 const LangOptions &ExistingLangOpts = PP.getLangOpts();
300 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000301 Complain ? &Reader.Diags : nullptr,
302 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000303}
304
305bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000306 bool Complain,
307 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000308 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
309 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000310 Complain ? &Reader.Diags : nullptr,
311 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000312}
313
314namespace {
315 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
316 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000317 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
318 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000319}
320
Ben Langmuirb92de022014-04-29 16:25:26 +0000321static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
322 DiagnosticsEngine &Diags,
323 bool Complain) {
324 typedef DiagnosticsEngine::Level Level;
325
326 // Check current mappings for new -Werror mappings, and the stored mappings
327 // for cases that were explicitly mapped to *not* be errors that are now
328 // errors because of options like -Werror.
329 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
330
331 for (DiagnosticsEngine *MappingSource : MappingSources) {
332 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
333 diag::kind DiagID = DiagIDMappingPair.first;
334 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
335 if (CurLevel < DiagnosticsEngine::Error)
336 continue; // not significant
337 Level StoredLevel =
338 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
339 if (StoredLevel < DiagnosticsEngine::Error) {
340 if (Complain)
341 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
342 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
343 return true;
344 }
345 }
346 }
347
348 return false;
349}
350
Alp Tokerac4e8e52014-06-22 21:58:33 +0000351static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
352 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
353 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
354 return true;
355 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000356}
357
358static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
359 DiagnosticsEngine &Diags,
360 bool IsSystem, bool Complain) {
361 // Top-level options
362 if (IsSystem) {
363 if (Diags.getSuppressSystemWarnings())
364 return false;
365 // If -Wsystem-headers was not enabled before, be conservative
366 if (StoredDiags.getSuppressSystemWarnings()) {
367 if (Complain)
368 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
369 return true;
370 }
371 }
372
373 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
374 if (Complain)
375 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
376 return true;
377 }
378
379 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
380 !StoredDiags.getEnableAllWarnings()) {
381 if (Complain)
382 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
383 return true;
384 }
385
386 if (isExtHandlingFromDiagsError(Diags) &&
387 !isExtHandlingFromDiagsError(StoredDiags)) {
388 if (Complain)
389 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
390 return true;
391 }
392
393 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
394}
395
396bool PCHValidator::ReadDiagnosticOptions(
397 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
398 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
399 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
400 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000401 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000402 // This should never fail, because we would have processed these options
403 // before writing them to an ASTFile.
404 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
405
406 ModuleManager &ModuleMgr = Reader.getModuleManager();
407 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
408
409 // If the original import came from a file explicitly generated by the user,
410 // don't check the diagnostic mappings.
411 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000412 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000413 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
414 // the transitive closure of its imports, since unrelated modules cannot be
415 // imported until after this module finishes validation.
416 ModuleFile *TopImport = *ModuleMgr.rbegin();
417 while (!TopImport->ImportedBy.empty())
418 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000419 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000420 return false;
421
422 StringRef ModuleName = TopImport->ModuleName;
423 assert(!ModuleName.empty() && "diagnostic options read before module name");
424
425 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
426 assert(M && "missing module");
427
428 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
429 // contains the union of their flags.
430 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
431}
432
Guy Benyei11169dd2012-12-18 14:30:41 +0000433/// \brief Collect the macro definitions provided by the given preprocessor
434/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000435static void
436collectMacroDefinitions(const PreprocessorOptions &PPOpts,
437 MacroDefinitionsMap &Macros,
438 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000439 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
440 StringRef Macro = PPOpts.Macros[I].first;
441 bool IsUndef = PPOpts.Macros[I].second;
442
443 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
444 StringRef MacroName = MacroPair.first;
445 StringRef MacroBody = MacroPair.second;
446
447 // For an #undef'd macro, we only care about the name.
448 if (IsUndef) {
449 if (MacroNames && !Macros.count(MacroName))
450 MacroNames->push_back(MacroName);
451
452 Macros[MacroName] = std::make_pair("", true);
453 continue;
454 }
455
456 // For a #define'd macro, figure out the actual definition.
457 if (MacroName.size() == Macro.size())
458 MacroBody = "1";
459 else {
460 // Note: GCC drops anything following an end-of-line character.
461 StringRef::size_type End = MacroBody.find_first_of("\n\r");
462 MacroBody = MacroBody.substr(0, End);
463 }
464
465 if (MacroNames && !Macros.count(MacroName))
466 MacroNames->push_back(MacroName);
467 Macros[MacroName] = std::make_pair(MacroBody, false);
468 }
469}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000470
Guy Benyei11169dd2012-12-18 14:30:41 +0000471/// \brief Check the preprocessor options deserialized from the control block
472/// against the preprocessor options in an existing preprocessor.
473///
474/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
475static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
476 const PreprocessorOptions &ExistingPPOpts,
477 DiagnosticsEngine *Diags,
478 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000479 std::string &SuggestedPredefines,
480 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000481 // Check macro definitions.
482 MacroDefinitionsMap ASTFileMacros;
483 collectMacroDefinitions(PPOpts, ASTFileMacros);
484 MacroDefinitionsMap ExistingMacros;
485 SmallVector<StringRef, 4> ExistingMacroNames;
486 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
487
488 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
489 // Dig out the macro definition in the existing preprocessor options.
490 StringRef MacroName = ExistingMacroNames[I];
491 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
492
493 // Check whether we know anything about this macro name or not.
494 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
495 = ASTFileMacros.find(MacroName);
496 if (Known == ASTFileMacros.end()) {
497 // FIXME: Check whether this identifier was referenced anywhere in the
498 // AST file. If so, we should reject the AST file. Unfortunately, this
499 // information isn't in the control block. What shall we do about it?
500
501 if (Existing.second) {
502 SuggestedPredefines += "#undef ";
503 SuggestedPredefines += MacroName.str();
504 SuggestedPredefines += '\n';
505 } else {
506 SuggestedPredefines += "#define ";
507 SuggestedPredefines += MacroName.str();
508 SuggestedPredefines += ' ';
509 SuggestedPredefines += Existing.first.str();
510 SuggestedPredefines += '\n';
511 }
512 continue;
513 }
514
515 // If the macro was defined in one but undef'd in the other, we have a
516 // conflict.
517 if (Existing.second != Known->second.second) {
518 if (Diags) {
519 Diags->Report(diag::err_pch_macro_def_undef)
520 << MacroName << Known->second.second;
521 }
522 return true;
523 }
524
525 // If the macro was #undef'd in both, or if the macro bodies are identical,
526 // it's fine.
527 if (Existing.second || Existing.first == Known->second.first)
528 continue;
529
530 // The macro bodies differ; complain.
531 if (Diags) {
532 Diags->Report(diag::err_pch_macro_def_conflict)
533 << MacroName << Known->second.first << Existing.first;
534 }
535 return true;
536 }
537
538 // Check whether we're using predefines.
539 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
540 if (Diags) {
541 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
542 }
543 return true;
544 }
545
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000546 // Detailed record is important since it is used for the module cache hash.
547 if (LangOpts.Modules &&
548 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
549 if (Diags) {
550 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
551 }
552 return true;
553 }
554
Guy Benyei11169dd2012-12-18 14:30:41 +0000555 // Compute the #include and #include_macros lines we need.
556 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
557 StringRef File = ExistingPPOpts.Includes[I];
558 if (File == ExistingPPOpts.ImplicitPCHInclude)
559 continue;
560
561 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
562 != PPOpts.Includes.end())
563 continue;
564
565 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000566 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000567 SuggestedPredefines += "\"\n";
568 }
569
570 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
571 StringRef File = ExistingPPOpts.MacroIncludes[I];
572 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
573 File)
574 != PPOpts.MacroIncludes.end())
575 continue;
576
577 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000578 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000579 SuggestedPredefines += "\"\n##\n";
580 }
581
582 return false;
583}
584
585bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
586 bool Complain,
587 std::string &SuggestedPredefines) {
588 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
589
590 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000591 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000592 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000593 SuggestedPredefines,
594 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000595}
596
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000597/// Check the header search options deserialized from the control block
598/// against the header search options in an existing preprocessor.
599///
600/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
601static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
602 StringRef SpecificModuleCachePath,
603 StringRef ExistingModuleCachePath,
604 DiagnosticsEngine *Diags,
605 const LangOptions &LangOpts) {
606 if (LangOpts.Modules) {
607 if (SpecificModuleCachePath != ExistingModuleCachePath) {
608 if (Diags)
609 Diags->Report(diag::err_pch_modulecache_mismatch)
610 << SpecificModuleCachePath << ExistingModuleCachePath;
611 return true;
612 }
613 }
614
615 return false;
616}
617
618bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
619 StringRef SpecificModuleCachePath,
620 bool Complain) {
621 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
622 PP.getHeaderSearchInfo().getModuleCachePath(),
623 Complain ? &Reader.Diags : nullptr,
624 PP.getLangOpts());
625}
626
Guy Benyei11169dd2012-12-18 14:30:41 +0000627void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
628 PP.setCounterValue(Value);
629}
630
631//===----------------------------------------------------------------------===//
632// AST reader implementation
633//===----------------------------------------------------------------------===//
634
Nico Weber824285e2014-05-08 04:26:47 +0000635void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
636 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000637 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000638 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000639}
640
641
642
643unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
644 return serialization::ComputeHash(Sel);
645}
646
647
648std::pair<unsigned, unsigned>
649ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000650 using namespace llvm::support;
651 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
652 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000653 return std::make_pair(KeyLen, DataLen);
654}
655
656ASTSelectorLookupTrait::internal_key_type
657ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000658 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000659 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000660 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
661 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
662 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000663 if (N == 0)
664 return SelTable.getNullarySelector(FirstII);
665 else if (N == 1)
666 return SelTable.getUnarySelector(FirstII);
667
668 SmallVector<IdentifierInfo *, 16> Args;
669 Args.push_back(FirstII);
670 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000671 Args.push_back(Reader.getLocalIdentifier(
672 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000673
674 return SelTable.getSelector(N, Args.data());
675}
676
677ASTSelectorLookupTrait::data_type
678ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
679 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000680 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000681
682 data_type Result;
683
Justin Bogner57ba0b22014-03-28 22:03:24 +0000684 Result.ID = Reader.getGlobalSelectorID(
685 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000686 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
687 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
688 Result.InstanceBits = FullInstanceBits & 0x3;
689 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
690 Result.FactoryBits = FullFactoryBits & 0x3;
691 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
692 unsigned NumInstanceMethods = FullInstanceBits >> 3;
693 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000694
695 // Load instance methods
696 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000697 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
698 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000699 Result.Instance.push_back(Method);
700 }
701
702 // Load factory methods
703 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000704 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
705 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000706 Result.Factory.push_back(Method);
707 }
708
709 return Result;
710}
711
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000712unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
713 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000714}
715
716std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000717ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000718 using namespace llvm::support;
719 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
720 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000721 return std::make_pair(KeyLen, DataLen);
722}
723
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000724ASTIdentifierLookupTraitBase::internal_key_type
725ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000726 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000727 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000728}
729
Douglas Gregordcf25082013-02-11 18:16:18 +0000730/// \brief Whether the given identifier is "interesting".
731static bool isInterestingIdentifier(IdentifierInfo &II) {
732 return II.isPoisoned() ||
733 II.isExtensionToken() ||
734 II.getObjCOrBuiltinID() ||
735 II.hasRevertedTokenIDToIdentifier() ||
736 II.hadMacroDefinition() ||
737 II.getFETokenInfo<void>();
738}
739
Guy Benyei11169dd2012-12-18 14:30:41 +0000740IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
741 const unsigned char* d,
742 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000743 using namespace llvm::support;
744 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000745 bool IsInteresting = RawID & 0x01;
746
747 // Wipe out the "is interesting" bit.
748 RawID = RawID >> 1;
749
750 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
751 if (!IsInteresting) {
752 // For uninteresting identifiers, just build the IdentifierInfo
753 // and associate it with the persistent ID.
754 IdentifierInfo *II = KnownII;
755 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000756 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000757 KnownII = II;
758 }
759 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000760 if (!II->isFromAST()) {
761 bool WasInteresting = isInterestingIdentifier(*II);
762 II->setIsFromAST();
763 if (WasInteresting)
764 II->setChangedSinceDeserialization();
765 }
766 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000767 return II;
768 }
769
Justin Bogner57ba0b22014-03-28 22:03:24 +0000770 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
771 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000772 bool CPlusPlusOperatorKeyword = Bits & 0x01;
773 Bits >>= 1;
774 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
775 Bits >>= 1;
776 bool Poisoned = Bits & 0x01;
777 Bits >>= 1;
778 bool ExtensionToken = Bits & 0x01;
779 Bits >>= 1;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000780 bool hasSubmoduleMacros = Bits & 0x01;
781 Bits >>= 1;
Guy Benyei11169dd2012-12-18 14:30:41 +0000782 bool hadMacroDefinition = Bits & 0x01;
783 Bits >>= 1;
784
785 assert(Bits == 0 && "Extra bits in the identifier?");
786 DataLen -= 8;
787
788 // Build the IdentifierInfo itself and link the identifier ID with
789 // the new IdentifierInfo.
790 IdentifierInfo *II = KnownII;
791 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000792 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000793 KnownII = II;
794 }
795 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000796 if (!II->isFromAST()) {
797 bool WasInteresting = isInterestingIdentifier(*II);
798 II->setIsFromAST();
799 if (WasInteresting)
800 II->setChangedSinceDeserialization();
801 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000802
803 // Set or check the various bits in the IdentifierInfo structure.
804 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000805 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000806 II->RevertTokenIDToIdentifier();
807 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
808 assert(II->isExtensionToken() == ExtensionToken &&
809 "Incorrect extension token flag");
810 (void)ExtensionToken;
811 if (Poisoned)
812 II->setIsPoisoned(true);
813 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
814 "Incorrect C++ operator keyword flag");
815 (void)CPlusPlusOperatorKeyword;
816
817 // If this identifier is a macro, deserialize the macro
818 // definition.
819 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000820 uint32_t MacroDirectivesOffset =
821 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000822 DataLen -= 4;
823 SmallVector<uint32_t, 8> LocalMacroIDs;
824 if (hasSubmoduleMacros) {
Richard Smithdaa69e02014-07-25 04:40:03 +0000825 while (true) {
826 uint32_t LocalMacroID =
827 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000828 DataLen -= 4;
Richard Smithdf8a8312015-03-13 04:05:01 +0000829 if (LocalMacroID == (uint32_t)-1) break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000830 LocalMacroIDs.push_back(LocalMacroID);
831 }
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +0000832 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000833
Richard Smithe842a472014-10-22 02:05:46 +0000834 if (F.Kind == MK_ImplicitModule || F.Kind == MK_ExplicitModule) {
Richard Smith49f906a2014-03-01 00:08:04 +0000835 // Macro definitions are stored from newest to oldest, so reverse them
836 // before registering them.
837 llvm::SmallVector<unsigned, 8> MacroSizes;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000838 for (SmallVectorImpl<uint32_t>::iterator
Richard Smith49f906a2014-03-01 00:08:04 +0000839 I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
840 unsigned Size = 1;
841
842 static const uint32_t HasOverridesFlag = 0x80000000U;
843 if (I + 1 != E && (I[1] & HasOverridesFlag))
844 Size += 1 + (I[1] & ~HasOverridesFlag);
845
846 MacroSizes.push_back(Size);
847 I += Size;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000848 }
Richard Smith49f906a2014-03-01 00:08:04 +0000849
850 SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
851 for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
852 SE = MacroSizes.rend();
853 SI != SE; ++SI) {
854 I -= *SI;
855
856 uint32_t LocalMacroID = *I;
Craig Topper00bbdcf2014-06-28 23:22:23 +0000857 ArrayRef<uint32_t> Overrides;
Richard Smith49f906a2014-03-01 00:08:04 +0000858 if (*SI != 1)
859 Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
860 Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
861 }
862 assert(I == LocalMacroIDs.begin());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000863 } else {
864 Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
865 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000866 }
867
868 Reader.SetIdentifierInfo(ID, II);
869
870 // Read all of the declarations visible at global scope with this
871 // name.
872 if (DataLen > 0) {
873 SmallVector<uint32_t, 4> DeclIDs;
874 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000875 DeclIDs.push_back(Reader.getGlobalDeclID(
876 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000877 Reader.SetGloballyVisibleDecls(II, DeclIDs);
878 }
879
880 return II;
881}
882
883unsigned
884ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
885 llvm::FoldingSetNodeID ID;
886 ID.AddInteger(Key.Kind);
887
888 switch (Key.Kind) {
889 case DeclarationName::Identifier:
890 case DeclarationName::CXXLiteralOperatorName:
891 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
892 break;
893 case DeclarationName::ObjCZeroArgSelector:
894 case DeclarationName::ObjCOneArgSelector:
895 case DeclarationName::ObjCMultiArgSelector:
896 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
897 break;
898 case DeclarationName::CXXOperatorName:
899 ID.AddInteger((OverloadedOperatorKind)Key.Data);
900 break;
901 case DeclarationName::CXXConstructorName:
902 case DeclarationName::CXXDestructorName:
903 case DeclarationName::CXXConversionFunctionName:
904 case DeclarationName::CXXUsingDirective:
905 break;
906 }
907
908 return ID.ComputeHash();
909}
910
911ASTDeclContextNameLookupTrait::internal_key_type
912ASTDeclContextNameLookupTrait::GetInternalKey(
913 const external_key_type& Name) const {
914 DeclNameKey Key;
915 Key.Kind = Name.getNameKind();
916 switch (Name.getNameKind()) {
917 case DeclarationName::Identifier:
918 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
919 break;
920 case DeclarationName::ObjCZeroArgSelector:
921 case DeclarationName::ObjCOneArgSelector:
922 case DeclarationName::ObjCMultiArgSelector:
923 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
924 break;
925 case DeclarationName::CXXOperatorName:
926 Key.Data = Name.getCXXOverloadedOperator();
927 break;
928 case DeclarationName::CXXLiteralOperatorName:
929 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
930 break;
931 case DeclarationName::CXXConstructorName:
932 case DeclarationName::CXXDestructorName:
933 case DeclarationName::CXXConversionFunctionName:
934 case DeclarationName::CXXUsingDirective:
935 Key.Data = 0;
936 break;
937 }
938
939 return Key;
940}
941
942std::pair<unsigned, unsigned>
943ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000944 using namespace llvm::support;
945 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
946 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000947 return std::make_pair(KeyLen, DataLen);
948}
949
950ASTDeclContextNameLookupTrait::internal_key_type
951ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000952 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000953
954 DeclNameKey Key;
955 Key.Kind = (DeclarationName::NameKind)*d++;
956 switch (Key.Kind) {
957 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000958 Key.Data = (uint64_t)Reader.getLocalIdentifier(
959 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000960 break;
961 case DeclarationName::ObjCZeroArgSelector:
962 case DeclarationName::ObjCOneArgSelector:
963 case DeclarationName::ObjCMultiArgSelector:
964 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000965 (uint64_t)Reader.getLocalSelector(
966 F, endian::readNext<uint32_t, little, unaligned>(
967 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000968 break;
969 case DeclarationName::CXXOperatorName:
970 Key.Data = *d++; // OverloadedOperatorKind
971 break;
972 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000973 Key.Data = (uint64_t)Reader.getLocalIdentifier(
974 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000975 break;
976 case DeclarationName::CXXConstructorName:
977 case DeclarationName::CXXDestructorName:
978 case DeclarationName::CXXConversionFunctionName:
979 case DeclarationName::CXXUsingDirective:
980 Key.Data = 0;
981 break;
982 }
983
984 return Key;
985}
986
987ASTDeclContextNameLookupTrait::data_type
988ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
989 const unsigned char* d,
990 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000991 using namespace llvm::support;
992 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000993 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
994 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000995 return std::make_pair(Start, Start + NumDecls);
996}
997
998bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000999 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00001000 const std::pair<uint64_t, uint64_t> &Offsets,
1001 DeclContextInfo &Info) {
1002 SavedStreamPosition SavedPosition(Cursor);
1003 // First the lexical decls.
1004 if (Offsets.first != 0) {
1005 Cursor.JumpToBit(Offsets.first);
1006
1007 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001008 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00001009 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001010 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001011 if (RecCode != DECL_CONTEXT_LEXICAL) {
1012 Error("Expected lexical block");
1013 return true;
1014 }
1015
Chris Lattner0e6c9402013-01-20 02:38:54 +00001016 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
1017 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +00001018 }
1019
1020 // Now the lookup table.
1021 if (Offsets.second != 0) {
1022 Cursor.JumpToBit(Offsets.second);
1023
1024 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001025 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00001026 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001027 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001028 if (RecCode != DECL_CONTEXT_VISIBLE) {
1029 Error("Expected visible lookup table block");
1030 return true;
1031 }
Justin Bognerda4e6502014-04-14 16:34:29 +00001032 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
1033 (const unsigned char *)Blob.data() + Record[0],
1034 (const unsigned char *)Blob.data() + sizeof(uint32_t),
1035 (const unsigned char *)Blob.data(),
1036 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +00001037 }
1038
1039 return false;
1040}
1041
1042void ASTReader::Error(StringRef Msg) {
1043 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +00001044 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
1045 Diag(diag::note_module_cache_path)
1046 << PP.getHeaderSearchInfo().getModuleCachePath();
1047 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001048}
1049
1050void ASTReader::Error(unsigned DiagID,
1051 StringRef Arg1, StringRef Arg2) {
1052 if (Diags.isDiagnosticInFlight())
1053 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1054 else
1055 Diag(DiagID) << Arg1 << Arg2;
1056}
1057
1058//===----------------------------------------------------------------------===//
1059// Source Manager Deserialization
1060//===----------------------------------------------------------------------===//
1061
1062/// \brief Read the line table in the source manager block.
1063/// \returns true if there was an error.
1064bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001065 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001066 unsigned Idx = 0;
1067 LineTableInfo &LineTable = SourceMgr.getLineTable();
1068
1069 // Parse the file names
1070 std::map<int, int> FileIDs;
1071 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1072 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001073 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001074 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1075 }
1076
1077 // Parse the line entries
1078 std::vector<LineEntry> Entries;
1079 while (Idx < Record.size()) {
1080 int FID = Record[Idx++];
1081 assert(FID >= 0 && "Serialized line entries for non-local file.");
1082 // Remap FileID from 1-based old view.
1083 FID += F.SLocEntryBaseID - 1;
1084
1085 // Extract the line entries
1086 unsigned NumEntries = Record[Idx++];
1087 assert(NumEntries && "Numentries is 00000");
1088 Entries.clear();
1089 Entries.reserve(NumEntries);
1090 for (unsigned I = 0; I != NumEntries; ++I) {
1091 unsigned FileOffset = Record[Idx++];
1092 unsigned LineNo = Record[Idx++];
1093 int FilenameID = FileIDs[Record[Idx++]];
1094 SrcMgr::CharacteristicKind FileKind
1095 = (SrcMgr::CharacteristicKind)Record[Idx++];
1096 unsigned IncludeOffset = Record[Idx++];
1097 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1098 FileKind, IncludeOffset));
1099 }
1100 LineTable.AddEntry(FileID::get(FID), Entries);
1101 }
1102
1103 return false;
1104}
1105
1106/// \brief Read a source manager block
1107bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1108 using namespace SrcMgr;
1109
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001110 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001111
1112 // Set the source-location entry cursor to the current position in
1113 // the stream. This cursor will be used to read the contents of the
1114 // source manager block initially, and then lazily read
1115 // source-location entries as needed.
1116 SLocEntryCursor = F.Stream;
1117
1118 // The stream itself is going to skip over the source manager block.
1119 if (F.Stream.SkipBlock()) {
1120 Error("malformed block record in AST file");
1121 return true;
1122 }
1123
1124 // Enter the source manager block.
1125 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1126 Error("malformed source manager block record in AST file");
1127 return true;
1128 }
1129
1130 RecordData Record;
1131 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001132 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1133
1134 switch (E.Kind) {
1135 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1136 case llvm::BitstreamEntry::Error:
1137 Error("malformed block record in AST file");
1138 return true;
1139 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001140 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001141 case llvm::BitstreamEntry::Record:
1142 // The interesting case.
1143 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001144 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001145
Guy Benyei11169dd2012-12-18 14:30:41 +00001146 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001147 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001148 StringRef Blob;
1149 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001150 default: // Default behavior: ignore.
1151 break;
1152
1153 case SM_SLOC_FILE_ENTRY:
1154 case SM_SLOC_BUFFER_ENTRY:
1155 case SM_SLOC_EXPANSION_ENTRY:
1156 // Once we hit one of the source location entries, we're done.
1157 return false;
1158 }
1159 }
1160}
1161
1162/// \brief If a header file is not found at the path that we expect it to be
1163/// and the PCH file was moved from its original location, try to resolve the
1164/// file by assuming that header+PCH were moved together and the header is in
1165/// the same place relative to the PCH.
1166static std::string
1167resolveFileRelativeToOriginalDir(const std::string &Filename,
1168 const std::string &OriginalDir,
1169 const std::string &CurrDir) {
1170 assert(OriginalDir != CurrDir &&
1171 "No point trying to resolve the file if the PCH dir didn't change");
1172 using namespace llvm::sys;
1173 SmallString<128> filePath(Filename);
1174 fs::make_absolute(filePath);
1175 assert(path::is_absolute(OriginalDir));
1176 SmallString<128> currPCHPath(CurrDir);
1177
1178 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1179 fileDirE = path::end(path::parent_path(filePath));
1180 path::const_iterator origDirI = path::begin(OriginalDir),
1181 origDirE = path::end(OriginalDir);
1182 // Skip the common path components from filePath and OriginalDir.
1183 while (fileDirI != fileDirE && origDirI != origDirE &&
1184 *fileDirI == *origDirI) {
1185 ++fileDirI;
1186 ++origDirI;
1187 }
1188 for (; origDirI != origDirE; ++origDirI)
1189 path::append(currPCHPath, "..");
1190 path::append(currPCHPath, fileDirI, fileDirE);
1191 path::append(currPCHPath, path::filename(Filename));
1192 return currPCHPath.str();
1193}
1194
1195bool ASTReader::ReadSLocEntry(int ID) {
1196 if (ID == 0)
1197 return false;
1198
1199 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1200 Error("source location entry ID out-of-range for AST file");
1201 return true;
1202 }
1203
1204 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1205 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001206 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001207 unsigned BaseOffset = F->SLocEntryBaseOffset;
1208
1209 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001210 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1211 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001212 Error("incorrectly-formatted source location entry in AST file");
1213 return true;
1214 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001215
Guy Benyei11169dd2012-12-18 14:30:41 +00001216 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001217 StringRef Blob;
1218 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001219 default:
1220 Error("incorrectly-formatted source location entry in AST file");
1221 return true;
1222
1223 case SM_SLOC_FILE_ENTRY: {
1224 // We will detect whether a file changed and return 'Failure' for it, but
1225 // we will also try to fail gracefully by setting up the SLocEntry.
1226 unsigned InputID = Record[4];
1227 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001228 const FileEntry *File = IF.getFile();
1229 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001230
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001231 // Note that we only check if a File was returned. If it was out-of-date
1232 // we have complained but we will continue creating a FileID to recover
1233 // gracefully.
1234 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001235 return true;
1236
1237 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1238 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1239 // This is the module's main file.
1240 IncludeLoc = getImportLocation(F);
1241 }
1242 SrcMgr::CharacteristicKind
1243 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1244 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1245 ID, BaseOffset + Record[0]);
1246 SrcMgr::FileInfo &FileInfo =
1247 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1248 FileInfo.NumCreatedFIDs = Record[5];
1249 if (Record[3])
1250 FileInfo.setHasLineDirectives();
1251
1252 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1253 unsigned NumFileDecls = Record[7];
1254 if (NumFileDecls) {
1255 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1256 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1257 NumFileDecls));
1258 }
1259
1260 const SrcMgr::ContentCache *ContentCache
1261 = SourceMgr.getOrCreateContentCache(File,
1262 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1263 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1264 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1265 unsigned Code = SLocEntryCursor.ReadCode();
1266 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001267 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001268
1269 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1270 Error("AST record has invalid code");
1271 return true;
1272 }
1273
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001274 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001275 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001276 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001277 }
1278
1279 break;
1280 }
1281
1282 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001283 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001284 unsigned Offset = Record[0];
1285 SrcMgr::CharacteristicKind
1286 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1287 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001288 if (IncludeLoc.isInvalid() &&
1289 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001290 IncludeLoc = getImportLocation(F);
1291 }
1292 unsigned Code = SLocEntryCursor.ReadCode();
1293 Record.clear();
1294 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001295 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001296
1297 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1298 Error("AST record has invalid code");
1299 return true;
1300 }
1301
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001302 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1303 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001304 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001305 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001306 break;
1307 }
1308
1309 case SM_SLOC_EXPANSION_ENTRY: {
1310 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1311 SourceMgr.createExpansionLoc(SpellingLoc,
1312 ReadSourceLocation(*F, Record[2]),
1313 ReadSourceLocation(*F, Record[3]),
1314 Record[4],
1315 ID,
1316 BaseOffset + Record[0]);
1317 break;
1318 }
1319 }
1320
1321 return false;
1322}
1323
1324std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1325 if (ID == 0)
1326 return std::make_pair(SourceLocation(), "");
1327
1328 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1329 Error("source location entry ID out-of-range for AST file");
1330 return std::make_pair(SourceLocation(), "");
1331 }
1332
1333 // Find which module file this entry lands in.
1334 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001335 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001336 return std::make_pair(SourceLocation(), "");
1337
1338 // FIXME: Can we map this down to a particular submodule? That would be
1339 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001340 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001341}
1342
1343/// \brief Find the location where the module F is imported.
1344SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1345 if (F->ImportLoc.isValid())
1346 return F->ImportLoc;
1347
1348 // Otherwise we have a PCH. It's considered to be "imported" at the first
1349 // location of its includer.
1350 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001351 // Main file is the importer.
1352 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1353 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001354 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001355 return F->ImportedBy[0]->FirstLoc;
1356}
1357
1358/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1359/// specified cursor. Read the abbreviations that are at the top of the block
1360/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001361bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001362 if (Cursor.EnterSubBlock(BlockID)) {
1363 Error("malformed block record in AST file");
1364 return Failure;
1365 }
1366
1367 while (true) {
1368 uint64_t Offset = Cursor.GetCurrentBitNo();
1369 unsigned Code = Cursor.ReadCode();
1370
1371 // We expect all abbrevs to be at the start of the block.
1372 if (Code != llvm::bitc::DEFINE_ABBREV) {
1373 Cursor.JumpToBit(Offset);
1374 return false;
1375 }
1376 Cursor.ReadAbbrevRecord();
1377 }
1378}
1379
Richard Smithe40f2ba2013-08-07 21:41:30 +00001380Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001381 unsigned &Idx) {
1382 Token Tok;
1383 Tok.startToken();
1384 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1385 Tok.setLength(Record[Idx++]);
1386 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1387 Tok.setIdentifierInfo(II);
1388 Tok.setKind((tok::TokenKind)Record[Idx++]);
1389 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1390 return Tok;
1391}
1392
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001393MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001394 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001395
1396 // Keep track of where we are in the stream, then jump back there
1397 // after reading this macro.
1398 SavedStreamPosition SavedPosition(Stream);
1399
1400 Stream.JumpToBit(Offset);
1401 RecordData Record;
1402 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001403 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001404
Guy Benyei11169dd2012-12-18 14:30:41 +00001405 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001406 // Advance to the next record, but if we get to the end of the block, don't
1407 // pop it (removing all the abbreviations from the cursor) since we want to
1408 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001409 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001410 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1411
1412 switch (Entry.Kind) {
1413 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1414 case llvm::BitstreamEntry::Error:
1415 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001416 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001417 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001418 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001419 case llvm::BitstreamEntry::Record:
1420 // The interesting case.
1421 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001422 }
1423
1424 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001425 Record.clear();
1426 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001427 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001428 switch (RecType) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001429 case PP_MACRO_DIRECTIVE_HISTORY:
1430 return Macro;
1431
Guy Benyei11169dd2012-12-18 14:30:41 +00001432 case PP_MACRO_OBJECT_LIKE:
1433 case PP_MACRO_FUNCTION_LIKE: {
1434 // If we already have a macro, that means that we've hit the end
1435 // of the definition of the macro we were looking for. We're
1436 // done.
1437 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001438 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001439
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001440 unsigned NextIndex = 1; // Skip identifier ID.
1441 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001442 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001443 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001444 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001445 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001446 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001447
Guy Benyei11169dd2012-12-18 14:30:41 +00001448 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1449 // Decode function-like macro info.
1450 bool isC99VarArgs = Record[NextIndex++];
1451 bool isGNUVarArgs = Record[NextIndex++];
1452 bool hasCommaPasting = Record[NextIndex++];
1453 MacroArgs.clear();
1454 unsigned NumArgs = Record[NextIndex++];
1455 for (unsigned i = 0; i != NumArgs; ++i)
1456 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1457
1458 // Install function-like macro info.
1459 MI->setIsFunctionLike();
1460 if (isC99VarArgs) MI->setIsC99Varargs();
1461 if (isGNUVarArgs) MI->setIsGNUVarargs();
1462 if (hasCommaPasting) MI->setHasCommaPasting();
1463 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1464 PP.getPreprocessorAllocator());
1465 }
1466
Guy Benyei11169dd2012-12-18 14:30:41 +00001467 // Remember that we saw this macro last so that we add the tokens that
1468 // form its body to it.
1469 Macro = MI;
1470
1471 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1472 Record[NextIndex]) {
1473 // We have a macro definition. Register the association
1474 PreprocessedEntityID
1475 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1476 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001477 PreprocessingRecord::PPEntityID
1478 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1479 MacroDefinition *PPDef =
1480 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1481 if (PPDef)
1482 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001483 }
1484
1485 ++NumMacrosRead;
1486 break;
1487 }
1488
1489 case PP_TOKEN: {
1490 // If we see a TOKEN before a PP_MACRO_*, then the file is
1491 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001492 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001493
John McCallf413f5e2013-05-03 00:10:13 +00001494 unsigned Idx = 0;
1495 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001496 Macro->AddTokenToBody(Tok);
1497 break;
1498 }
1499 }
1500 }
1501}
1502
1503PreprocessedEntityID
1504ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1505 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1506 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1507 assert(I != M.PreprocessedEntityRemap.end()
1508 && "Invalid index into preprocessed entity index remap");
1509
1510 return LocalID + I->second;
1511}
1512
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001513unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1514 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001515}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001516
Guy Benyei11169dd2012-12-18 14:30:41 +00001517HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001518HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1519 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
Richard Smith7ed1bc92014-12-05 22:42:13 +00001520 FE->getName(), /*Imported*/false };
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001521 return ikey;
1522}
Guy Benyei11169dd2012-12-18 14:30:41 +00001523
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001524bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1525 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001526 return false;
1527
Richard Smith7ed1bc92014-12-05 22:42:13 +00001528 if (llvm::sys::path::is_absolute(a.Filename) &&
1529 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001530 return true;
1531
Guy Benyei11169dd2012-12-18 14:30:41 +00001532 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001533 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001534 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1535 if (!Key.Imported)
1536 return FileMgr.getFile(Key.Filename);
1537
1538 std::string Resolved = Key.Filename;
1539 Reader.ResolveImportedPath(M, Resolved);
1540 return FileMgr.getFile(Resolved);
1541 };
1542
1543 const FileEntry *FEA = GetFile(a);
1544 const FileEntry *FEB = GetFile(b);
1545 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001546}
1547
1548std::pair<unsigned, unsigned>
1549HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001550 using namespace llvm::support;
1551 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001552 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001553 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001554}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001555
1556HeaderFileInfoTrait::internal_key_type
1557HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001558 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001559 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001560 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1561 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001562 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001563 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001564 return ikey;
1565}
1566
Guy Benyei11169dd2012-12-18 14:30:41 +00001567HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001568HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001569 unsigned DataLen) {
1570 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001571 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001572 HeaderFileInfo HFI;
1573 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001574 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1575 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001576 HFI.isImport = (Flags >> 5) & 0x01;
1577 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1578 HFI.DirInfo = (Flags >> 2) & 0x03;
1579 HFI.Resolved = (Flags >> 1) & 0x01;
1580 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001581 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1582 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1583 M, endian::readNext<uint32_t, little, unaligned>(d));
1584 if (unsigned FrameworkOffset =
1585 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001586 // The framework offset is 1 greater than the actual offset,
1587 // since 0 is used as an indicator for "no framework name".
1588 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1589 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1590 }
1591
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001592 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001593 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001594 if (LocalSMID) {
1595 // This header is part of a module. Associate it with the module to enable
1596 // implicit module import.
1597 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1598 Module *Mod = Reader.getSubmodule(GlobalSMID);
1599 HFI.isModuleHeader = true;
1600 FileManager &FileMgr = Reader.getFileManager();
1601 ModuleMap &ModMap =
1602 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001603 // FIXME: This information should be propagated through the
1604 // SUBMODULE_HEADER etc records rather than from here.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001605 // FIXME: We don't ever mark excluded headers.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001606 std::string Filename = key.Filename;
1607 if (key.Imported)
1608 Reader.ResolveImportedPath(M, Filename);
1609 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Hans Wennborg0101b542014-12-02 02:13:09 +00001610 ModMap.addHeader(Mod, H, HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001611 }
1612 }
1613
Guy Benyei11169dd2012-12-18 14:30:41 +00001614 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1615 (void)End;
1616
1617 // This HeaderFileInfo was externally loaded.
1618 HFI.External = true;
1619 return HFI;
1620}
1621
Richard Smith49f906a2014-03-01 00:08:04 +00001622void
1623ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1624 GlobalMacroID GMacID,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001625 ArrayRef<SubmoduleID> Overrides) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001626 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
Craig Toppera13603a2014-05-22 05:54:18 +00001627 SubmoduleID *OverrideData = nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001628 if (!Overrides.empty()) {
1629 OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1630 OverrideData[0] = Overrides.size();
1631 for (unsigned I = 0; I != Overrides.size(); ++I)
1632 OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1633 }
1634 PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001635}
1636
1637void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1638 ModuleFile *M,
1639 uint64_t MacroDirectivesOffset) {
1640 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1641 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001642}
1643
1644void ASTReader::ReadDefinedMacros() {
1645 // Note that we are loading defined macros.
1646 Deserializing Macros(this);
1647
1648 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1649 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001650 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001651
1652 // If there was no preprocessor block, skip this file.
1653 if (!MacroCursor.getBitStreamReader())
1654 continue;
1655
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001656 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001657 Cursor.JumpToBit((*I)->MacroStartOffset);
1658
1659 RecordData Record;
1660 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001661 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1662
1663 switch (E.Kind) {
1664 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1665 case llvm::BitstreamEntry::Error:
1666 Error("malformed block record in AST file");
1667 return;
1668 case llvm::BitstreamEntry::EndBlock:
1669 goto NextCursor;
1670
1671 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001672 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001673 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001674 default: // Default behavior: ignore.
1675 break;
1676
1677 case PP_MACRO_OBJECT_LIKE:
1678 case PP_MACRO_FUNCTION_LIKE:
1679 getLocalIdentifier(**I, Record[0]);
1680 break;
1681
1682 case PP_TOKEN:
1683 // Ignore tokens.
1684 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001685 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001686 break;
1687 }
1688 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001689 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001690 }
1691}
1692
1693namespace {
1694 /// \brief Visitor class used to look up identifirs in an AST file.
1695 class IdentifierLookupVisitor {
1696 StringRef Name;
1697 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001698 unsigned &NumIdentifierLookups;
1699 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001700 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001701
Guy Benyei11169dd2012-12-18 14:30:41 +00001702 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001703 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1704 unsigned &NumIdentifierLookups,
1705 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001706 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001707 NumIdentifierLookups(NumIdentifierLookups),
1708 NumIdentifierLookupHits(NumIdentifierLookupHits),
1709 Found()
1710 {
1711 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001712
1713 static bool visit(ModuleFile &M, void *UserData) {
1714 IdentifierLookupVisitor *This
1715 = static_cast<IdentifierLookupVisitor *>(UserData);
1716
1717 // If we've already searched this module file, skip it now.
1718 if (M.Generation <= This->PriorGeneration)
1719 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001720
Guy Benyei11169dd2012-12-18 14:30:41 +00001721 ASTIdentifierLookupTable *IdTable
1722 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1723 if (!IdTable)
1724 return false;
1725
1726 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1727 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001728 ++This->NumIdentifierLookups;
1729 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001730 if (Pos == IdTable->end())
1731 return false;
1732
1733 // Dereferencing the iterator has the effect of building the
1734 // IdentifierInfo node and populating it with the various
1735 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001736 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001737 This->Found = *Pos;
1738 return true;
1739 }
1740
1741 // \brief Retrieve the identifier info found within the module
1742 // files.
1743 IdentifierInfo *getIdentifierInfo() const { return Found; }
1744 };
1745}
1746
1747void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1748 // Note that we are loading an identifier.
1749 Deserializing AnIdentifier(this);
1750
1751 unsigned PriorGeneration = 0;
1752 if (getContext().getLangOpts().Modules)
1753 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001754
1755 // If there is a global index, look there first to determine which modules
1756 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001757 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001758 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001759 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001760 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1761 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001762 }
1763 }
1764
Douglas Gregor7211ac12013-01-25 23:32:03 +00001765 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001766 NumIdentifierLookups,
1767 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001768 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001769 markIdentifierUpToDate(&II);
1770}
1771
1772void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1773 if (!II)
1774 return;
1775
1776 II->setOutOfDate(false);
1777
1778 // Update the generation for this identifier.
1779 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001780 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001781}
1782
Richard Smith49f906a2014-03-01 00:08:04 +00001783struct ASTReader::ModuleMacroInfo {
1784 SubmoduleID SubModID;
1785 MacroInfo *MI;
1786 SubmoduleID *Overrides;
1787 // FIXME: Remove this.
1788 ModuleFile *F;
1789
1790 bool isDefine() const { return MI; }
1791
1792 SubmoduleID getSubmoduleID() const { return SubModID; }
1793
Craig Topper00bbdcf2014-06-28 23:22:23 +00001794 ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
Richard Smith49f906a2014-03-01 00:08:04 +00001795 if (!Overrides)
Craig Topper00bbdcf2014-06-28 23:22:23 +00001796 return None;
Richard Smith49f906a2014-03-01 00:08:04 +00001797 return llvm::makeArrayRef(Overrides + 1, *Overrides);
1798 }
1799
Richard Smithdaa69e02014-07-25 04:40:03 +00001800 MacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
Richard Smith49f906a2014-03-01 00:08:04 +00001801 if (!MI)
Richard Smithdaa69e02014-07-25 04:40:03 +00001802 return PP.AllocateUndefMacroDirective(ImportLoc, SubModID,
1803 getOverriddenSubmodules());
1804 return PP.AllocateDefMacroDirective(MI, ImportLoc, SubModID,
1805 getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00001806 }
1807};
1808
1809ASTReader::ModuleMacroInfo *
Richard Smithdf8a8312015-03-13 04:05:01 +00001810ASTReader::getModuleMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo) {
Richard Smith49f906a2014-03-01 00:08:04 +00001811 ModuleMacroInfo Info;
1812
1813 uint32_t ID = PMInfo.ModuleMacroData.MacID;
1814 if (ID & 1) {
1815 // Macro undefinition.
1816 Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
Craig Toppera13603a2014-05-22 05:54:18 +00001817 Info.MI = nullptr;
Richard Smithdf8a8312015-03-13 04:05:01 +00001818
1819 // If we've already loaded the #undef of this macro from this module,
1820 // don't do so again.
1821 if (!LoadedUndefs.insert(std::make_pair(II, Info.SubModID)).second)
1822 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001823 } else {
1824 // Macro definition.
1825 GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1826 assert(GMacID);
1827
1828 // If this macro has already been loaded, don't do so again.
1829 // FIXME: This is highly dubious. Multiple macro definitions can have the
1830 // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1831 if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
Craig Toppera13603a2014-05-22 05:54:18 +00001832 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001833
1834 Info.MI = getMacro(GMacID);
1835 Info.SubModID = Info.MI->getOwningModuleID();
1836 }
1837 Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1838 Info.F = PMInfo.M;
1839
1840 return new (Context) ModuleMacroInfo(Info);
1841}
1842
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001843void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1844 const PendingMacroInfo &PMInfo) {
1845 assert(II);
1846
Richard Smithe842a472014-10-22 02:05:46 +00001847 if (PMInfo.M->Kind != MK_ImplicitModule &&
1848 PMInfo.M->Kind != MK_ExplicitModule) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001849 installPCHMacroDirectives(II, *PMInfo.M,
1850 PMInfo.PCHMacroData.MacroDirectivesOffset);
1851 return;
1852 }
Richard Smith49f906a2014-03-01 00:08:04 +00001853
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001854 // Module Macro.
1855
Richard Smithdf8a8312015-03-13 04:05:01 +00001856 ModuleMacroInfo *MMI = getModuleMacro(II, PMInfo);
Richard Smith49f906a2014-03-01 00:08:04 +00001857 if (!MMI)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001858 return;
1859
Richard Smith49f906a2014-03-01 00:08:04 +00001860 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1861 if (Owner && Owner->NameVisibility == Module::Hidden) {
1862 // Macros in the owning module are hidden. Just remember this macro to
1863 // install if we make this module visible.
1864 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1865 } else {
Richard Smithdaa69e02014-07-25 04:40:03 +00001866 installImportedMacro(II, MMI, Owner);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001867 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001868}
1869
1870void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1871 ModuleFile &M, uint64_t Offset) {
Richard Smithe842a472014-10-22 02:05:46 +00001872 assert(M.Kind != MK_ImplicitModule && M.Kind != MK_ExplicitModule);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001873
1874 BitstreamCursor &Cursor = M.MacroCursor;
1875 SavedStreamPosition SavedPosition(Cursor);
1876 Cursor.JumpToBit(Offset);
1877
1878 llvm::BitstreamEntry Entry =
1879 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1880 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1881 Error("malformed block record in AST file");
1882 return;
1883 }
1884
1885 RecordData Record;
1886 PreprocessorRecordTypes RecType =
1887 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1888 if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1889 Error("malformed block record in AST file");
1890 return;
1891 }
1892
1893 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001894 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001895 unsigned Idx = 0, N = Record.size();
1896 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001897 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001898 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001899 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1900 switch (K) {
1901 case MacroDirective::MD_Define: {
1902 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1903 MacroInfo *MI = getMacro(GMacID);
Richard Smithdaa69e02014-07-25 04:40:03 +00001904 SubmoduleID ImportedFrom = Record[Idx++];
1905 bool IsAmbiguous = Record[Idx++];
1906 llvm::SmallVector<unsigned, 4> Overrides;
1907 if (ImportedFrom) {
1908 Overrides.insert(Overrides.end(),
1909 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1910 Idx += Overrides.size() + 1;
1911 }
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001912 DefMacroDirective *DefMD =
Richard Smithdaa69e02014-07-25 04:40:03 +00001913 PP.AllocateDefMacroDirective(MI, Loc, ImportedFrom, Overrides);
1914 DefMD->setAmbiguous(IsAmbiguous);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001915 MD = DefMD;
1916 break;
1917 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001918 case MacroDirective::MD_Undefine: {
1919 SubmoduleID ImportedFrom = Record[Idx++];
1920 llvm::SmallVector<unsigned, 4> Overrides;
1921 if (ImportedFrom) {
1922 Overrides.insert(Overrides.end(),
1923 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
1924 Idx += Overrides.size() + 1;
1925 }
1926 MD = PP.AllocateUndefMacroDirective(Loc, ImportedFrom, Overrides);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001927 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001928 }
1929 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001930 bool isPublic = Record[Idx++];
1931 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1932 break;
1933 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001934
1935 if (!Latest)
1936 Latest = MD;
1937 if (Earliest)
1938 Earliest->setPrevious(MD);
1939 Earliest = MD;
1940 }
1941
1942 PP.setLoadedMacroDirective(II, Latest);
1943}
1944
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001945/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001946/// modules.
1947static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001948 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001949 assert(PrevMI && NewMI);
Craig Toppera13603a2014-05-22 05:54:18 +00001950 Module *PrevOwner = nullptr;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001951 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1952 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001953 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001954 return false;
Chandler Carruthc2132d82015-03-13 08:29:54 +00001955 SourceManager &SrcMgr = Reader.getSourceManager();
1956 bool PrevInSystem = (PrevOwner && PrevOwner->IsSystem) ||
1957 SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1958 bool NewInSystem = (NewOwner && NewOwner->IsSystem) ||
1959 SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
Douglas Gregor5e461192013-06-07 22:56:11 +00001960 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001961}
1962
Richard Smith49f906a2014-03-01 00:08:04 +00001963void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001964 SourceLocation ImportLoc,
Richard Smith49f906a2014-03-01 00:08:04 +00001965 AmbiguousMacros &Ambig,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001966 ArrayRef<SubmoduleID> Overrides) {
Richard Smith49f906a2014-03-01 00:08:04 +00001967 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1968 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001969
Richard Smith49f906a2014-03-01 00:08:04 +00001970 // If this macro is not yet visible, remove it from the hidden names list.
Richard Smithbb853c72014-08-13 01:23:33 +00001971 // It won't be there if we're in the middle of making the owner visible.
Richard Smith49f906a2014-03-01 00:08:04 +00001972 Module *Owner = getSubmodule(OwnerID);
Richard Smithbb853c72014-08-13 01:23:33 +00001973 auto HiddenIt = HiddenNamesMap.find(Owner);
1974 if (HiddenIt != HiddenNamesMap.end()) {
1975 HiddenNames &Hidden = HiddenIt->second;
1976 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1977 if (HI != Hidden.HiddenMacros.end()) {
1978 // Register the macro now so we don't lose it when we re-export.
1979 PP.appendMacroDirective(II, HI->second->import(PP, ImportLoc));
Richard Smithdaa69e02014-07-25 04:40:03 +00001980
Richard Smithbb853c72014-08-13 01:23:33 +00001981 auto SubOverrides = HI->second->getOverriddenSubmodules();
1982 Hidden.HiddenMacros.erase(HI);
1983 removeOverriddenMacros(II, ImportLoc, Ambig, SubOverrides);
1984 }
Richard Smith49f906a2014-03-01 00:08:04 +00001985 }
1986
1987 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001988 Ambig.erase(
1989 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1990 return MD->getInfo()->getOwningModuleID() == OwnerID;
1991 }),
1992 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001993 }
1994}
1995
1996ASTReader::AmbiguousMacros *
1997ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001998 SourceLocation ImportLoc,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001999 ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002000 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00002001 if (!Prev && Overrides.empty())
Craig Toppera13603a2014-05-22 05:54:18 +00002002 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00002003
Craig Toppera13603a2014-05-22 05:54:18 +00002004 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective()
2005 : nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00002006 if (PrevDef && PrevDef->isAmbiguous()) {
2007 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
2008 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
2009 Ambig.push_back(PrevDef);
2010
Richard Smithdaa69e02014-07-25 04:40:03 +00002011 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00002012
2013 if (!Ambig.empty())
2014 return &Ambig;
2015
2016 AmbiguousMacroDefs.erase(II);
2017 } else {
2018 // There's no ambiguity yet. Maybe we're introducing one.
Benjamin Kramer834652a2014-05-03 18:44:26 +00002019 AmbiguousMacros Ambig;
Richard Smith49f906a2014-03-01 00:08:04 +00002020 if (PrevDef)
2021 Ambig.push_back(PrevDef);
2022
Richard Smithdaa69e02014-07-25 04:40:03 +00002023 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00002024
2025 if (!Ambig.empty()) {
2026 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
Benjamin Kramer834652a2014-05-03 18:44:26 +00002027 std::swap(Result, Ambig);
Richard Smith49f906a2014-03-01 00:08:04 +00002028 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002029 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002030 }
Richard Smith49f906a2014-03-01 00:08:04 +00002031
2032 // We ended up with no ambiguity.
Craig Toppera13603a2014-05-22 05:54:18 +00002033 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00002034}
2035
2036void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
Richard Smithdaa69e02014-07-25 04:40:03 +00002037 Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00002038 assert(II && Owner);
2039
2040 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
Richard Smithdaa69e02014-07-25 04:40:03 +00002041 if (ImportLoc.isInvalid()) {
Richard Smith49f906a2014-03-01 00:08:04 +00002042 // FIXME: If we made macros from this module visible but didn't provide a
2043 // source location for the import, we don't have a location for the macro.
2044 // Use the location at which the containing module file was first imported
2045 // for now.
2046 ImportLoc = MMI->F->DirectImportLoc;
Richard Smith56be7542014-03-21 00:33:59 +00002047 assert(ImportLoc.isValid() && "no import location for a visible macro?");
Richard Smith49f906a2014-03-01 00:08:04 +00002048 }
2049
Benjamin Kramer834652a2014-05-03 18:44:26 +00002050 AmbiguousMacros *Prev =
Richard Smithdaa69e02014-07-25 04:40:03 +00002051 removeOverriddenMacros(II, ImportLoc, MMI->getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00002052
Richard Smith49f906a2014-03-01 00:08:04 +00002053 // Create a synthetic macro definition corresponding to the import (or null
2054 // if this was an undefinition of the macro).
Richard Smithdaa69e02014-07-25 04:40:03 +00002055 MacroDirective *Imported = MMI->import(PP, ImportLoc);
2056 DefMacroDirective *MD = dyn_cast<DefMacroDirective>(Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002057
2058 // If there's no ambiguity, just install the macro.
2059 if (!Prev) {
Richard Smithdaa69e02014-07-25 04:40:03 +00002060 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002061 return;
2062 }
2063 assert(!Prev->empty());
2064
2065 if (!MD) {
2066 // We imported a #undef that didn't remove all prior definitions. The most
2067 // recent prior definition remains, and we install it in the place of the
Richard Smithdaa69e02014-07-25 04:40:03 +00002068 // imported directive, as if by a local #pragma pop_macro.
Richard Smith49f906a2014-03-01 00:08:04 +00002069 MacroInfo *NewMI = Prev->back()->getInfo();
2070 Prev->pop_back();
Richard Smithdaa69e02014-07-25 04:40:03 +00002071 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc);
2072
2073 // Install our #undef first so that we don't lose track of it. We'll replace
2074 // this with whichever macro definition ends up winning.
2075 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002076 }
2077
2078 // We're introducing a macro definition that creates or adds to an ambiguity.
2079 // We can resolve that ambiguity if this macro is token-for-token identical to
2080 // all of the existing definitions.
2081 MacroInfo *NewMI = MD->getInfo();
2082 assert(NewMI && "macro definition with no MacroInfo?");
2083 while (!Prev->empty()) {
2084 MacroInfo *PrevMI = Prev->back()->getInfo();
2085 assert(PrevMI && "macro definition with no MacroInfo?");
2086
2087 // Before marking the macros as ambiguous, check if this is a case where
2088 // both macros are in system headers. If so, we trust that the system
2089 // did not get it wrong. This also handles cases where Clang's own
2090 // headers have a different spelling of certain system macros:
2091 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
2092 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
2093 //
2094 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
2095 // overrides the system limits.h's macros, so there's no conflict here.
2096 if (NewMI != PrevMI &&
2097 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
2098 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
2099 break;
2100
2101 // The previous definition is the same as this one (or both are defined in
2102 // system modules so we can assume they're equivalent); we don't need to
2103 // track it any more.
2104 Prev->pop_back();
2105 }
2106
2107 if (!Prev->empty())
2108 MD->setAmbiguous(true);
2109
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002110 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002111}
2112
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002113ASTReader::InputFileInfo
2114ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002115 // Go find this input file.
2116 BitstreamCursor &Cursor = F.InputFilesCursor;
2117 SavedStreamPosition SavedPosition(Cursor);
2118 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2119
2120 unsigned Code = Cursor.ReadCode();
2121 RecordData Record;
2122 StringRef Blob;
2123
2124 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2125 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2126 "invalid record type for input file");
2127 (void)Result;
2128
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002129 std::string Filename;
2130 off_t StoredSize;
2131 time_t StoredTime;
2132 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002133
Ben Langmuir198c1682014-03-07 07:27:49 +00002134 assert(Record[0] == ID && "Bogus stored ID or offset");
2135 StoredSize = static_cast<off_t>(Record[1]);
2136 StoredTime = static_cast<time_t>(Record[2]);
2137 Overridden = static_cast<bool>(Record[3]);
2138 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002139 ResolveImportedPath(F, Filename);
2140
Hans Wennborg73945142014-03-14 17:45:06 +00002141 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
2142 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002143}
2144
2145std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002146 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00002147}
2148
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002149InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002150 // If this ID is bogus, just return an empty input file.
2151 if (ID == 0 || ID > F.InputFilesLoaded.size())
2152 return InputFile();
2153
2154 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002155 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002156 return F.InputFilesLoaded[ID-1];
2157
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002158 if (F.InputFilesLoaded[ID-1].isNotFound())
2159 return InputFile();
2160
Guy Benyei11169dd2012-12-18 14:30:41 +00002161 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002162 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002163 SavedStreamPosition SavedPosition(Cursor);
2164 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2165
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002166 InputFileInfo FI = readInputFileInfo(F, ID);
2167 off_t StoredSize = FI.StoredSize;
2168 time_t StoredTime = FI.StoredTime;
2169 bool Overridden = FI.Overridden;
2170 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002171
Ben Langmuir198c1682014-03-07 07:27:49 +00002172 const FileEntry *File
2173 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
2174 : FileMgr.getFile(Filename, /*OpenFile=*/false);
2175
2176 // If we didn't find the file, resolve it relative to the
2177 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002178 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002179 F.OriginalDir != CurrentDir) {
2180 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2181 F.OriginalDir,
2182 CurrentDir);
2183 if (!Resolved.empty())
2184 File = FileMgr.getFile(Resolved);
2185 }
2186
2187 // For an overridden file, create a virtual file with the stored
2188 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00002189 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002190 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2191 }
2192
Craig Toppera13603a2014-05-22 05:54:18 +00002193 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002194 if (Complain) {
2195 std::string ErrorStr = "could not find file '";
2196 ErrorStr += Filename;
2197 ErrorStr += "' referenced by AST file";
2198 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00002199 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002200 // Record that we didn't find the file.
2201 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2202 return InputFile();
2203 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002204
Ben Langmuir198c1682014-03-07 07:27:49 +00002205 // Check if there was a request to override the contents of the file
2206 // that was part of the precompiled header. Overridding such a file
2207 // can lead to problems when lexing using the source locations from the
2208 // PCH.
2209 SourceManager &SM = getSourceManager();
2210 if (!Overridden && SM.isFileOverridden(File)) {
2211 if (Complain)
2212 Error(diag::err_fe_pch_file_overridden, Filename);
2213 // After emitting the diagnostic, recover by disabling the override so
2214 // that the original file will be used.
2215 SM.disableFileContentsOverride(File);
2216 // The FileEntry is a virtual file entry with the size of the contents
2217 // that would override the original contents. Set it to the original's
2218 // size/time.
2219 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2220 StoredSize, StoredTime);
2221 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002222
Ben Langmuir198c1682014-03-07 07:27:49 +00002223 bool IsOutOfDate = false;
2224
2225 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002226 if (!Overridden && //
2227 (StoredSize != File->getSize() ||
2228#if defined(LLVM_ON_WIN32)
2229 false
2230#else
Ben Langmuir198c1682014-03-07 07:27:49 +00002231 // In our regression testing, the Windows file system seems to
2232 // have inconsistent modification times that sometimes
2233 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00002234 //
2235 // This also happens in networked file systems, so disable this
2236 // check if validation is disabled or if we have an explicitly
2237 // built PCM file.
2238 //
2239 // FIXME: Should we also do this for PCH files? They could also
2240 // reasonably get shared across a network during a distributed build.
2241 (StoredTime != File->getModificationTime() && !DisableValidation &&
2242 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00002243#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002244 )) {
2245 if (Complain) {
2246 // Build a list of the PCH imports that got us here (in reverse).
2247 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2248 while (ImportStack.back()->ImportedBy.size() > 0)
2249 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002250
Ben Langmuir198c1682014-03-07 07:27:49 +00002251 // The top-level PCH is stale.
2252 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2253 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002254
Ben Langmuir198c1682014-03-07 07:27:49 +00002255 // Print the import stack.
2256 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2257 Diag(diag::note_pch_required_by)
2258 << Filename << ImportStack[0]->FileName;
2259 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002260 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002261 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002262 }
2263
Ben Langmuir198c1682014-03-07 07:27:49 +00002264 if (!Diags.isDiagnosticInFlight())
2265 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002266 }
2267
Ben Langmuir198c1682014-03-07 07:27:49 +00002268 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002269 }
2270
Ben Langmuir198c1682014-03-07 07:27:49 +00002271 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2272
2273 // Note that we've loaded this input file.
2274 F.InputFilesLoaded[ID-1] = IF;
2275 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002276}
2277
Richard Smith7ed1bc92014-12-05 22:42:13 +00002278/// \brief If we are loading a relocatable PCH or module file, and the filename
2279/// is not an absolute path, add the system or module root to the beginning of
2280/// the file name.
2281void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2282 // Resolve relative to the base directory, if we have one.
2283 if (!M.BaseDirectory.empty())
2284 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002285}
2286
Richard Smith7ed1bc92014-12-05 22:42:13 +00002287void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002288 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2289 return;
2290
Richard Smith7ed1bc92014-12-05 22:42:13 +00002291 SmallString<128> Buffer;
2292 llvm::sys::path::append(Buffer, Prefix, Filename);
2293 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002294}
2295
2296ASTReader::ASTReadResult
2297ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002298 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002299 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002300 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002301 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002302
2303 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2304 Error("malformed block record in AST file");
2305 return Failure;
2306 }
2307
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002308 // Should we allow the configuration of the module file to differ from the
2309 // configuration of the current translation unit in a compatible way?
2310 //
2311 // FIXME: Allow this for files explicitly specified with -include-pch too.
2312 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2313
Guy Benyei11169dd2012-12-18 14:30:41 +00002314 // Read all of the records and blocks in the control block.
2315 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002316 unsigned NumInputs = 0;
2317 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002318 while (1) {
2319 llvm::BitstreamEntry Entry = Stream.advance();
2320
2321 switch (Entry.Kind) {
2322 case llvm::BitstreamEntry::Error:
2323 Error("malformed block record in AST file");
2324 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002325 case llvm::BitstreamEntry::EndBlock: {
2326 // Validate input files.
2327 const HeaderSearchOptions &HSOpts =
2328 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002329
Richard Smitha1825302014-10-23 22:18:29 +00002330 // All user input files reside at the index range [0, NumUserInputs), and
2331 // system input files reside at [NumUserInputs, NumInputs).
Ben Langmuiracb803e2014-11-10 22:13:10 +00002332 if (!DisableValidation) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002333 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002334
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002335 // If we are reading a module, we will create a verification timestamp,
2336 // so we verify all input files. Otherwise, verify only user input
2337 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002338
2339 unsigned N = NumUserInputs;
2340 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002341 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002342 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002343 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002344 N = NumInputs;
2345
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002346 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002347 InputFile IF = getInputFile(F, I+1, Complain);
2348 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002349 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002350 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002351 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002352
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002353 if (Listener)
2354 Listener->visitModuleFile(F.FileName);
2355
Ben Langmuircb69b572014-03-07 06:40:32 +00002356 if (Listener && Listener->needsInputFileVisitation()) {
2357 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2358 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002359 for (unsigned I = 0; I < N; ++I) {
2360 bool IsSystem = I >= NumUserInputs;
2361 InputFileInfo FI = readInputFileInfo(F, I+1);
2362 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2363 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002364 }
2365
Guy Benyei11169dd2012-12-18 14:30:41 +00002366 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002367 }
2368
Chris Lattnere7b154b2013-01-19 21:39:22 +00002369 case llvm::BitstreamEntry::SubBlock:
2370 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 case INPUT_FILES_BLOCK_ID:
2372 F.InputFilesCursor = Stream;
2373 if (Stream.SkipBlock() || // Skip with the main cursor
2374 // Read the abbreviations
2375 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2376 Error("malformed block record in AST file");
2377 return Failure;
2378 }
2379 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002380
Guy Benyei11169dd2012-12-18 14:30:41 +00002381 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002382 if (Stream.SkipBlock()) {
2383 Error("malformed block record in AST file");
2384 return Failure;
2385 }
2386 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002387 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002388
2389 case llvm::BitstreamEntry::Record:
2390 // The interesting case.
2391 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002392 }
2393
2394 // Read and process a record.
2395 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002396 StringRef Blob;
2397 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002398 case METADATA: {
2399 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2400 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002401 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2402 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002403 return VersionMismatch;
2404 }
2405
2406 bool hasErrors = Record[5];
2407 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2408 Diag(diag::err_pch_with_compiler_errors);
2409 return HadErrors;
2410 }
2411
2412 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002413 // Relative paths in a relocatable PCH are relative to our sysroot.
2414 if (F.RelocatablePCH)
2415 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002416
2417 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002418 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002419 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2420 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002421 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002422 return VersionMismatch;
2423 }
2424 break;
2425 }
2426
Ben Langmuir487ea142014-10-23 18:05:36 +00002427 case SIGNATURE:
2428 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2429 F.Signature = Record[0];
2430 break;
2431
Guy Benyei11169dd2012-12-18 14:30:41 +00002432 case IMPORTS: {
2433 // Load each of the imported PCH files.
2434 unsigned Idx = 0, N = Record.size();
2435 while (Idx < N) {
2436 // Read information about the AST file.
2437 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2438 // The import location will be the local one for now; we will adjust
2439 // all import locations of module imports after the global source
2440 // location info are setup.
2441 SourceLocation ImportLoc =
2442 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002443 off_t StoredSize = (off_t)Record[Idx++];
2444 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002445 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002446 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002447
2448 // Load the AST file.
2449 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00002450 StoredSize, StoredModTime, StoredSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00002451 ClientLoadCapabilities)) {
2452 case Failure: return Failure;
2453 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002454 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002455 case OutOfDate: return OutOfDate;
2456 case VersionMismatch: return VersionMismatch;
2457 case ConfigurationMismatch: return ConfigurationMismatch;
2458 case HadErrors: return HadErrors;
2459 case Success: break;
2460 }
2461 }
2462 break;
2463 }
2464
2465 case LANGUAGE_OPTIONS: {
2466 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002467 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002468 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002469 ParseLanguageOptions(Record, Complain, *Listener,
2470 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002471 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002472 return ConfigurationMismatch;
2473 break;
2474 }
2475
2476 case TARGET_OPTIONS: {
2477 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2478 if (Listener && &F == *ModuleMgr.begin() &&
Chandler Carruth0d745bc2015-03-14 04:47:43 +00002479 ParseTargetOptions(Record, Complain, *Listener,
2480 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002481 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002482 return ConfigurationMismatch;
2483 break;
2484 }
2485
2486 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002487 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002488 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002489 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002490 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002491 !DisableValidation)
2492 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002493 break;
2494 }
2495
2496 case FILE_SYSTEM_OPTIONS: {
2497 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2498 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002499 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002500 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002501 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002502 return ConfigurationMismatch;
2503 break;
2504 }
2505
2506 case HEADER_SEARCH_OPTIONS: {
2507 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2508 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002509 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002510 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002511 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002512 return ConfigurationMismatch;
2513 break;
2514 }
2515
2516 case PREPROCESSOR_OPTIONS: {
2517 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2518 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002519 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002520 ParsePreprocessorOptions(Record, Complain, *Listener,
2521 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002522 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002523 return ConfigurationMismatch;
2524 break;
2525 }
2526
2527 case ORIGINAL_FILE:
2528 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002529 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002530 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002531 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002532 break;
2533
2534 case ORIGINAL_FILE_ID:
2535 F.OriginalSourceFileID = FileID::get(Record[0]);
2536 break;
2537
2538 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002539 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002540 break;
2541
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002542 case MODULE_NAME:
2543 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002544 if (Listener)
2545 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002546 break;
2547
Richard Smith223d3f22014-12-06 03:21:08 +00002548 case MODULE_DIRECTORY: {
2549 assert(!F.ModuleName.empty() &&
2550 "MODULE_DIRECTORY found before MODULE_NAME");
2551 // If we've already loaded a module map file covering this module, we may
2552 // have a better path for it (relative to the current build).
2553 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2554 if (M && M->Directory) {
2555 // If we're implicitly loading a module, the base directory can't
2556 // change between the build and use.
2557 if (F.Kind != MK_ExplicitModule) {
2558 const DirectoryEntry *BuildDir =
2559 PP.getFileManager().getDirectory(Blob);
2560 if (!BuildDir || BuildDir != M->Directory) {
2561 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2562 Diag(diag::err_imported_module_relocated)
2563 << F.ModuleName << Blob << M->Directory->getName();
2564 return OutOfDate;
2565 }
2566 }
2567 F.BaseDirectory = M->Directory->getName();
2568 } else {
2569 F.BaseDirectory = Blob;
2570 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002571 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002572 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002573
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002574 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002575 if (ASTReadResult Result =
2576 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2577 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002578 break;
2579
Guy Benyei11169dd2012-12-18 14:30:41 +00002580 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002581 NumInputs = Record[0];
2582 NumUserInputs = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00002583 F.InputFileOffsets = (const uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002584 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002585 break;
2586 }
2587 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002588}
2589
Ben Langmuir2c9af442014-04-10 17:57:43 +00002590ASTReader::ASTReadResult
2591ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002592 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002593
2594 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2595 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002596 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002597 }
2598
2599 // Read all of the records and blocks for the AST file.
2600 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002601 while (1) {
2602 llvm::BitstreamEntry Entry = Stream.advance();
2603
2604 switch (Entry.Kind) {
2605 case llvm::BitstreamEntry::Error:
2606 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002607 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002608 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002609 // Outside of C++, we do not store a lookup map for the translation unit.
2610 // Instead, mark it as needing a lookup map to be built if this module
2611 // contains any declarations lexically within it (which it always does!).
2612 // This usually has no cost, since we very rarely need the lookup map for
2613 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002614 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002615 if (DC->hasExternalLexicalStorage() &&
2616 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002617 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002618
Ben Langmuir2c9af442014-04-10 17:57:43 +00002619 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002620 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002621 case llvm::BitstreamEntry::SubBlock:
2622 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002623 case DECLTYPES_BLOCK_ID:
2624 // We lazily load the decls block, but we want to set up the
2625 // DeclsCursor cursor to point into it. Clone our current bitcode
2626 // cursor to it, enter the block and read the abbrevs in that block.
2627 // With the main cursor, we just skip over it.
2628 F.DeclsCursor = Stream;
2629 if (Stream.SkipBlock() || // Skip with the main cursor.
2630 // Read the abbrevs.
2631 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2632 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002633 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002634 }
2635 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002636
Guy Benyei11169dd2012-12-18 14:30:41 +00002637 case PREPROCESSOR_BLOCK_ID:
2638 F.MacroCursor = Stream;
2639 if (!PP.getExternalSource())
2640 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002641
Guy Benyei11169dd2012-12-18 14:30:41 +00002642 if (Stream.SkipBlock() ||
2643 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2644 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002645 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002646 }
2647 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2648 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002649
Guy Benyei11169dd2012-12-18 14:30:41 +00002650 case PREPROCESSOR_DETAIL_BLOCK_ID:
2651 F.PreprocessorDetailCursor = Stream;
2652 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002653 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002654 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002655 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002656 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002657 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002658 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002659 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2660
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 if (!PP.getPreprocessingRecord())
2662 PP.createPreprocessingRecord();
2663 if (!PP.getPreprocessingRecord()->getExternalSource())
2664 PP.getPreprocessingRecord()->SetExternalSource(*this);
2665 break;
2666
2667 case SOURCE_MANAGER_BLOCK_ID:
2668 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002669 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002670 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002671
Guy Benyei11169dd2012-12-18 14:30:41 +00002672 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002673 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2674 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002675 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002676
Guy Benyei11169dd2012-12-18 14:30:41 +00002677 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002678 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002679 if (Stream.SkipBlock() ||
2680 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2681 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002682 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002683 }
2684 CommentsCursors.push_back(std::make_pair(C, &F));
2685 break;
2686 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002687
Guy Benyei11169dd2012-12-18 14:30:41 +00002688 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002689 if (Stream.SkipBlock()) {
2690 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002691 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002692 }
2693 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002694 }
2695 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002696
2697 case llvm::BitstreamEntry::Record:
2698 // The interesting case.
2699 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002700 }
2701
2702 // Read and process a record.
2703 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002704 StringRef Blob;
2705 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002706 default: // Default behavior: ignore.
2707 break;
2708
2709 case TYPE_OFFSET: {
2710 if (F.LocalNumTypes != 0) {
2711 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002712 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002713 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002714 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002715 F.LocalNumTypes = Record[0];
2716 unsigned LocalBaseTypeIndex = Record[1];
2717 F.BaseTypeIndex = getTotalNumTypes();
2718
2719 if (F.LocalNumTypes > 0) {
2720 // Introduce the global -> local mapping for types within this module.
2721 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2722
2723 // Introduce the local -> global mapping for types within this module.
2724 F.TypeRemap.insertOrReplace(
2725 std::make_pair(LocalBaseTypeIndex,
2726 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002727
2728 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002729 }
2730 break;
2731 }
2732
2733 case DECL_OFFSET: {
2734 if (F.LocalNumDecls != 0) {
2735 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002736 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002737 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002738 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002739 F.LocalNumDecls = Record[0];
2740 unsigned LocalBaseDeclID = Record[1];
2741 F.BaseDeclID = getTotalNumDecls();
2742
2743 if (F.LocalNumDecls > 0) {
2744 // Introduce the global -> local mapping for declarations within this
2745 // module.
2746 GlobalDeclMap.insert(
2747 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2748
2749 // Introduce the local -> global mapping for declarations within this
2750 // module.
2751 F.DeclRemap.insertOrReplace(
2752 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2753
2754 // Introduce the global -> local mapping for declarations within this
2755 // module.
2756 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002757
Ben Langmuir52ca6782014-10-20 16:27:32 +00002758 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2759 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002760 break;
2761 }
2762
2763 case TU_UPDATE_LEXICAL: {
2764 DeclContext *TU = Context.getTranslationUnitDecl();
2765 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002766 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002767 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002768 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002769 TU->setHasExternalLexicalStorage(true);
2770 break;
2771 }
2772
2773 case UPDATE_VISIBLE: {
2774 unsigned Idx = 0;
2775 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2776 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002777 ASTDeclContextNameLookupTable::Create(
2778 (const unsigned char *)Blob.data() + Record[Idx++],
2779 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2780 (const unsigned char *)Blob.data(),
2781 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002782 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002783 auto *DC = cast<DeclContext>(D);
2784 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002785 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2786 delete LookupTable;
2787 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002788 } else
2789 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2790 break;
2791 }
2792
2793 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002794 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002795 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002796 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2797 (const unsigned char *)F.IdentifierTableData + Record[0],
2798 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2799 (const unsigned char *)F.IdentifierTableData,
2800 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002801
2802 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2803 }
2804 break;
2805
2806 case IDENTIFIER_OFFSET: {
2807 if (F.LocalNumIdentifiers != 0) {
2808 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002809 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002810 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002811 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002812 F.LocalNumIdentifiers = Record[0];
2813 unsigned LocalBaseIdentifierID = Record[1];
2814 F.BaseIdentifierID = getTotalNumIdentifiers();
2815
2816 if (F.LocalNumIdentifiers > 0) {
2817 // Introduce the global -> local mapping for identifiers within this
2818 // module.
2819 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2820 &F));
2821
2822 // Introduce the local -> global mapping for identifiers within this
2823 // module.
2824 F.IdentifierRemap.insertOrReplace(
2825 std::make_pair(LocalBaseIdentifierID,
2826 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002827
Ben Langmuir52ca6782014-10-20 16:27:32 +00002828 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2829 + F.LocalNumIdentifiers);
2830 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002831 break;
2832 }
2833
Ben Langmuir332aafe2014-01-31 01:06:56 +00002834 case EAGERLY_DESERIALIZED_DECLS:
Guy Benyei11169dd2012-12-18 14:30:41 +00002835 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002836 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002837 break;
2838
2839 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002840 if (SpecialTypes.empty()) {
2841 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2842 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2843 break;
2844 }
2845
2846 if (SpecialTypes.size() != Record.size()) {
2847 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002848 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002849 }
2850
2851 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2852 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2853 if (!SpecialTypes[I])
2854 SpecialTypes[I] = ID;
2855 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2856 // merge step?
2857 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002858 break;
2859
2860 case STATISTICS:
2861 TotalNumStatements += Record[0];
2862 TotalNumMacros += Record[1];
2863 TotalLexicalDeclContexts += Record[2];
2864 TotalVisibleDeclContexts += Record[3];
2865 break;
2866
2867 case UNUSED_FILESCOPED_DECLS:
2868 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2869 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2870 break;
2871
2872 case DELEGATING_CTORS:
2873 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2874 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2875 break;
2876
2877 case WEAK_UNDECLARED_IDENTIFIERS:
2878 if (Record.size() % 4 != 0) {
2879 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002880 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002881 }
2882
2883 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2884 // files. This isn't the way to do it :)
2885 WeakUndeclaredIdentifiers.clear();
2886
2887 // Translate the weak, undeclared identifiers into global IDs.
2888 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2889 WeakUndeclaredIdentifiers.push_back(
2890 getGlobalIdentifierID(F, Record[I++]));
2891 WeakUndeclaredIdentifiers.push_back(
2892 getGlobalIdentifierID(F, Record[I++]));
2893 WeakUndeclaredIdentifiers.push_back(
2894 ReadSourceLocation(F, Record, I).getRawEncoding());
2895 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2896 }
2897 break;
2898
Guy Benyei11169dd2012-12-18 14:30:41 +00002899 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002900 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002901 F.LocalNumSelectors = Record[0];
2902 unsigned LocalBaseSelectorID = Record[1];
2903 F.BaseSelectorID = getTotalNumSelectors();
2904
2905 if (F.LocalNumSelectors > 0) {
2906 // Introduce the global -> local mapping for selectors within this
2907 // module.
2908 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2909
2910 // Introduce the local -> global mapping for selectors within this
2911 // module.
2912 F.SelectorRemap.insertOrReplace(
2913 std::make_pair(LocalBaseSelectorID,
2914 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002915
2916 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002917 }
2918 break;
2919 }
2920
2921 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002922 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002923 if (Record[0])
2924 F.SelectorLookupTable
2925 = ASTSelectorLookupTable::Create(
2926 F.SelectorLookupTableData + Record[0],
2927 F.SelectorLookupTableData,
2928 ASTSelectorLookupTrait(*this, F));
2929 TotalNumMethodPoolEntries += Record[1];
2930 break;
2931
2932 case REFERENCED_SELECTOR_POOL:
2933 if (!Record.empty()) {
2934 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2935 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2936 Record[Idx++]));
2937 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2938 getRawEncoding());
2939 }
2940 }
2941 break;
2942
2943 case PP_COUNTER_VALUE:
2944 if (!Record.empty() && Listener)
2945 Listener->ReadCounter(F, Record[0]);
2946 break;
2947
2948 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002949 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002950 F.NumFileSortedDecls = Record[0];
2951 break;
2952
2953 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002954 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002955 F.LocalNumSLocEntries = Record[0];
2956 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002957 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002958 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002959 SLocSpaceSize);
2960 // Make our entry in the range map. BaseID is negative and growing, so
2961 // we invert it. Because we invert it, though, we need the other end of
2962 // the range.
2963 unsigned RangeStart =
2964 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2965 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2966 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2967
2968 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2969 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2970 GlobalSLocOffsetMap.insert(
2971 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2972 - SLocSpaceSize,&F));
2973
2974 // Initialize the remapping table.
2975 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002976 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002977 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002978 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002979 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2980
2981 TotalNumSLocEntries += F.LocalNumSLocEntries;
2982 break;
2983 }
2984
2985 case MODULE_OFFSET_MAP: {
2986 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002987 const unsigned char *Data = (const unsigned char*)Blob.data();
2988 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002989
2990 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2991 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2992 F.SLocRemap.insert(std::make_pair(0U, 0));
2993 F.SLocRemap.insert(std::make_pair(2U, 1));
2994 }
2995
Guy Benyei11169dd2012-12-18 14:30:41 +00002996 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002997 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2998 RemapBuilder;
2999 RemapBuilder SLocRemap(F.SLocRemap);
3000 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3001 RemapBuilder MacroRemap(F.MacroRemap);
3002 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3003 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3004 RemapBuilder SelectorRemap(F.SelectorRemap);
3005 RemapBuilder DeclRemap(F.DeclRemap);
3006 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00003007
3008 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00003009 using namespace llvm::support;
3010 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00003011 StringRef Name = StringRef((const char*)Data, Len);
3012 Data += Len;
3013 ModuleFile *OM = ModuleMgr.lookup(Name);
3014 if (!OM) {
3015 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003016 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003017 }
3018
Justin Bogner57ba0b22014-03-28 22:03:24 +00003019 uint32_t SLocOffset =
3020 endian::readNext<uint32_t, little, unaligned>(Data);
3021 uint32_t IdentifierIDOffset =
3022 endian::readNext<uint32_t, little, unaligned>(Data);
3023 uint32_t MacroIDOffset =
3024 endian::readNext<uint32_t, little, unaligned>(Data);
3025 uint32_t PreprocessedEntityIDOffset =
3026 endian::readNext<uint32_t, little, unaligned>(Data);
3027 uint32_t SubmoduleIDOffset =
3028 endian::readNext<uint32_t, little, unaligned>(Data);
3029 uint32_t SelectorIDOffset =
3030 endian::readNext<uint32_t, little, unaligned>(Data);
3031 uint32_t DeclIDOffset =
3032 endian::readNext<uint32_t, little, unaligned>(Data);
3033 uint32_t TypeIndexOffset =
3034 endian::readNext<uint32_t, little, unaligned>(Data);
3035
Ben Langmuir785180e2014-10-20 16:27:30 +00003036 uint32_t None = std::numeric_limits<uint32_t>::max();
3037
3038 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3039 RemapBuilder &Remap) {
3040 if (Offset != None)
3041 Remap.insert(std::make_pair(Offset,
3042 static_cast<int>(BaseOffset - Offset)));
3043 };
3044 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3045 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3046 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3047 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3048 PreprocessedEntityRemap);
3049 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3050 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3051 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3052 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00003053
3054 // Global -> local mappings.
3055 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3056 }
3057 break;
3058 }
3059
3060 case SOURCE_MANAGER_LINE_TABLE:
3061 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003062 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003063 break;
3064
3065 case SOURCE_LOCATION_PRELOADS: {
3066 // Need to transform from the local view (1-based IDs) to the global view,
3067 // which is based off F.SLocEntryBaseID.
3068 if (!F.PreloadSLocEntries.empty()) {
3069 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003070 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003071 }
3072
3073 F.PreloadSLocEntries.swap(Record);
3074 break;
3075 }
3076
3077 case EXT_VECTOR_DECLS:
3078 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3079 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3080 break;
3081
3082 case VTABLE_USES:
3083 if (Record.size() % 3 != 0) {
3084 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003085 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003086 }
3087
3088 // Later tables overwrite earlier ones.
3089 // FIXME: Modules will have some trouble with this. This is clearly not
3090 // the right way to do this.
3091 VTableUses.clear();
3092
3093 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3094 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3095 VTableUses.push_back(
3096 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3097 VTableUses.push_back(Record[Idx++]);
3098 }
3099 break;
3100
Guy Benyei11169dd2012-12-18 14:30:41 +00003101 case PENDING_IMPLICIT_INSTANTIATIONS:
3102 if (PendingInstantiations.size() % 2 != 0) {
3103 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003104 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003105 }
3106
3107 if (Record.size() % 2 != 0) {
3108 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003109 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003110 }
3111
3112 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3113 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3114 PendingInstantiations.push_back(
3115 ReadSourceLocation(F, Record, I).getRawEncoding());
3116 }
3117 break;
3118
3119 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00003120 if (Record.size() != 2) {
3121 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003122 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003123 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003124 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3125 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3126 break;
3127
3128 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003129 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3130 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3131 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003132
3133 unsigned LocalBasePreprocessedEntityID = Record[0];
3134
3135 unsigned StartingID;
3136 if (!PP.getPreprocessingRecord())
3137 PP.createPreprocessingRecord();
3138 if (!PP.getPreprocessingRecord()->getExternalSource())
3139 PP.getPreprocessingRecord()->SetExternalSource(*this);
3140 StartingID
3141 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003142 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003143 F.BasePreprocessedEntityID = StartingID;
3144
3145 if (F.NumPreprocessedEntities > 0) {
3146 // Introduce the global -> local mapping for preprocessed entities in
3147 // this module.
3148 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3149
3150 // Introduce the local -> global mapping for preprocessed entities in
3151 // this module.
3152 F.PreprocessedEntityRemap.insertOrReplace(
3153 std::make_pair(LocalBasePreprocessedEntityID,
3154 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3155 }
3156
3157 break;
3158 }
3159
3160 case DECL_UPDATE_OFFSETS: {
3161 if (Record.size() % 2 != 0) {
3162 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003163 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003164 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003165 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3166 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3167 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3168
3169 // If we've already loaded the decl, perform the updates when we finish
3170 // loading this block.
3171 if (Decl *D = GetExistingDecl(ID))
3172 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3173 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003174 break;
3175 }
3176
3177 case DECL_REPLACEMENTS: {
3178 if (Record.size() % 3 != 0) {
3179 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003180 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003181 }
3182 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3183 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3184 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3185 break;
3186 }
3187
3188 case OBJC_CATEGORIES_MAP: {
3189 if (F.LocalNumObjCCategoriesInMap != 0) {
3190 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003191 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003192 }
3193
3194 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003195 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003196 break;
3197 }
3198
3199 case OBJC_CATEGORIES:
3200 F.ObjCCategories.swap(Record);
3201 break;
3202
3203 case CXX_BASE_SPECIFIER_OFFSETS: {
3204 if (F.LocalNumCXXBaseSpecifiers != 0) {
3205 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003206 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003207 }
3208
3209 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003210 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003211 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
3212 break;
3213 }
3214
3215 case DIAG_PRAGMA_MAPPINGS:
3216 if (F.PragmaDiagMappings.empty())
3217 F.PragmaDiagMappings.swap(Record);
3218 else
3219 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3220 Record.begin(), Record.end());
3221 break;
3222
3223 case CUDA_SPECIAL_DECL_REFS:
3224 // Later tables overwrite earlier ones.
3225 // FIXME: Modules will have trouble with this.
3226 CUDASpecialDeclRefs.clear();
3227 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3228 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3229 break;
3230
3231 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003232 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003233 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003234 if (Record[0]) {
3235 F.HeaderFileInfoTable
3236 = HeaderFileInfoLookupTable::Create(
3237 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3238 (const unsigned char *)F.HeaderFileInfoTableData,
3239 HeaderFileInfoTrait(*this, F,
3240 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003241 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003242
3243 PP.getHeaderSearchInfo().SetExternalSource(this);
3244 if (!PP.getHeaderSearchInfo().getExternalLookup())
3245 PP.getHeaderSearchInfo().SetExternalLookup(this);
3246 }
3247 break;
3248 }
3249
3250 case FP_PRAGMA_OPTIONS:
3251 // Later tables overwrite earlier ones.
3252 FPPragmaOptions.swap(Record);
3253 break;
3254
3255 case OPENCL_EXTENSIONS:
3256 // Later tables overwrite earlier ones.
3257 OpenCLExtensions.swap(Record);
3258 break;
3259
3260 case TENTATIVE_DEFINITIONS:
3261 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3262 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3263 break;
3264
3265 case KNOWN_NAMESPACES:
3266 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3267 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3268 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003269
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003270 case UNDEFINED_BUT_USED:
3271 if (UndefinedButUsed.size() % 2 != 0) {
3272 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003273 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003274 }
3275
3276 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003277 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003278 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003279 }
3280 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003281 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3282 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003283 ReadSourceLocation(F, Record, I).getRawEncoding());
3284 }
3285 break;
3286
Guy Benyei11169dd2012-12-18 14:30:41 +00003287 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003288 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003289 // If we aren't loading a module (which has its own exports), make
3290 // all of the imported modules visible.
3291 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003292 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3293 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3294 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3295 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003296 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003297 }
3298 }
3299 break;
3300 }
3301
3302 case LOCAL_REDECLARATIONS: {
3303 F.RedeclarationChains.swap(Record);
3304 break;
3305 }
3306
3307 case LOCAL_REDECLARATIONS_MAP: {
3308 if (F.LocalNumRedeclarationsInMap != 0) {
3309 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003310 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003311 }
3312
3313 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003314 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003315 break;
3316 }
3317
Guy Benyei11169dd2012-12-18 14:30:41 +00003318 case MACRO_OFFSET: {
3319 if (F.LocalNumMacros != 0) {
3320 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003321 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003322 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003323 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003324 F.LocalNumMacros = Record[0];
3325 unsigned LocalBaseMacroID = Record[1];
3326 F.BaseMacroID = getTotalNumMacros();
3327
3328 if (F.LocalNumMacros > 0) {
3329 // Introduce the global -> local mapping for macros within this module.
3330 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3331
3332 // Introduce the local -> global mapping for macros within this module.
3333 F.MacroRemap.insertOrReplace(
3334 std::make_pair(LocalBaseMacroID,
3335 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003336
3337 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003338 }
3339 break;
3340 }
3341
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003342 case MACRO_TABLE: {
3343 // FIXME: Not used yet.
Guy Benyei11169dd2012-12-18 14:30:41 +00003344 break;
3345 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00003346
3347 case LATE_PARSED_TEMPLATE: {
3348 LateParsedTemplates.append(Record.begin(), Record.end());
3349 break;
3350 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003351
3352 case OPTIMIZE_PRAGMA_OPTIONS:
3353 if (Record.size() != 1) {
3354 Error("invalid pragma optimize record");
3355 return Failure;
3356 }
3357 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3358 break;
Nico Weber72889432014-09-06 01:25:55 +00003359
3360 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3361 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3362 UnusedLocalTypedefNameCandidates.push_back(
3363 getGlobalDeclID(F, Record[I]));
3364 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003365 }
3366 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003367}
3368
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003369ASTReader::ASTReadResult
3370ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3371 const ModuleFile *ImportedBy,
3372 unsigned ClientLoadCapabilities) {
3373 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003374 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003375
Richard Smithe842a472014-10-22 02:05:46 +00003376 if (F.Kind == MK_ExplicitModule) {
3377 // For an explicitly-loaded module, we don't care whether the original
3378 // module map file exists or matches.
3379 return Success;
3380 }
3381
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003382 // Try to resolve ModuleName in the current header search context and
3383 // verify that it is found in the same module map file as we saved. If the
3384 // top-level AST file is a main file, skip this check because there is no
3385 // usable header search context.
3386 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003387 "MODULE_NAME should come before MODULE_MAP_FILE");
3388 if (F.Kind == MK_ImplicitModule &&
3389 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3390 // An implicitly-loaded module file should have its module listed in some
3391 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003392 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003393 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3394 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3395 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003396 assert(ImportedBy && "top-level import should be verified");
3397 if ((ClientLoadCapabilities & ARR_Missing) == 0)
Richard Smithe842a472014-10-22 02:05:46 +00003398 Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3399 << ImportedBy->FileName
3400 << F.ModuleMapPath;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003401 return Missing;
3402 }
3403
Richard Smithe842a472014-10-22 02:05:46 +00003404 assert(M->Name == F.ModuleName && "found module with different name");
3405
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003406 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003407 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003408 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3409 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003410 assert(ImportedBy && "top-level import should be verified");
3411 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3412 Diag(diag::err_imported_module_modmap_changed)
3413 << F.ModuleName << ImportedBy->FileName
3414 << ModMap->getName() << F.ModuleMapPath;
3415 return OutOfDate;
3416 }
3417
3418 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3419 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3420 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003421 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003422 const FileEntry *F =
3423 FileMgr.getFile(Filename, false, false);
3424 if (F == nullptr) {
3425 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3426 Error("could not find file '" + Filename +"' referenced by AST file");
3427 return OutOfDate;
3428 }
3429 AdditionalStoredMaps.insert(F);
3430 }
3431
3432 // Check any additional module map files (e.g. module.private.modulemap)
3433 // that are not in the pcm.
3434 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3435 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3436 // Remove files that match
3437 // Note: SmallPtrSet::erase is really remove
3438 if (!AdditionalStoredMaps.erase(ModMap)) {
3439 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3440 Diag(diag::err_module_different_modmap)
3441 << F.ModuleName << /*new*/0 << ModMap->getName();
3442 return OutOfDate;
3443 }
3444 }
3445 }
3446
3447 // Check any additional module map files that are in the pcm, but not
3448 // found in header search. Cases that match are already removed.
3449 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3450 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3451 Diag(diag::err_module_different_modmap)
3452 << F.ModuleName << /*not new*/1 << ModMap->getName();
3453 return OutOfDate;
3454 }
3455 }
3456
3457 if (Listener)
3458 Listener->ReadModuleMapFile(F.ModuleMapPath);
3459 return Success;
3460}
3461
3462
Douglas Gregorc1489562013-02-12 23:36:21 +00003463/// \brief Move the given method to the back of the global list of methods.
3464static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3465 // Find the entry for this selector in the method pool.
3466 Sema::GlobalMethodPool::iterator Known
3467 = S.MethodPool.find(Method->getSelector());
3468 if (Known == S.MethodPool.end())
3469 return;
3470
3471 // Retrieve the appropriate method list.
3472 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3473 : Known->second.second;
3474 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003475 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003476 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003477 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003478 Found = true;
3479 } else {
3480 // Keep searching.
3481 continue;
3482 }
3483 }
3484
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003485 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003486 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003487 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003488 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003489 }
3490}
3491
Richard Smithe657bbd2014-07-18 22:13:40 +00003492void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner,
3493 bool FromFinalization) {
3494 // FIXME: Only do this if Owner->NameVisibility == AllVisible.
Richard Smith57721ac2014-07-21 04:10:40 +00003495 for (Decl *D : Names.HiddenDecls) {
Richard Smith49f906a2014-03-01 00:08:04 +00003496 bool wasHidden = D->Hidden;
3497 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003498
Richard Smith49f906a2014-03-01 00:08:04 +00003499 if (wasHidden && SemaObj) {
3500 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3501 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003502 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003503 }
3504 }
Richard Smith49f906a2014-03-01 00:08:04 +00003505
Richard Smithe657bbd2014-07-18 22:13:40 +00003506 assert((FromFinalization || Owner->NameVisibility >= Module::MacrosVisible) &&
3507 "nothing to make visible?");
Richard Smithdaa69e02014-07-25 04:40:03 +00003508 for (const auto &Macro : Names.HiddenMacros) {
3509 if (FromFinalization)
3510 PP.appendMacroDirective(Macro.first,
3511 Macro.second->import(PP, SourceLocation()));
3512 else
3513 installImportedMacro(Macro.first, Macro.second, Owner);
3514 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003515}
3516
Richard Smith49f906a2014-03-01 00:08:04 +00003517void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003518 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003519 SourceLocation ImportLoc,
3520 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003521 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003522 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003523 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003524 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003525 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003526
3527 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003528 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003529 // there is nothing more to do.
3530 continue;
3531 }
Richard Smith49f906a2014-03-01 00:08:04 +00003532
Guy Benyei11169dd2012-12-18 14:30:41 +00003533 if (!Mod->isAvailable()) {
3534 // Modules that aren't available cannot be made visible.
3535 continue;
3536 }
3537
3538 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003539 if (NameVisibility >= Module::MacrosVisible &&
3540 Mod->NameVisibility < Module::MacrosVisible)
3541 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003542 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003543
Guy Benyei11169dd2012-12-18 14:30:41 +00003544 // If we've already deserialized any names from this module,
3545 // mark them as visible.
3546 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3547 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003548 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003549 HiddenNamesMap.erase(Hidden);
Richard Smith57721ac2014-07-21 04:10:40 +00003550 makeNamesVisible(HiddenNames.second, HiddenNames.first,
3551 /*FromFinalization*/false);
3552 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3553 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003554 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003555
Guy Benyei11169dd2012-12-18 14:30:41 +00003556 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003557 SmallVector<Module *, 16> Exports;
3558 Mod->getExportedModules(Exports);
3559 for (SmallVectorImpl<Module *>::iterator
3560 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3561 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003562 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003563 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003564 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003565
3566 // Detect any conflicts.
3567 if (Complain) {
3568 assert(ImportLoc.isValid() && "Missing import location");
3569 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3570 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3571 Diag(ImportLoc, diag::warn_module_conflict)
3572 << Mod->getFullModuleName()
3573 << Mod->Conflicts[I].Other->getFullModuleName()
3574 << Mod->Conflicts[I].Message;
3575 // FIXME: Need note where the other module was imported.
3576 }
3577 }
3578 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003579 }
3580}
3581
Douglas Gregore060e572013-01-25 01:03:03 +00003582bool ASTReader::loadGlobalIndex() {
3583 if (GlobalIndex)
3584 return false;
3585
3586 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3587 !Context.getLangOpts().Modules)
3588 return true;
3589
3590 // Try to load the global index.
3591 TriedLoadingGlobalIndex = true;
3592 StringRef ModuleCachePath
3593 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3594 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003595 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003596 if (!Result.first)
3597 return true;
3598
3599 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003600 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003601 return false;
3602}
3603
3604bool ASTReader::isGlobalIndexUnavailable() const {
3605 return Context.getLangOpts().Modules && UseGlobalIndex &&
3606 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3607}
3608
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003609static void updateModuleTimestamp(ModuleFile &MF) {
3610 // Overwrite the timestamp file contents so that file's mtime changes.
3611 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003612 std::error_code EC;
3613 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3614 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003615 return;
3616 OS << "Timestamp file\n";
3617}
3618
Guy Benyei11169dd2012-12-18 14:30:41 +00003619ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3620 ModuleKind Type,
3621 SourceLocation ImportLoc,
3622 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003623 llvm::SaveAndRestore<SourceLocation>
3624 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3625
Richard Smithd1c46742014-04-30 02:24:17 +00003626 // Defer any pending actions until we get to the end of reading the AST file.
3627 Deserializing AnASTFile(this);
3628
Guy Benyei11169dd2012-12-18 14:30:41 +00003629 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003630 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003631
3632 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003633 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003634 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003635 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003636 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003637 ClientLoadCapabilities)) {
3638 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003639 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003640 case OutOfDate:
3641 case VersionMismatch:
3642 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003643 case HadErrors: {
3644 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3645 for (const ImportedModule &IM : Loaded)
3646 LoadedSet.insert(IM.Mod);
3647
Douglas Gregor7029ce12013-03-19 00:28:20 +00003648 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003649 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003650 Context.getLangOpts().Modules
3651 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003652 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003653
3654 // If we find that any modules are unusable, the global index is going
3655 // to be out-of-date. Just remove it.
3656 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003657 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003658 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003659 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003660 case Success:
3661 break;
3662 }
3663
3664 // Here comes stuff that we only do once the entire chain is loaded.
3665
3666 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003667 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3668 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003669 M != MEnd; ++M) {
3670 ModuleFile &F = *M->Mod;
3671
3672 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003673 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3674 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003675
3676 // Once read, set the ModuleFile bit base offset and update the size in
3677 // bits of all files we've seen.
3678 F.GlobalBitOffset = TotalModulesSizeInBits;
3679 TotalModulesSizeInBits += F.SizeInBits;
3680 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3681
3682 // Preload SLocEntries.
3683 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3684 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3685 // Load it through the SourceManager and don't call ReadSLocEntry()
3686 // directly because the entry may have already been loaded in which case
3687 // calling ReadSLocEntry() directly would trigger an assertion in
3688 // SourceManager.
3689 SourceMgr.getLoadedSLocEntryByID(Index);
3690 }
3691 }
3692
Douglas Gregor603cd862013-03-22 18:50:14 +00003693 // Setup the import locations and notify the module manager that we've
3694 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003695 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3696 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003697 M != MEnd; ++M) {
3698 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003699
3700 ModuleMgr.moduleFileAccepted(&F);
3701
3702 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003703 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003704 if (!M->ImportedBy)
3705 F.ImportLoc = M->ImportLoc;
3706 else
3707 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3708 M->ImportLoc.getRawEncoding());
3709 }
3710
3711 // Mark all of the identifiers in the identifier table as being out of date,
3712 // so that various accessors know to check the loaded modules when the
3713 // identifier is used.
3714 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3715 IdEnd = PP.getIdentifierTable().end();
3716 Id != IdEnd; ++Id)
3717 Id->second->setOutOfDate(true);
3718
3719 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003720 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3721 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003722 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3723 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003724
3725 switch (Unresolved.Kind) {
3726 case UnresolvedModuleRef::Conflict:
3727 if (ResolvedMod) {
3728 Module::Conflict Conflict;
3729 Conflict.Other = ResolvedMod;
3730 Conflict.Message = Unresolved.String.str();
3731 Unresolved.Mod->Conflicts.push_back(Conflict);
3732 }
3733 continue;
3734
3735 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003736 if (ResolvedMod)
3737 Unresolved.Mod->Imports.push_back(ResolvedMod);
3738 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003739
Douglas Gregorfb912652013-03-20 21:10:35 +00003740 case UnresolvedModuleRef::Export:
3741 if (ResolvedMod || Unresolved.IsWildcard)
3742 Unresolved.Mod->Exports.push_back(
3743 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3744 continue;
3745 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003746 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003747 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003748
3749 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3750 // Might be unnecessary as use declarations are only used to build the
3751 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003752
3753 InitializeContext();
3754
Richard Smith3d8e97e2013-10-18 06:54:39 +00003755 if (SemaObj)
3756 UpdateSema();
3757
Guy Benyei11169dd2012-12-18 14:30:41 +00003758 if (DeserializationListener)
3759 DeserializationListener->ReaderInitialized(this);
3760
3761 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3762 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3763 PrimaryModule.OriginalSourceFileID
3764 = FileID::get(PrimaryModule.SLocEntryBaseID
3765 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3766
3767 // If this AST file is a precompiled preamble, then set the
3768 // preamble file ID of the source manager to the file source file
3769 // from which the preamble was built.
3770 if (Type == MK_Preamble) {
3771 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3772 } else if (Type == MK_MainFile) {
3773 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3774 }
3775 }
3776
3777 // For any Objective-C class definitions we have already loaded, make sure
3778 // that we load any additional categories.
3779 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3780 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3781 ObjCClassesLoaded[I],
3782 PreviousGeneration);
3783 }
Douglas Gregore060e572013-01-25 01:03:03 +00003784
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003785 if (PP.getHeaderSearchInfo()
3786 .getHeaderSearchOpts()
3787 .ModulesValidateOncePerBuildSession) {
3788 // Now we are certain that the module and all modules it depends on are
3789 // up to date. Create or update timestamp files for modules that are
3790 // located in the module cache (not for PCH files that could be anywhere
3791 // in the filesystem).
3792 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3793 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003794 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003795 updateModuleTimestamp(*M.Mod);
3796 }
3797 }
3798 }
3799
Guy Benyei11169dd2012-12-18 14:30:41 +00003800 return Success;
3801}
3802
Ben Langmuir487ea142014-10-23 18:05:36 +00003803static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3804
Guy Benyei11169dd2012-12-18 14:30:41 +00003805ASTReader::ASTReadResult
3806ASTReader::ReadASTCore(StringRef FileName,
3807 ModuleKind Type,
3808 SourceLocation ImportLoc,
3809 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003810 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003811 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003812 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003813 unsigned ClientLoadCapabilities) {
3814 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003815 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003816 ModuleManager::AddModuleResult AddResult
3817 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003818 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003819 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003820 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003821
Douglas Gregor7029ce12013-03-19 00:28:20 +00003822 switch (AddResult) {
3823 case ModuleManager::AlreadyLoaded:
3824 return Success;
3825
3826 case ModuleManager::NewlyLoaded:
3827 // Load module file below.
3828 break;
3829
3830 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003831 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003832 // it.
3833 if (ClientLoadCapabilities & ARR_Missing)
3834 return Missing;
3835
3836 // Otherwise, return an error.
3837 {
3838 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3839 + ErrorStr;
3840 Error(Msg);
3841 }
3842 return Failure;
3843
3844 case ModuleManager::OutOfDate:
3845 // We couldn't load the module file because it is out-of-date. If the
3846 // client can handle out-of-date, return it.
3847 if (ClientLoadCapabilities & ARR_OutOfDate)
3848 return OutOfDate;
3849
3850 // Otherwise, return an error.
3851 {
3852 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3853 + ErrorStr;
3854 Error(Msg);
3855 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003856 return Failure;
3857 }
3858
Douglas Gregor7029ce12013-03-19 00:28:20 +00003859 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003860
3861 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3862 // module?
3863 if (FileName != "-") {
3864 CurrentDir = llvm::sys::path::parent_path(FileName);
3865 if (CurrentDir.empty()) CurrentDir = ".";
3866 }
3867
3868 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003869 BitstreamCursor &Stream = F.Stream;
Rafael Espindolafd832392014-11-12 14:48:44 +00003870 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003871 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3872
Guy Benyei11169dd2012-12-18 14:30:41 +00003873 // Sniff for the signature.
3874 if (Stream.Read(8) != 'C' ||
3875 Stream.Read(8) != 'P' ||
3876 Stream.Read(8) != 'C' ||
3877 Stream.Read(8) != 'H') {
3878 Diag(diag::err_not_a_pch_file) << FileName;
3879 return Failure;
3880 }
3881
3882 // This is used for compatibility with older PCH formats.
3883 bool HaveReadControlBlock = false;
3884
Chris Lattnerefa77172013-01-20 00:00:22 +00003885 while (1) {
3886 llvm::BitstreamEntry Entry = Stream.advance();
3887
3888 switch (Entry.Kind) {
3889 case llvm::BitstreamEntry::Error:
3890 case llvm::BitstreamEntry::EndBlock:
3891 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003892 Error("invalid record at top-level of AST file");
3893 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003894
3895 case llvm::BitstreamEntry::SubBlock:
3896 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003897 }
3898
Guy Benyei11169dd2012-12-18 14:30:41 +00003899 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003900 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003901 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3902 if (Stream.ReadBlockInfoBlock()) {
3903 Error("malformed BlockInfoBlock in AST file");
3904 return Failure;
3905 }
3906 break;
3907 case CONTROL_BLOCK_ID:
3908 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003909 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003910 case Success:
3911 break;
3912
3913 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003914 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003915 case OutOfDate: return OutOfDate;
3916 case VersionMismatch: return VersionMismatch;
3917 case ConfigurationMismatch: return ConfigurationMismatch;
3918 case HadErrors: return HadErrors;
3919 }
3920 break;
3921 case AST_BLOCK_ID:
3922 if (!HaveReadControlBlock) {
3923 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003924 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003925 return VersionMismatch;
3926 }
3927
3928 // Record that we've loaded this module.
3929 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3930 return Success;
3931
3932 default:
3933 if (Stream.SkipBlock()) {
3934 Error("malformed block record in AST file");
3935 return Failure;
3936 }
3937 break;
3938 }
3939 }
3940
3941 return Success;
3942}
3943
3944void ASTReader::InitializeContext() {
3945 // If there's a listener, notify them that we "read" the translation unit.
3946 if (DeserializationListener)
3947 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3948 Context.getTranslationUnitDecl());
3949
Guy Benyei11169dd2012-12-18 14:30:41 +00003950 // FIXME: Find a better way to deal with collisions between these
3951 // built-in types. Right now, we just ignore the problem.
3952
3953 // Load the special types.
3954 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3955 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3956 if (!Context.CFConstantStringTypeDecl)
3957 Context.setCFConstantStringType(GetType(String));
3958 }
3959
3960 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3961 QualType FileType = GetType(File);
3962 if (FileType.isNull()) {
3963 Error("FILE type is NULL");
3964 return;
3965 }
3966
3967 if (!Context.FILEDecl) {
3968 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3969 Context.setFILEDecl(Typedef->getDecl());
3970 else {
3971 const TagType *Tag = FileType->getAs<TagType>();
3972 if (!Tag) {
3973 Error("Invalid FILE type in AST file");
3974 return;
3975 }
3976 Context.setFILEDecl(Tag->getDecl());
3977 }
3978 }
3979 }
3980
3981 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3982 QualType Jmp_bufType = GetType(Jmp_buf);
3983 if (Jmp_bufType.isNull()) {
3984 Error("jmp_buf type is NULL");
3985 return;
3986 }
3987
3988 if (!Context.jmp_bufDecl) {
3989 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3990 Context.setjmp_bufDecl(Typedef->getDecl());
3991 else {
3992 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3993 if (!Tag) {
3994 Error("Invalid jmp_buf type in AST file");
3995 return;
3996 }
3997 Context.setjmp_bufDecl(Tag->getDecl());
3998 }
3999 }
4000 }
4001
4002 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4003 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4004 if (Sigjmp_bufType.isNull()) {
4005 Error("sigjmp_buf type is NULL");
4006 return;
4007 }
4008
4009 if (!Context.sigjmp_bufDecl) {
4010 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4011 Context.setsigjmp_bufDecl(Typedef->getDecl());
4012 else {
4013 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4014 assert(Tag && "Invalid sigjmp_buf type in AST file");
4015 Context.setsigjmp_bufDecl(Tag->getDecl());
4016 }
4017 }
4018 }
4019
4020 if (unsigned ObjCIdRedef
4021 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4022 if (Context.ObjCIdRedefinitionType.isNull())
4023 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4024 }
4025
4026 if (unsigned ObjCClassRedef
4027 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4028 if (Context.ObjCClassRedefinitionType.isNull())
4029 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4030 }
4031
4032 if (unsigned ObjCSelRedef
4033 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4034 if (Context.ObjCSelRedefinitionType.isNull())
4035 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4036 }
4037
4038 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4039 QualType Ucontext_tType = GetType(Ucontext_t);
4040 if (Ucontext_tType.isNull()) {
4041 Error("ucontext_t type is NULL");
4042 return;
4043 }
4044
4045 if (!Context.ucontext_tDecl) {
4046 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4047 Context.setucontext_tDecl(Typedef->getDecl());
4048 else {
4049 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4050 assert(Tag && "Invalid ucontext_t type in AST file");
4051 Context.setucontext_tDecl(Tag->getDecl());
4052 }
4053 }
4054 }
4055 }
4056
4057 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4058
4059 // If there were any CUDA special declarations, deserialize them.
4060 if (!CUDASpecialDeclRefs.empty()) {
4061 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4062 Context.setcudaConfigureCallDecl(
4063 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4064 }
Richard Smith56be7542014-03-21 00:33:59 +00004065
Guy Benyei11169dd2012-12-18 14:30:41 +00004066 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00004067 // FIXME: This does not make macro-only imports visible again. It also doesn't
4068 // make #includes mapped to module imports visible.
4069 for (auto &Import : ImportedModules) {
4070 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004071 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00004072 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00004073 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00004074 }
4075 ImportedModules.clear();
4076}
4077
4078void ASTReader::finalizeForWriting() {
Richard Smith57721ac2014-07-21 04:10:40 +00004079 while (!HiddenNamesMap.empty()) {
4080 auto HiddenNames = std::move(*HiddenNamesMap.begin());
4081 HiddenNamesMap.erase(HiddenNamesMap.begin());
4082 makeNamesVisible(HiddenNames.second, HiddenNames.first,
4083 /*FromFinalization*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004084 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004085}
4086
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004087/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
4088/// cursor into the start of the given block ID, returning false on success and
4089/// true on failure.
4090static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004091 while (1) {
4092 llvm::BitstreamEntry Entry = Cursor.advance();
4093 switch (Entry.Kind) {
4094 case llvm::BitstreamEntry::Error:
4095 case llvm::BitstreamEntry::EndBlock:
4096 return true;
4097
4098 case llvm::BitstreamEntry::Record:
4099 // Ignore top-level records.
4100 Cursor.skipRecord(Entry.ID);
4101 break;
4102
4103 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004104 if (Entry.ID == BlockID) {
4105 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004106 return true;
4107 // Found it!
4108 return false;
4109 }
4110
4111 if (Cursor.SkipBlock())
4112 return true;
4113 }
4114 }
4115}
4116
Ben Langmuir487ea142014-10-23 18:05:36 +00004117static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
4118 BitstreamCursor Stream(StreamFile);
4119 if (Stream.Read(8) != 'C' ||
4120 Stream.Read(8) != 'P' ||
4121 Stream.Read(8) != 'C' ||
4122 Stream.Read(8) != 'H') {
4123 return 0;
4124 }
4125
4126 // Scan for the CONTROL_BLOCK_ID block.
4127 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4128 return 0;
4129
4130 // Scan for SIGNATURE inside the control block.
4131 ASTReader::RecordData Record;
4132 while (1) {
4133 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4134 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
4135 Entry.Kind != llvm::BitstreamEntry::Record)
4136 return 0;
4137
4138 Record.clear();
4139 StringRef Blob;
4140 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4141 return Record[0];
4142 }
4143}
4144
Guy Benyei11169dd2012-12-18 14:30:41 +00004145/// \brief Retrieve the name of the original source file name
4146/// directly from the AST file, without actually loading the AST
4147/// file.
4148std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
4149 FileManager &FileMgr,
4150 DiagnosticsEngine &Diags) {
4151 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004152 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004153 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004154 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4155 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004156 return std::string();
4157 }
4158
4159 // Initialize the stream
4160 llvm::BitstreamReader StreamFile;
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004161 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
4162 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004163 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004164
4165 // Sniff for the signature.
4166 if (Stream.Read(8) != 'C' ||
4167 Stream.Read(8) != 'P' ||
4168 Stream.Read(8) != 'C' ||
4169 Stream.Read(8) != 'H') {
4170 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4171 return std::string();
4172 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004173
Chris Lattnere7b154b2013-01-19 21:39:22 +00004174 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004175 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004176 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4177 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004178 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004179
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004180 // Scan for ORIGINAL_FILE inside the control block.
4181 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004182 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004183 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004184 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4185 return std::string();
4186
4187 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4188 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4189 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004190 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004191
Guy Benyei11169dd2012-12-18 14:30:41 +00004192 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004193 StringRef Blob;
4194 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4195 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004196 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004197}
4198
4199namespace {
4200 class SimplePCHValidator : public ASTReaderListener {
4201 const LangOptions &ExistingLangOpts;
4202 const TargetOptions &ExistingTargetOpts;
4203 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004204 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004205 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004206
Guy Benyei11169dd2012-12-18 14:30:41 +00004207 public:
4208 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4209 const TargetOptions &ExistingTargetOpts,
4210 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004211 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004212 FileManager &FileMgr)
4213 : ExistingLangOpts(ExistingLangOpts),
4214 ExistingTargetOpts(ExistingTargetOpts),
4215 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004216 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004217 FileMgr(FileMgr)
4218 {
4219 }
4220
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004221 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4222 bool AllowCompatibleDifferences) override {
4223 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4224 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004225 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004226 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4227 bool AllowCompatibleDifferences) override {
4228 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4229 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004230 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004231 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4232 StringRef SpecificModuleCachePath,
4233 bool Complain) override {
4234 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4235 ExistingModuleCachePath,
4236 nullptr, ExistingLangOpts);
4237 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004238 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4239 bool Complain,
4240 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004241 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004242 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004243 }
4244 };
4245}
4246
4247bool ASTReader::readASTFileControlBlock(StringRef Filename,
4248 FileManager &FileMgr,
4249 ASTReaderListener &Listener) {
4250 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004251 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004252 if (!Buffer) {
4253 return true;
4254 }
4255
4256 // Initialize the stream
4257 llvm::BitstreamReader StreamFile;
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004258 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
4259 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004260 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004261
4262 // Sniff for the signature.
4263 if (Stream.Read(8) != 'C' ||
4264 Stream.Read(8) != 'P' ||
4265 Stream.Read(8) != 'C' ||
4266 Stream.Read(8) != 'H') {
4267 return true;
4268 }
4269
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004270 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004271 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004272 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004273
4274 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004275 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004276 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004277 BitstreamCursor InputFilesCursor;
4278 if (NeedsInputFiles) {
4279 InputFilesCursor = Stream;
4280 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4281 return true;
4282
4283 // Read the abbreviations
4284 while (true) {
4285 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4286 unsigned Code = InputFilesCursor.ReadCode();
4287
4288 // We expect all abbrevs to be at the start of the block.
4289 if (Code != llvm::bitc::DEFINE_ABBREV) {
4290 InputFilesCursor.JumpToBit(Offset);
4291 break;
4292 }
4293 InputFilesCursor.ReadAbbrevRecord();
4294 }
4295 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004296
4297 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004298 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004299 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004300 while (1) {
4301 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4302 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4303 return false;
4304
4305 if (Entry.Kind != llvm::BitstreamEntry::Record)
4306 return true;
4307
Guy Benyei11169dd2012-12-18 14:30:41 +00004308 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004309 StringRef Blob;
4310 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004311 switch ((ControlRecordTypes)RecCode) {
4312 case METADATA: {
4313 if (Record[0] != VERSION_MAJOR)
4314 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004315
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004316 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004317 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004318
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004319 break;
4320 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004321 case MODULE_NAME:
4322 Listener.ReadModuleName(Blob);
4323 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004324 case MODULE_DIRECTORY:
4325 ModuleDir = Blob;
4326 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004327 case MODULE_MAP_FILE: {
4328 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004329 auto Path = ReadString(Record, Idx);
4330 ResolveImportedPath(Path, ModuleDir);
4331 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004332 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004333 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004334 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004335 if (ParseLanguageOptions(Record, false, Listener,
4336 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004337 return true;
4338 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004339
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004340 case TARGET_OPTIONS:
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004341 if (ParseTargetOptions(Record, false, Listener,
4342 /*AllowCompatibleConfigurationMismatch*/ false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004343 return true;
4344 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004345
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004346 case DIAGNOSTIC_OPTIONS:
4347 if (ParseDiagnosticOptions(Record, false, Listener))
4348 return true;
4349 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004350
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004351 case FILE_SYSTEM_OPTIONS:
4352 if (ParseFileSystemOptions(Record, false, Listener))
4353 return true;
4354 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004355
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004356 case HEADER_SEARCH_OPTIONS:
4357 if (ParseHeaderSearchOptions(Record, false, Listener))
4358 return true;
4359 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004360
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004361 case PREPROCESSOR_OPTIONS: {
4362 std::string IgnoredSuggestedPredefines;
4363 if (ParsePreprocessorOptions(Record, false, Listener,
4364 IgnoredSuggestedPredefines))
4365 return true;
4366 break;
4367 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004368
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004369 case INPUT_FILE_OFFSETS: {
4370 if (!NeedsInputFiles)
4371 break;
4372
4373 unsigned NumInputFiles = Record[0];
4374 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004375 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004376 for (unsigned I = 0; I != NumInputFiles; ++I) {
4377 // Go find this input file.
4378 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004379
4380 if (isSystemFile && !NeedsSystemInputFiles)
4381 break; // the rest are system input files
4382
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004383 BitstreamCursor &Cursor = InputFilesCursor;
4384 SavedStreamPosition SavedPosition(Cursor);
4385 Cursor.JumpToBit(InputFileOffs[I]);
4386
4387 unsigned Code = Cursor.ReadCode();
4388 RecordData Record;
4389 StringRef Blob;
4390 bool shouldContinue = false;
4391 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4392 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004393 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004394 std::string Filename = Blob;
4395 ResolveImportedPath(Filename, ModuleDir);
4396 shouldContinue =
4397 Listener.visitInputFile(Filename, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004398 break;
4399 }
4400 if (!shouldContinue)
4401 break;
4402 }
4403 break;
4404 }
4405
Richard Smithd4b230b2014-10-27 23:01:16 +00004406 case IMPORTS: {
4407 if (!NeedsImports)
4408 break;
4409
4410 unsigned Idx = 0, N = Record.size();
4411 while (Idx < N) {
4412 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004413 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004414 std::string Filename = ReadString(Record, Idx);
4415 ResolveImportedPath(Filename, ModuleDir);
4416 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004417 }
4418 break;
4419 }
4420
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004421 default:
4422 // No other validation to perform.
4423 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004424 }
4425 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004426}
4427
4428
4429bool ASTReader::isAcceptableASTFile(StringRef Filename,
4430 FileManager &FileMgr,
4431 const LangOptions &LangOpts,
4432 const TargetOptions &TargetOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004433 const PreprocessorOptions &PPOpts,
4434 std::string ExistingModuleCachePath) {
4435 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4436 ExistingModuleCachePath, FileMgr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004437 return !readASTFileControlBlock(Filename, FileMgr, validator);
4438}
4439
Ben Langmuir2c9af442014-04-10 17:57:43 +00004440ASTReader::ASTReadResult
4441ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004442 // Enter the submodule block.
4443 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4444 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004445 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004446 }
4447
4448 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4449 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004450 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004451 RecordData Record;
4452 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004453 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4454
4455 switch (Entry.Kind) {
4456 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4457 case llvm::BitstreamEntry::Error:
4458 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004459 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004460 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004461 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004462 case llvm::BitstreamEntry::Record:
4463 // The interesting case.
4464 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004465 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004466
Guy Benyei11169dd2012-12-18 14:30:41 +00004467 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004468 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004469 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004470 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4471
4472 if ((Kind == SUBMODULE_METADATA) != First) {
4473 Error("submodule metadata record should be at beginning of block");
4474 return Failure;
4475 }
4476 First = false;
4477
4478 // Submodule information is only valid if we have a current module.
4479 // FIXME: Should we error on these cases?
4480 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4481 Kind != SUBMODULE_DEFINITION)
4482 continue;
4483
4484 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004485 default: // Default behavior: ignore.
4486 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004487
Richard Smith03478d92014-10-23 22:12:14 +00004488 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004489 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004490 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004491 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004492 }
Richard Smith03478d92014-10-23 22:12:14 +00004493
Chris Lattner0e6c9402013-01-20 02:38:54 +00004494 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004495 unsigned Idx = 0;
4496 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4497 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4498 bool IsFramework = Record[Idx++];
4499 bool IsExplicit = Record[Idx++];
4500 bool IsSystem = Record[Idx++];
4501 bool IsExternC = Record[Idx++];
4502 bool InferSubmodules = Record[Idx++];
4503 bool InferExplicitSubmodules = Record[Idx++];
4504 bool InferExportWildcard = Record[Idx++];
4505 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004506
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004507 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004508 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004509 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004510
Guy Benyei11169dd2012-12-18 14:30:41 +00004511 // Retrieve this (sub)module from the module map, creating it if
4512 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004513 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004514 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004515
4516 // FIXME: set the definition loc for CurrentModule, or call
4517 // ModMap.setInferredModuleAllowedBy()
4518
Guy Benyei11169dd2012-12-18 14:30:41 +00004519 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4520 if (GlobalIndex >= SubmodulesLoaded.size() ||
4521 SubmodulesLoaded[GlobalIndex]) {
4522 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004523 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004524 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004525
Douglas Gregor7029ce12013-03-19 00:28:20 +00004526 if (!ParentModule) {
4527 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4528 if (CurFile != F.File) {
4529 if (!Diags.isDiagnosticInFlight()) {
4530 Diag(diag::err_module_file_conflict)
4531 << CurrentModule->getTopLevelModuleName()
4532 << CurFile->getName()
4533 << F.File->getName();
4534 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004535 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004536 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004537 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004538
4539 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004540 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004541
Guy Benyei11169dd2012-12-18 14:30:41 +00004542 CurrentModule->IsFromModuleFile = true;
4543 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004544 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 CurrentModule->InferSubmodules = InferSubmodules;
4546 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4547 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004548 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004549 if (DeserializationListener)
4550 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4551
4552 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004553
Douglas Gregorfb912652013-03-20 21:10:35 +00004554 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004555 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004556 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004557 CurrentModule->UnresolvedConflicts.clear();
4558 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004559 break;
4560 }
4561
4562 case SUBMODULE_UMBRELLA_HEADER: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004563 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004564 if (!CurrentModule->getUmbrellaHeader())
4565 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4566 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004567 // This can be a spurious difference caused by changing the VFS to
4568 // point to a different copy of the file, and it is too late to
4569 // to rebuild safely.
4570 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4571 // after input file validation only real problems would remain and we
4572 // could just error. For now, assume it's okay.
4573 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004574 }
4575 }
4576 break;
4577 }
4578
Richard Smith202210b2014-10-24 20:23:01 +00004579 case SUBMODULE_HEADER:
4580 case SUBMODULE_EXCLUDED_HEADER:
4581 case SUBMODULE_PRIVATE_HEADER:
4582 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004583 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4584 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004585 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004586
Richard Smith202210b2014-10-24 20:23:01 +00004587 case SUBMODULE_TEXTUAL_HEADER:
4588 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4589 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4590 // them here.
4591 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004592
Guy Benyei11169dd2012-12-18 14:30:41 +00004593 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004594 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004595 break;
4596 }
4597
4598 case SUBMODULE_UMBRELLA_DIR: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004599 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004600 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004601 if (!CurrentModule->getUmbrellaDir())
4602 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4603 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004604 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4605 Error("mismatched umbrella directories in submodule");
4606 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004607 }
4608 }
4609 break;
4610 }
4611
4612 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004613 F.BaseSubmoduleID = getTotalNumSubmodules();
4614 F.LocalNumSubmodules = Record[0];
4615 unsigned LocalBaseSubmoduleID = Record[1];
4616 if (F.LocalNumSubmodules > 0) {
4617 // Introduce the global -> local mapping for submodules within this
4618 // module.
4619 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4620
4621 // Introduce the local -> global mapping for submodules within this
4622 // module.
4623 F.SubmoduleRemap.insertOrReplace(
4624 std::make_pair(LocalBaseSubmoduleID,
4625 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004626
Ben Langmuir52ca6782014-10-20 16:27:32 +00004627 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4628 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004629 break;
4630 }
4631
4632 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004633 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004634 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004635 Unresolved.File = &F;
4636 Unresolved.Mod = CurrentModule;
4637 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004638 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004639 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004640 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004641 }
4642 break;
4643 }
4644
4645 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004646 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004647 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004648 Unresolved.File = &F;
4649 Unresolved.Mod = CurrentModule;
4650 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004651 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004652 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004653 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004654 }
4655
4656 // Once we've loaded the set of exports, there's no reason to keep
4657 // the parsed, unresolved exports around.
4658 CurrentModule->UnresolvedExports.clear();
4659 break;
4660 }
4661 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004662 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004663 Context.getTargetInfo());
4664 break;
4665 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004666
4667 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004668 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004669 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004670 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004671
4672 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004673 CurrentModule->ConfigMacros.push_back(Blob.str());
4674 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004675
4676 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004677 UnresolvedModuleRef Unresolved;
4678 Unresolved.File = &F;
4679 Unresolved.Mod = CurrentModule;
4680 Unresolved.ID = Record[0];
4681 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4682 Unresolved.IsWildcard = false;
4683 Unresolved.String = Blob;
4684 UnresolvedModuleRefs.push_back(Unresolved);
4685 break;
4686 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004687 }
4688 }
4689}
4690
4691/// \brief Parse the record that corresponds to a LangOptions data
4692/// structure.
4693///
4694/// This routine parses the language options from the AST file and then gives
4695/// them to the AST listener if one is set.
4696///
4697/// \returns true if the listener deems the file unacceptable, false otherwise.
4698bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4699 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004700 ASTReaderListener &Listener,
4701 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004702 LangOptions LangOpts;
4703 unsigned Idx = 0;
4704#define LANGOPT(Name, Bits, Default, Description) \
4705 LangOpts.Name = Record[Idx++];
4706#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4707 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4708#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004709#define SANITIZER(NAME, ID) \
4710 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004711#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004712
4713 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4714 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4715 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4716
4717 unsigned Length = Record[Idx++];
4718 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4719 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004720
4721 Idx += Length;
4722
4723 // Comment options.
4724 for (unsigned N = Record[Idx++]; N; --N) {
4725 LangOpts.CommentOpts.BlockCommandNames.push_back(
4726 ReadString(Record, Idx));
4727 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004728 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004729
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004730 return Listener.ReadLanguageOptions(LangOpts, Complain,
4731 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004732}
4733
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004734bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4735 ASTReaderListener &Listener,
4736 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004737 unsigned Idx = 0;
4738 TargetOptions TargetOpts;
4739 TargetOpts.Triple = ReadString(Record, Idx);
4740 TargetOpts.CPU = ReadString(Record, Idx);
4741 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004742 for (unsigned N = Record[Idx++]; N; --N) {
4743 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4744 }
4745 for (unsigned N = Record[Idx++]; N; --N) {
4746 TargetOpts.Features.push_back(ReadString(Record, Idx));
4747 }
4748
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004749 return Listener.ReadTargetOptions(TargetOpts, Complain,
4750 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004751}
4752
4753bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4754 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004755 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004756 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004757#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004758#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004759 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004760#include "clang/Basic/DiagnosticOptions.def"
4761
Richard Smith3be1cb22014-08-07 00:24:21 +00004762 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004763 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004764 for (unsigned N = Record[Idx++]; N; --N)
4765 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004766
4767 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4768}
4769
4770bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4771 ASTReaderListener &Listener) {
4772 FileSystemOptions FSOpts;
4773 unsigned Idx = 0;
4774 FSOpts.WorkingDir = ReadString(Record, Idx);
4775 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4776}
4777
4778bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4779 bool Complain,
4780 ASTReaderListener &Listener) {
4781 HeaderSearchOptions HSOpts;
4782 unsigned Idx = 0;
4783 HSOpts.Sysroot = ReadString(Record, Idx);
4784
4785 // Include entries.
4786 for (unsigned N = Record[Idx++]; N; --N) {
4787 std::string Path = ReadString(Record, Idx);
4788 frontend::IncludeDirGroup Group
4789 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004790 bool IsFramework = Record[Idx++];
4791 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004792 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004793 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004794 }
4795
4796 // System header prefixes.
4797 for (unsigned N = Record[Idx++]; N; --N) {
4798 std::string Prefix = ReadString(Record, Idx);
4799 bool IsSystemHeader = Record[Idx++];
4800 HSOpts.SystemHeaderPrefixes.push_back(
4801 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4802 }
4803
4804 HSOpts.ResourceDir = ReadString(Record, Idx);
4805 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004806 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004807 HSOpts.DisableModuleHash = Record[Idx++];
4808 HSOpts.UseBuiltinIncludes = Record[Idx++];
4809 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4810 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4811 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004812 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004813
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004814 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4815 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004816}
4817
4818bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4819 bool Complain,
4820 ASTReaderListener &Listener,
4821 std::string &SuggestedPredefines) {
4822 PreprocessorOptions PPOpts;
4823 unsigned Idx = 0;
4824
4825 // Macro definitions/undefs
4826 for (unsigned N = Record[Idx++]; N; --N) {
4827 std::string Macro = ReadString(Record, Idx);
4828 bool IsUndef = Record[Idx++];
4829 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4830 }
4831
4832 // Includes
4833 for (unsigned N = Record[Idx++]; N; --N) {
4834 PPOpts.Includes.push_back(ReadString(Record, Idx));
4835 }
4836
4837 // Macro Includes
4838 for (unsigned N = Record[Idx++]; N; --N) {
4839 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4840 }
4841
4842 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004843 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004844 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4845 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4846 PPOpts.ObjCXXARCStandardLibrary =
4847 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4848 SuggestedPredefines.clear();
4849 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4850 SuggestedPredefines);
4851}
4852
4853std::pair<ModuleFile *, unsigned>
4854ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4855 GlobalPreprocessedEntityMapType::iterator
4856 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4857 assert(I != GlobalPreprocessedEntityMap.end() &&
4858 "Corrupted global preprocessed entity map");
4859 ModuleFile *M = I->second;
4860 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4861 return std::make_pair(M, LocalIndex);
4862}
4863
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004864llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004865ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4866 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4867 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4868 Mod.NumPreprocessedEntities);
4869
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004870 return llvm::make_range(PreprocessingRecord::iterator(),
4871 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004872}
4873
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004874llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004875ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004876 return llvm::make_range(
4877 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4878 ModuleDeclIterator(this, &Mod,
4879 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004880}
4881
4882PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4883 PreprocessedEntityID PPID = Index+1;
4884 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4885 ModuleFile &M = *PPInfo.first;
4886 unsigned LocalIndex = PPInfo.second;
4887 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4888
Guy Benyei11169dd2012-12-18 14:30:41 +00004889 if (!PP.getPreprocessingRecord()) {
4890 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004891 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004892 }
4893
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004894 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4895 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4896
4897 llvm::BitstreamEntry Entry =
4898 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4899 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004900 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004901
Guy Benyei11169dd2012-12-18 14:30:41 +00004902 // Read the record.
4903 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4904 ReadSourceLocation(M, PPOffs.End));
4905 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004906 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004907 RecordData Record;
4908 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004909 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4910 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004911 switch (RecType) {
4912 case PPD_MACRO_EXPANSION: {
4913 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004914 IdentifierInfo *Name = nullptr;
4915 MacroDefinition *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004916 if (isBuiltin)
4917 Name = getLocalIdentifier(M, Record[1]);
4918 else {
4919 PreprocessedEntityID
4920 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4921 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4922 }
4923
4924 MacroExpansion *ME;
4925 if (isBuiltin)
4926 ME = new (PPRec) MacroExpansion(Name, Range);
4927 else
4928 ME = new (PPRec) MacroExpansion(Def, Range);
4929
4930 return ME;
4931 }
4932
4933 case PPD_MACRO_DEFINITION: {
4934 // Decode the identifier info and then check again; if the macro is
4935 // still defined and associated with the identifier,
4936 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4937 MacroDefinition *MD
4938 = new (PPRec) MacroDefinition(II, Range);
4939
4940 if (DeserializationListener)
4941 DeserializationListener->MacroDefinitionRead(PPID, MD);
4942
4943 return MD;
4944 }
4945
4946 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004947 const char *FullFileNameStart = Blob.data() + Record[0];
4948 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004949 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004950 if (!FullFileName.empty())
4951 File = PP.getFileManager().getFile(FullFileName);
4952
4953 // FIXME: Stable encoding
4954 InclusionDirective::InclusionKind Kind
4955 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4956 InclusionDirective *ID
4957 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004958 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004959 Record[1], Record[3],
4960 File,
4961 Range);
4962 return ID;
4963 }
4964 }
4965
4966 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4967}
4968
4969/// \brief \arg SLocMapI points at a chunk of a module that contains no
4970/// preprocessed entities or the entities it contains are not the ones we are
4971/// looking for. Find the next module that contains entities and return the ID
4972/// of the first entry.
4973PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4974 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4975 ++SLocMapI;
4976 for (GlobalSLocOffsetMapType::const_iterator
4977 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4978 ModuleFile &M = *SLocMapI->second;
4979 if (M.NumPreprocessedEntities)
4980 return M.BasePreprocessedEntityID;
4981 }
4982
4983 return getTotalNumPreprocessedEntities();
4984}
4985
4986namespace {
4987
4988template <unsigned PPEntityOffset::*PPLoc>
4989struct PPEntityComp {
4990 const ASTReader &Reader;
4991 ModuleFile &M;
4992
4993 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4994
4995 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4996 SourceLocation LHS = getLoc(L);
4997 SourceLocation RHS = getLoc(R);
4998 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4999 }
5000
5001 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5002 SourceLocation LHS = getLoc(L);
5003 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5004 }
5005
5006 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5007 SourceLocation RHS = getLoc(R);
5008 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5009 }
5010
5011 SourceLocation getLoc(const PPEntityOffset &PPE) const {
5012 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
5013 }
5014};
5015
5016}
5017
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005018PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5019 bool EndsAfter) const {
5020 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005021 return getTotalNumPreprocessedEntities();
5022
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005023 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5024 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005025 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5026 "Corrupted global sloc offset map");
5027
5028 if (SLocMapI->second->NumPreprocessedEntities == 0)
5029 return findNextPreprocessedEntity(SLocMapI);
5030
5031 ModuleFile &M = *SLocMapI->second;
5032 typedef const PPEntityOffset *pp_iterator;
5033 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5034 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5035
5036 size_t Count = M.NumPreprocessedEntities;
5037 size_t Half;
5038 pp_iterator First = pp_begin;
5039 pp_iterator PPI;
5040
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005041 if (EndsAfter) {
5042 PPI = std::upper_bound(pp_begin, pp_end, Loc,
5043 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
5044 } else {
5045 // Do a binary search manually instead of using std::lower_bound because
5046 // The end locations of entities may be unordered (when a macro expansion
5047 // is inside another macro argument), but for this case it is not important
5048 // whether we get the first macro expansion or its containing macro.
5049 while (Count > 0) {
5050 Half = Count / 2;
5051 PPI = First;
5052 std::advance(PPI, Half);
5053 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
5054 Loc)) {
5055 First = PPI;
5056 ++First;
5057 Count = Count - Half - 1;
5058 } else
5059 Count = Half;
5060 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005061 }
5062
5063 if (PPI == pp_end)
5064 return findNextPreprocessedEntity(SLocMapI);
5065
5066 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5067}
5068
Guy Benyei11169dd2012-12-18 14:30:41 +00005069/// \brief Returns a pair of [Begin, End) indices of preallocated
5070/// preprocessed entities that \arg Range encompasses.
5071std::pair<unsigned, unsigned>
5072 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5073 if (Range.isInvalid())
5074 return std::make_pair(0,0);
5075 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5076
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005077 PreprocessedEntityID BeginID =
5078 findPreprocessedEntity(Range.getBegin(), false);
5079 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005080 return std::make_pair(BeginID, EndID);
5081}
5082
5083/// \brief Optionally returns true or false if the preallocated preprocessed
5084/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005085Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005086 FileID FID) {
5087 if (FID.isInvalid())
5088 return false;
5089
5090 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5091 ModuleFile &M = *PPInfo.first;
5092 unsigned LocalIndex = PPInfo.second;
5093 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5094
5095 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
5096 if (Loc.isInvalid())
5097 return false;
5098
5099 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5100 return true;
5101 else
5102 return false;
5103}
5104
5105namespace {
5106 /// \brief Visitor used to search for information about a header file.
5107 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005108 const FileEntry *FE;
5109
David Blaikie05785d12013-02-20 22:23:23 +00005110 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005111
5112 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005113 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5114 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00005115
5116 static bool visit(ModuleFile &M, void *UserData) {
5117 HeaderFileInfoVisitor *This
5118 = static_cast<HeaderFileInfoVisitor *>(UserData);
5119
Guy Benyei11169dd2012-12-18 14:30:41 +00005120 HeaderFileInfoLookupTable *Table
5121 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5122 if (!Table)
5123 return false;
5124
5125 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00005126 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005127 if (Pos == Table->end())
5128 return false;
5129
5130 This->HFI = *Pos;
5131 return true;
5132 }
5133
David Blaikie05785d12013-02-20 22:23:23 +00005134 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005135 };
5136}
5137
5138HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005139 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005140 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005141 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005142 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005143
5144 return HeaderFileInfo();
5145}
5146
5147void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5148 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005149 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005150 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5151 ModuleFile &F = *(*I);
5152 unsigned Idx = 0;
5153 DiagStates.clear();
5154 assert(!Diag.DiagStates.empty());
5155 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5156 while (Idx < F.PragmaDiagMappings.size()) {
5157 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5158 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5159 if (DiagStateID != 0) {
5160 Diag.DiagStatePoints.push_back(
5161 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5162 FullSourceLoc(Loc, SourceMgr)));
5163 continue;
5164 }
5165
5166 assert(DiagStateID == 0);
5167 // A new DiagState was created here.
5168 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5169 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5170 DiagStates.push_back(NewState);
5171 Diag.DiagStatePoints.push_back(
5172 DiagnosticsEngine::DiagStatePoint(NewState,
5173 FullSourceLoc(Loc, SourceMgr)));
5174 while (1) {
5175 assert(Idx < F.PragmaDiagMappings.size() &&
5176 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5177 if (Idx >= F.PragmaDiagMappings.size()) {
5178 break; // Something is messed up but at least avoid infinite loop in
5179 // release build.
5180 }
5181 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5182 if (DiagID == (unsigned)-1) {
5183 break; // no more diag/map pairs for this location.
5184 }
Alp Tokerc726c362014-06-10 09:31:37 +00005185 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5186 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5187 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005188 }
5189 }
5190 }
5191}
5192
5193/// \brief Get the correct cursor and offset for loading a type.
5194ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5195 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5196 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5197 ModuleFile *M = I->second;
5198 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5199}
5200
5201/// \brief Read and return the type with the given index..
5202///
5203/// The index is the type ID, shifted and minus the number of predefs. This
5204/// routine actually reads the record corresponding to the type at the given
5205/// location. It is a helper routine for GetType, which deals with reading type
5206/// IDs.
5207QualType ASTReader::readTypeRecord(unsigned Index) {
5208 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005209 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005210
5211 // Keep track of where we are in the stream, then jump back there
5212 // after reading this type.
5213 SavedStreamPosition SavedPosition(DeclsCursor);
5214
5215 ReadingKindTracker ReadingKind(Read_Type, *this);
5216
5217 // Note that we are loading a type record.
5218 Deserializing AType(this);
5219
5220 unsigned Idx = 0;
5221 DeclsCursor.JumpToBit(Loc.Offset);
5222 RecordData Record;
5223 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005224 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005225 case TYPE_EXT_QUAL: {
5226 if (Record.size() != 2) {
5227 Error("Incorrect encoding of extended qualifier type");
5228 return QualType();
5229 }
5230 QualType Base = readType(*Loc.F, Record, Idx);
5231 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5232 return Context.getQualifiedType(Base, Quals);
5233 }
5234
5235 case TYPE_COMPLEX: {
5236 if (Record.size() != 1) {
5237 Error("Incorrect encoding of complex type");
5238 return QualType();
5239 }
5240 QualType ElemType = readType(*Loc.F, Record, Idx);
5241 return Context.getComplexType(ElemType);
5242 }
5243
5244 case TYPE_POINTER: {
5245 if (Record.size() != 1) {
5246 Error("Incorrect encoding of pointer type");
5247 return QualType();
5248 }
5249 QualType PointeeType = readType(*Loc.F, Record, Idx);
5250 return Context.getPointerType(PointeeType);
5251 }
5252
Reid Kleckner8a365022013-06-24 17:51:48 +00005253 case TYPE_DECAYED: {
5254 if (Record.size() != 1) {
5255 Error("Incorrect encoding of decayed type");
5256 return QualType();
5257 }
5258 QualType OriginalType = readType(*Loc.F, Record, Idx);
5259 QualType DT = Context.getAdjustedParameterType(OriginalType);
5260 if (!isa<DecayedType>(DT))
5261 Error("Decayed type does not decay");
5262 return DT;
5263 }
5264
Reid Kleckner0503a872013-12-05 01:23:43 +00005265 case TYPE_ADJUSTED: {
5266 if (Record.size() != 2) {
5267 Error("Incorrect encoding of adjusted type");
5268 return QualType();
5269 }
5270 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5271 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5272 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5273 }
5274
Guy Benyei11169dd2012-12-18 14:30:41 +00005275 case TYPE_BLOCK_POINTER: {
5276 if (Record.size() != 1) {
5277 Error("Incorrect encoding of block pointer type");
5278 return QualType();
5279 }
5280 QualType PointeeType = readType(*Loc.F, Record, Idx);
5281 return Context.getBlockPointerType(PointeeType);
5282 }
5283
5284 case TYPE_LVALUE_REFERENCE: {
5285 if (Record.size() != 2) {
5286 Error("Incorrect encoding of lvalue reference type");
5287 return QualType();
5288 }
5289 QualType PointeeType = readType(*Loc.F, Record, Idx);
5290 return Context.getLValueReferenceType(PointeeType, Record[1]);
5291 }
5292
5293 case TYPE_RVALUE_REFERENCE: {
5294 if (Record.size() != 1) {
5295 Error("Incorrect encoding of rvalue reference type");
5296 return QualType();
5297 }
5298 QualType PointeeType = readType(*Loc.F, Record, Idx);
5299 return Context.getRValueReferenceType(PointeeType);
5300 }
5301
5302 case TYPE_MEMBER_POINTER: {
5303 if (Record.size() != 2) {
5304 Error("Incorrect encoding of member pointer type");
5305 return QualType();
5306 }
5307 QualType PointeeType = readType(*Loc.F, Record, Idx);
5308 QualType ClassType = readType(*Loc.F, Record, Idx);
5309 if (PointeeType.isNull() || ClassType.isNull())
5310 return QualType();
5311
5312 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5313 }
5314
5315 case TYPE_CONSTANT_ARRAY: {
5316 QualType ElementType = readType(*Loc.F, Record, Idx);
5317 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5318 unsigned IndexTypeQuals = Record[2];
5319 unsigned Idx = 3;
5320 llvm::APInt Size = ReadAPInt(Record, Idx);
5321 return Context.getConstantArrayType(ElementType, Size,
5322 ASM, IndexTypeQuals);
5323 }
5324
5325 case TYPE_INCOMPLETE_ARRAY: {
5326 QualType ElementType = readType(*Loc.F, Record, Idx);
5327 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5328 unsigned IndexTypeQuals = Record[2];
5329 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5330 }
5331
5332 case TYPE_VARIABLE_ARRAY: {
5333 QualType ElementType = readType(*Loc.F, Record, Idx);
5334 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5335 unsigned IndexTypeQuals = Record[2];
5336 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5337 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5338 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5339 ASM, IndexTypeQuals,
5340 SourceRange(LBLoc, RBLoc));
5341 }
5342
5343 case TYPE_VECTOR: {
5344 if (Record.size() != 3) {
5345 Error("incorrect encoding of vector type in AST file");
5346 return QualType();
5347 }
5348
5349 QualType ElementType = readType(*Loc.F, Record, Idx);
5350 unsigned NumElements = Record[1];
5351 unsigned VecKind = Record[2];
5352 return Context.getVectorType(ElementType, NumElements,
5353 (VectorType::VectorKind)VecKind);
5354 }
5355
5356 case TYPE_EXT_VECTOR: {
5357 if (Record.size() != 3) {
5358 Error("incorrect encoding of extended vector type in AST file");
5359 return QualType();
5360 }
5361
5362 QualType ElementType = readType(*Loc.F, Record, Idx);
5363 unsigned NumElements = Record[1];
5364 return Context.getExtVectorType(ElementType, NumElements);
5365 }
5366
5367 case TYPE_FUNCTION_NO_PROTO: {
5368 if (Record.size() != 6) {
5369 Error("incorrect encoding of no-proto function type");
5370 return QualType();
5371 }
5372 QualType ResultType = readType(*Loc.F, Record, Idx);
5373 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5374 (CallingConv)Record[4], Record[5]);
5375 return Context.getFunctionNoProtoType(ResultType, Info);
5376 }
5377
5378 case TYPE_FUNCTION_PROTO: {
5379 QualType ResultType = readType(*Loc.F, Record, Idx);
5380
5381 FunctionProtoType::ExtProtoInfo EPI;
5382 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5383 /*hasregparm*/ Record[2],
5384 /*regparm*/ Record[3],
5385 static_cast<CallingConv>(Record[4]),
5386 /*produces*/ Record[5]);
5387
5388 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005389
5390 EPI.Variadic = Record[Idx++];
5391 EPI.HasTrailingReturn = Record[Idx++];
5392 EPI.TypeQuals = Record[Idx++];
5393 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005394 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005395 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005396
5397 unsigned NumParams = Record[Idx++];
5398 SmallVector<QualType, 16> ParamTypes;
5399 for (unsigned I = 0; I != NumParams; ++I)
5400 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5401
Jordan Rose5c382722013-03-08 21:51:21 +00005402 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005403 }
5404
5405 case TYPE_UNRESOLVED_USING: {
5406 unsigned Idx = 0;
5407 return Context.getTypeDeclType(
5408 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5409 }
5410
5411 case TYPE_TYPEDEF: {
5412 if (Record.size() != 2) {
5413 Error("incorrect encoding of typedef type");
5414 return QualType();
5415 }
5416 unsigned Idx = 0;
5417 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5418 QualType Canonical = readType(*Loc.F, Record, Idx);
5419 if (!Canonical.isNull())
5420 Canonical = Context.getCanonicalType(Canonical);
5421 return Context.getTypedefType(Decl, Canonical);
5422 }
5423
5424 case TYPE_TYPEOF_EXPR:
5425 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5426
5427 case TYPE_TYPEOF: {
5428 if (Record.size() != 1) {
5429 Error("incorrect encoding of typeof(type) in AST file");
5430 return QualType();
5431 }
5432 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5433 return Context.getTypeOfType(UnderlyingType);
5434 }
5435
5436 case TYPE_DECLTYPE: {
5437 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5438 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5439 }
5440
5441 case TYPE_UNARY_TRANSFORM: {
5442 QualType BaseType = readType(*Loc.F, Record, Idx);
5443 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5444 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5445 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5446 }
5447
Richard Smith74aeef52013-04-26 16:15:35 +00005448 case TYPE_AUTO: {
5449 QualType Deduced = readType(*Loc.F, Record, Idx);
5450 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005451 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005452 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005453 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005454
5455 case TYPE_RECORD: {
5456 if (Record.size() != 2) {
5457 Error("incorrect encoding of record type");
5458 return QualType();
5459 }
5460 unsigned Idx = 0;
5461 bool IsDependent = Record[Idx++];
5462 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5463 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5464 QualType T = Context.getRecordType(RD);
5465 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5466 return T;
5467 }
5468
5469 case TYPE_ENUM: {
5470 if (Record.size() != 2) {
5471 Error("incorrect encoding of enum type");
5472 return QualType();
5473 }
5474 unsigned Idx = 0;
5475 bool IsDependent = Record[Idx++];
5476 QualType T
5477 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5478 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5479 return T;
5480 }
5481
5482 case TYPE_ATTRIBUTED: {
5483 if (Record.size() != 3) {
5484 Error("incorrect encoding of attributed type");
5485 return QualType();
5486 }
5487 QualType modifiedType = readType(*Loc.F, Record, Idx);
5488 QualType equivalentType = readType(*Loc.F, Record, Idx);
5489 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5490 return Context.getAttributedType(kind, modifiedType, equivalentType);
5491 }
5492
5493 case TYPE_PAREN: {
5494 if (Record.size() != 1) {
5495 Error("incorrect encoding of paren type");
5496 return QualType();
5497 }
5498 QualType InnerType = readType(*Loc.F, Record, Idx);
5499 return Context.getParenType(InnerType);
5500 }
5501
5502 case TYPE_PACK_EXPANSION: {
5503 if (Record.size() != 2) {
5504 Error("incorrect encoding of pack expansion type");
5505 return QualType();
5506 }
5507 QualType Pattern = readType(*Loc.F, Record, Idx);
5508 if (Pattern.isNull())
5509 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005510 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005511 if (Record[1])
5512 NumExpansions = Record[1] - 1;
5513 return Context.getPackExpansionType(Pattern, NumExpansions);
5514 }
5515
5516 case TYPE_ELABORATED: {
5517 unsigned Idx = 0;
5518 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5519 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5520 QualType NamedType = readType(*Loc.F, Record, Idx);
5521 return Context.getElaboratedType(Keyword, NNS, NamedType);
5522 }
5523
5524 case TYPE_OBJC_INTERFACE: {
5525 unsigned Idx = 0;
5526 ObjCInterfaceDecl *ItfD
5527 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5528 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5529 }
5530
5531 case TYPE_OBJC_OBJECT: {
5532 unsigned Idx = 0;
5533 QualType Base = readType(*Loc.F, Record, Idx);
5534 unsigned NumProtos = Record[Idx++];
5535 SmallVector<ObjCProtocolDecl*, 4> Protos;
5536 for (unsigned I = 0; I != NumProtos; ++I)
5537 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5538 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5539 }
5540
5541 case TYPE_OBJC_OBJECT_POINTER: {
5542 unsigned Idx = 0;
5543 QualType Pointee = readType(*Loc.F, Record, Idx);
5544 return Context.getObjCObjectPointerType(Pointee);
5545 }
5546
5547 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5548 unsigned Idx = 0;
5549 QualType Parm = readType(*Loc.F, Record, Idx);
5550 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005551 return Context.getSubstTemplateTypeParmType(
5552 cast<TemplateTypeParmType>(Parm),
5553 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005554 }
5555
5556 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5557 unsigned Idx = 0;
5558 QualType Parm = readType(*Loc.F, Record, Idx);
5559 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5560 return Context.getSubstTemplateTypeParmPackType(
5561 cast<TemplateTypeParmType>(Parm),
5562 ArgPack);
5563 }
5564
5565 case TYPE_INJECTED_CLASS_NAME: {
5566 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5567 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5568 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5569 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005570 const Type *T = nullptr;
5571 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5572 if (const Type *Existing = DI->getTypeForDecl()) {
5573 T = Existing;
5574 break;
5575 }
5576 }
5577 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005578 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005579 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5580 DI->setTypeForDecl(T);
5581 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005582 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005583 }
5584
5585 case TYPE_TEMPLATE_TYPE_PARM: {
5586 unsigned Idx = 0;
5587 unsigned Depth = Record[Idx++];
5588 unsigned Index = Record[Idx++];
5589 bool Pack = Record[Idx++];
5590 TemplateTypeParmDecl *D
5591 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5592 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5593 }
5594
5595 case TYPE_DEPENDENT_NAME: {
5596 unsigned Idx = 0;
5597 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5598 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5599 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5600 QualType Canon = readType(*Loc.F, Record, Idx);
5601 if (!Canon.isNull())
5602 Canon = Context.getCanonicalType(Canon);
5603 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5604 }
5605
5606 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5607 unsigned Idx = 0;
5608 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5609 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5610 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5611 unsigned NumArgs = Record[Idx++];
5612 SmallVector<TemplateArgument, 8> Args;
5613 Args.reserve(NumArgs);
5614 while (NumArgs--)
5615 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5616 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5617 Args.size(), Args.data());
5618 }
5619
5620 case TYPE_DEPENDENT_SIZED_ARRAY: {
5621 unsigned Idx = 0;
5622
5623 // ArrayType
5624 QualType ElementType = readType(*Loc.F, Record, Idx);
5625 ArrayType::ArraySizeModifier ASM
5626 = (ArrayType::ArraySizeModifier)Record[Idx++];
5627 unsigned IndexTypeQuals = Record[Idx++];
5628
5629 // DependentSizedArrayType
5630 Expr *NumElts = ReadExpr(*Loc.F);
5631 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5632
5633 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5634 IndexTypeQuals, Brackets);
5635 }
5636
5637 case TYPE_TEMPLATE_SPECIALIZATION: {
5638 unsigned Idx = 0;
5639 bool IsDependent = Record[Idx++];
5640 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5641 SmallVector<TemplateArgument, 8> Args;
5642 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5643 QualType Underlying = readType(*Loc.F, Record, Idx);
5644 QualType T;
5645 if (Underlying.isNull())
5646 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5647 Args.size());
5648 else
5649 T = Context.getTemplateSpecializationType(Name, Args.data(),
5650 Args.size(), Underlying);
5651 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5652 return T;
5653 }
5654
5655 case TYPE_ATOMIC: {
5656 if (Record.size() != 1) {
5657 Error("Incorrect encoding of atomic type");
5658 return QualType();
5659 }
5660 QualType ValueType = readType(*Loc.F, Record, Idx);
5661 return Context.getAtomicType(ValueType);
5662 }
5663 }
5664 llvm_unreachable("Invalid TypeCode!");
5665}
5666
Richard Smith564417a2014-03-20 21:47:22 +00005667void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5668 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005669 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005670 const RecordData &Record, unsigned &Idx) {
5671 ExceptionSpecificationType EST =
5672 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005673 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005674 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005675 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005676 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005677 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005678 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005679 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005680 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005681 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5682 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005683 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005684 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005685 }
5686}
5687
Guy Benyei11169dd2012-12-18 14:30:41 +00005688class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5689 ASTReader &Reader;
5690 ModuleFile &F;
5691 const ASTReader::RecordData &Record;
5692 unsigned &Idx;
5693
5694 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5695 unsigned &I) {
5696 return Reader.ReadSourceLocation(F, R, I);
5697 }
5698
5699 template<typename T>
5700 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5701 return Reader.ReadDeclAs<T>(F, Record, Idx);
5702 }
5703
5704public:
5705 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5706 const ASTReader::RecordData &Record, unsigned &Idx)
5707 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5708 { }
5709
5710 // We want compile-time assurance that we've enumerated all of
5711 // these, so unfortunately we have to declare them first, then
5712 // define them out-of-line.
5713#define ABSTRACT_TYPELOC(CLASS, PARENT)
5714#define TYPELOC(CLASS, PARENT) \
5715 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5716#include "clang/AST/TypeLocNodes.def"
5717
5718 void VisitFunctionTypeLoc(FunctionTypeLoc);
5719 void VisitArrayTypeLoc(ArrayTypeLoc);
5720};
5721
5722void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5723 // nothing to do
5724}
5725void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5726 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5727 if (TL.needsExtraLocalData()) {
5728 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5729 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5730 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5731 TL.setModeAttr(Record[Idx++]);
5732 }
5733}
5734void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5735 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5736}
5737void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5738 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5739}
Reid Kleckner8a365022013-06-24 17:51:48 +00005740void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5741 // nothing to do
5742}
Reid Kleckner0503a872013-12-05 01:23:43 +00005743void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5744 // nothing to do
5745}
Guy Benyei11169dd2012-12-18 14:30:41 +00005746void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5747 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5748}
5749void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5750 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5751}
5752void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5753 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5754}
5755void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5756 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5757 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5758}
5759void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5760 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5761 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5762 if (Record[Idx++])
5763 TL.setSizeExpr(Reader.ReadExpr(F));
5764 else
Craig Toppera13603a2014-05-22 05:54:18 +00005765 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005766}
5767void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5768 VisitArrayTypeLoc(TL);
5769}
5770void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5771 VisitArrayTypeLoc(TL);
5772}
5773void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5774 VisitArrayTypeLoc(TL);
5775}
5776void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5777 DependentSizedArrayTypeLoc TL) {
5778 VisitArrayTypeLoc(TL);
5779}
5780void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5781 DependentSizedExtVectorTypeLoc TL) {
5782 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5783}
5784void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5785 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5786}
5787void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5788 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5789}
5790void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5791 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5792 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5793 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5794 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005795 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5796 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005797 }
5798}
5799void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5800 VisitFunctionTypeLoc(TL);
5801}
5802void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5803 VisitFunctionTypeLoc(TL);
5804}
5805void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5806 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5807}
5808void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5809 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5810}
5811void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5812 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5813 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5814 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5815}
5816void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5817 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5818 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5819 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5820 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5821}
5822void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5823 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5824}
5825void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5826 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5827 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5828 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5829 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5830}
5831void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5832 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5833}
5834void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5835 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5836}
5837void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5838 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5839}
5840void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5841 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5842 if (TL.hasAttrOperand()) {
5843 SourceRange range;
5844 range.setBegin(ReadSourceLocation(Record, Idx));
5845 range.setEnd(ReadSourceLocation(Record, Idx));
5846 TL.setAttrOperandParensRange(range);
5847 }
5848 if (TL.hasAttrExprOperand()) {
5849 if (Record[Idx++])
5850 TL.setAttrExprOperand(Reader.ReadExpr(F));
5851 else
Craig Toppera13603a2014-05-22 05:54:18 +00005852 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005853 } else if (TL.hasAttrEnumOperand())
5854 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5855}
5856void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5857 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5858}
5859void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5860 SubstTemplateTypeParmTypeLoc TL) {
5861 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5862}
5863void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5864 SubstTemplateTypeParmPackTypeLoc TL) {
5865 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5866}
5867void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5868 TemplateSpecializationTypeLoc TL) {
5869 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5870 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5871 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5872 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5873 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5874 TL.setArgLocInfo(i,
5875 Reader.GetTemplateArgumentLocInfo(F,
5876 TL.getTypePtr()->getArg(i).getKind(),
5877 Record, Idx));
5878}
5879void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5880 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5881 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5882}
5883void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5884 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5885 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5886}
5887void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5888 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5889}
5890void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5891 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5892 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5893 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5894}
5895void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5896 DependentTemplateSpecializationTypeLoc TL) {
5897 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5898 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5899 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5900 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5901 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5902 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5903 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5904 TL.setArgLocInfo(I,
5905 Reader.GetTemplateArgumentLocInfo(F,
5906 TL.getTypePtr()->getArg(I).getKind(),
5907 Record, Idx));
5908}
5909void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5910 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5911}
5912void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5913 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5914}
5915void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5916 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5917 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5918 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5919 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5920 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5921}
5922void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5923 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5924}
5925void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5926 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5927 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5928 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5929}
5930
5931TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5932 const RecordData &Record,
5933 unsigned &Idx) {
5934 QualType InfoTy = readType(F, Record, Idx);
5935 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005936 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005937
5938 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5939 TypeLocReader TLR(*this, F, Record, Idx);
5940 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5941 TLR.Visit(TL);
5942 return TInfo;
5943}
5944
5945QualType ASTReader::GetType(TypeID ID) {
5946 unsigned FastQuals = ID & Qualifiers::FastMask;
5947 unsigned Index = ID >> Qualifiers::FastWidth;
5948
5949 if (Index < NUM_PREDEF_TYPE_IDS) {
5950 QualType T;
5951 switch ((PredefinedTypeIDs)Index) {
5952 case PREDEF_TYPE_NULL_ID: return QualType();
5953 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5954 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5955
5956 case PREDEF_TYPE_CHAR_U_ID:
5957 case PREDEF_TYPE_CHAR_S_ID:
5958 // FIXME: Check that the signedness of CharTy is correct!
5959 T = Context.CharTy;
5960 break;
5961
5962 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5963 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5964 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5965 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5966 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5967 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5968 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5969 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5970 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5971 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5972 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5973 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5974 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5975 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5976 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5977 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5978 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5979 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5980 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5981 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5982 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5983 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5984 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5985 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5986 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5987 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5988 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5989 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005990 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5991 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5992 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5993 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5994 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5995 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005996 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005997 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005998 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5999
6000 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6001 T = Context.getAutoRRefDeductType();
6002 break;
6003
6004 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6005 T = Context.ARCUnbridgedCastTy;
6006 break;
6007
6008 case PREDEF_TYPE_VA_LIST_TAG:
6009 T = Context.getVaListTagType();
6010 break;
6011
6012 case PREDEF_TYPE_BUILTIN_FN:
6013 T = Context.BuiltinFnTy;
6014 break;
6015 }
6016
6017 assert(!T.isNull() && "Unknown predefined type");
6018 return T.withFastQualifiers(FastQuals);
6019 }
6020
6021 Index -= NUM_PREDEF_TYPE_IDS;
6022 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6023 if (TypesLoaded[Index].isNull()) {
6024 TypesLoaded[Index] = readTypeRecord(Index);
6025 if (TypesLoaded[Index].isNull())
6026 return QualType();
6027
6028 TypesLoaded[Index]->setFromAST();
6029 if (DeserializationListener)
6030 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6031 TypesLoaded[Index]);
6032 }
6033
6034 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6035}
6036
6037QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6038 return GetType(getGlobalTypeID(F, LocalID));
6039}
6040
6041serialization::TypeID
6042ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6043 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6044 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6045
6046 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6047 return LocalID;
6048
6049 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6050 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6051 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6052
6053 unsigned GlobalIndex = LocalIndex + I->second;
6054 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6055}
6056
6057TemplateArgumentLocInfo
6058ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6059 TemplateArgument::ArgKind Kind,
6060 const RecordData &Record,
6061 unsigned &Index) {
6062 switch (Kind) {
6063 case TemplateArgument::Expression:
6064 return ReadExpr(F);
6065 case TemplateArgument::Type:
6066 return GetTypeSourceInfo(F, Record, Index);
6067 case TemplateArgument::Template: {
6068 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6069 Index);
6070 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6071 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6072 SourceLocation());
6073 }
6074 case TemplateArgument::TemplateExpansion: {
6075 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6076 Index);
6077 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6078 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6079 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6080 EllipsisLoc);
6081 }
6082 case TemplateArgument::Null:
6083 case TemplateArgument::Integral:
6084 case TemplateArgument::Declaration:
6085 case TemplateArgument::NullPtr:
6086 case TemplateArgument::Pack:
6087 // FIXME: Is this right?
6088 return TemplateArgumentLocInfo();
6089 }
6090 llvm_unreachable("unexpected template argument loc");
6091}
6092
6093TemplateArgumentLoc
6094ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6095 const RecordData &Record, unsigned &Index) {
6096 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6097
6098 if (Arg.getKind() == TemplateArgument::Expression) {
6099 if (Record[Index++]) // bool InfoHasSameExpr.
6100 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6101 }
6102 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6103 Record, Index));
6104}
6105
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006106const ASTTemplateArgumentListInfo*
6107ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6108 const RecordData &Record,
6109 unsigned &Index) {
6110 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6111 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6112 unsigned NumArgsAsWritten = Record[Index++];
6113 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6114 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6115 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6116 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6117}
6118
Guy Benyei11169dd2012-12-18 14:30:41 +00006119Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6120 return GetDecl(ID);
6121}
6122
Richard Smith50895422015-01-31 03:04:55 +00006123template<typename TemplateSpecializationDecl>
6124static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6125 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6126 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6127}
6128
Richard Smith053f6c62014-05-16 23:01:30 +00006129void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006130 if (NumCurrentElementsDeserializing) {
6131 // We arrange to not care about the complete redeclaration chain while we're
6132 // deserializing. Just remember that the AST has marked this one as complete
6133 // but that it's not actually complete yet, so we know we still need to
6134 // complete it later.
6135 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6136 return;
6137 }
6138
Richard Smith053f6c62014-05-16 23:01:30 +00006139 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6140
Richard Smith053f6c62014-05-16 23:01:30 +00006141 // If this is a named declaration, complete it by looking it up
6142 // within its context.
6143 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006144 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006145 // all mergeable entities within it.
6146 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6147 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6148 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
6149 auto *II = Name.getAsIdentifierInfo();
6150 if (isa<TranslationUnitDecl>(DC) && II) {
6151 // Outside of C++, we don't have a lookup table for the TU, so update
6152 // the identifier instead. In C++, either way should work fine.
6153 if (II->isOutOfDate())
6154 updateOutOfDateIdentifier(*II);
6155 } else
6156 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006157 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
6158 // FIXME: It'd be nice to do something a bit more targeted here.
6159 D->getDeclContext()->decls_begin();
Richard Smith053f6c62014-05-16 23:01:30 +00006160 }
6161 }
Richard Smith50895422015-01-31 03:04:55 +00006162
6163 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6164 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6165 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6166 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6167 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6168 if (auto *Template = FD->getPrimaryTemplate())
6169 Template->LoadLazySpecializations();
6170 }
Richard Smith053f6c62014-05-16 23:01:30 +00006171}
6172
Richard Smithcd45dbc2014-04-19 03:48:30 +00006173uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6174 const RecordData &Record,
6175 unsigned &Idx) {
6176 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6177 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006178 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006179 }
6180
Guy Benyei11169dd2012-12-18 14:30:41 +00006181 unsigned LocalID = Record[Idx++];
6182 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6183}
6184
6185CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6186 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006187 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006188 SavedStreamPosition SavedPosition(Cursor);
6189 Cursor.JumpToBit(Loc.Offset);
6190 ReadingKindTracker ReadingKind(Read_Decl, *this);
6191 RecordData Record;
6192 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006193 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006194 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006195 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006196 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006197 }
6198
6199 unsigned Idx = 0;
6200 unsigned NumBases = Record[Idx++];
6201 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6202 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6203 for (unsigned I = 0; I != NumBases; ++I)
6204 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6205 return Bases;
6206}
6207
6208serialization::DeclID
6209ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6210 if (LocalID < NUM_PREDEF_DECL_IDS)
6211 return LocalID;
6212
6213 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6214 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6215 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6216
6217 return LocalID + I->second;
6218}
6219
6220bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6221 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006222 // Predefined decls aren't from any module.
6223 if (ID < NUM_PREDEF_DECL_IDS)
6224 return false;
6225
Guy Benyei11169dd2012-12-18 14:30:41 +00006226 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6227 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6228 return &M == I->second;
6229}
6230
Douglas Gregor9f782892013-01-21 15:25:38 +00006231ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006232 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006233 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006234 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6235 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6236 return I->second;
6237}
6238
6239SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6240 if (ID < NUM_PREDEF_DECL_IDS)
6241 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006242
Guy Benyei11169dd2012-12-18 14:30:41 +00006243 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6244
6245 if (Index > DeclsLoaded.size()) {
6246 Error("declaration ID out-of-range for AST file");
6247 return SourceLocation();
6248 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006249
Guy Benyei11169dd2012-12-18 14:30:41 +00006250 if (Decl *D = DeclsLoaded[Index])
6251 return D->getLocation();
6252
6253 unsigned RawLocation = 0;
6254 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6255 return ReadSourceLocation(*Rec.F, RawLocation);
6256}
6257
Richard Smithfe620d22015-03-05 23:24:12 +00006258static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6259 switch (ID) {
6260 case PREDEF_DECL_NULL_ID:
6261 return nullptr;
6262
6263 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6264 return Context.getTranslationUnitDecl();
6265
6266 case PREDEF_DECL_OBJC_ID_ID:
6267 return Context.getObjCIdDecl();
6268
6269 case PREDEF_DECL_OBJC_SEL_ID:
6270 return Context.getObjCSelDecl();
6271
6272 case PREDEF_DECL_OBJC_CLASS_ID:
6273 return Context.getObjCClassDecl();
6274
6275 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6276 return Context.getObjCProtocolDecl();
6277
6278 case PREDEF_DECL_INT_128_ID:
6279 return Context.getInt128Decl();
6280
6281 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6282 return Context.getUInt128Decl();
6283
6284 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6285 return Context.getObjCInstanceTypeDecl();
6286
6287 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6288 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006289
6290 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6291 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006292 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006293 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006294}
6295
Richard Smithcd45dbc2014-04-19 03:48:30 +00006296Decl *ASTReader::GetExistingDecl(DeclID ID) {
6297 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006298 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6299 if (D) {
6300 // Track that we have merged the declaration with ID \p ID into the
6301 // pre-existing predefined declaration \p D.
6302 auto &Merged = MergedDecls[D->getCanonicalDecl()];
6303 if (Merged.empty())
6304 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006305 }
Richard Smithfe620d22015-03-05 23:24:12 +00006306 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006307 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006308
Guy Benyei11169dd2012-12-18 14:30:41 +00006309 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6310
6311 if (Index >= DeclsLoaded.size()) {
6312 assert(0 && "declaration ID out-of-range for AST file");
6313 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006314 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006315 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006316
6317 return DeclsLoaded[Index];
6318}
6319
6320Decl *ASTReader::GetDecl(DeclID ID) {
6321 if (ID < NUM_PREDEF_DECL_IDS)
6322 return GetExistingDecl(ID);
6323
6324 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6325
6326 if (Index >= DeclsLoaded.size()) {
6327 assert(0 && "declaration ID out-of-range for AST file");
6328 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006329 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006330 }
6331
Guy Benyei11169dd2012-12-18 14:30:41 +00006332 if (!DeclsLoaded[Index]) {
6333 ReadDeclRecord(ID);
6334 if (DeserializationListener)
6335 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6336 }
6337
6338 return DeclsLoaded[Index];
6339}
6340
6341DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6342 DeclID GlobalID) {
6343 if (GlobalID < NUM_PREDEF_DECL_IDS)
6344 return GlobalID;
6345
6346 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6347 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6348 ModuleFile *Owner = I->second;
6349
6350 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6351 = M.GlobalToLocalDeclIDs.find(Owner);
6352 if (Pos == M.GlobalToLocalDeclIDs.end())
6353 return 0;
6354
6355 return GlobalID - Owner->BaseDeclID + Pos->second;
6356}
6357
6358serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6359 const RecordData &Record,
6360 unsigned &Idx) {
6361 if (Idx >= Record.size()) {
6362 Error("Corrupted AST file");
6363 return 0;
6364 }
6365
6366 return getGlobalDeclID(F, Record[Idx++]);
6367}
6368
6369/// \brief Resolve the offset of a statement into a statement.
6370///
6371/// This operation will read a new statement from the external
6372/// source each time it is called, and is meant to be used via a
6373/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6374Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6375 // Switch case IDs are per Decl.
6376 ClearSwitchCaseIDs();
6377
6378 // Offset here is a global offset across the entire chain.
6379 RecordLocation Loc = getLocalBitOffset(Offset);
6380 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6381 return ReadStmtFromStream(*Loc.F);
6382}
6383
6384namespace {
6385 class FindExternalLexicalDeclsVisitor {
6386 ASTReader &Reader;
6387 const DeclContext *DC;
6388 bool (*isKindWeWant)(Decl::Kind);
6389
6390 SmallVectorImpl<Decl*> &Decls;
6391 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6392
6393 public:
6394 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6395 bool (*isKindWeWant)(Decl::Kind),
6396 SmallVectorImpl<Decl*> &Decls)
6397 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6398 {
6399 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6400 PredefsVisited[I] = false;
6401 }
6402
6403 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6404 if (Preorder)
6405 return false;
6406
6407 FindExternalLexicalDeclsVisitor *This
6408 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6409
6410 ModuleFile::DeclContextInfosMap::iterator Info
6411 = M.DeclContextInfos.find(This->DC);
6412 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6413 return false;
6414
6415 // Load all of the declaration IDs
6416 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6417 *IDE = ID + Info->second.NumLexicalDecls;
6418 ID != IDE; ++ID) {
6419 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6420 continue;
6421
6422 // Don't add predefined declarations to the lexical context more
6423 // than once.
6424 if (ID->second < NUM_PREDEF_DECL_IDS) {
6425 if (This->PredefsVisited[ID->second])
6426 continue;
6427
6428 This->PredefsVisited[ID->second] = true;
6429 }
6430
6431 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6432 if (!This->DC->isDeclInLexicalTraversal(D))
6433 This->Decls.push_back(D);
6434 }
6435 }
6436
6437 return false;
6438 }
6439 };
6440}
6441
6442ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6443 bool (*isKindWeWant)(Decl::Kind),
6444 SmallVectorImpl<Decl*> &Decls) {
6445 // There might be lexical decls in multiple modules, for the TU at
6446 // least. Walk all of the modules in the order they were loaded.
6447 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6448 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6449 ++NumLexicalDeclContextsRead;
6450 return ELR_Success;
6451}
6452
6453namespace {
6454
6455class DeclIDComp {
6456 ASTReader &Reader;
6457 ModuleFile &Mod;
6458
6459public:
6460 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6461
6462 bool operator()(LocalDeclID L, LocalDeclID R) const {
6463 SourceLocation LHS = getLocation(L);
6464 SourceLocation RHS = getLocation(R);
6465 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6466 }
6467
6468 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6469 SourceLocation RHS = getLocation(R);
6470 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6471 }
6472
6473 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6474 SourceLocation LHS = getLocation(L);
6475 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6476 }
6477
6478 SourceLocation getLocation(LocalDeclID ID) const {
6479 return Reader.getSourceManager().getFileLoc(
6480 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6481 }
6482};
6483
6484}
6485
6486void ASTReader::FindFileRegionDecls(FileID File,
6487 unsigned Offset, unsigned Length,
6488 SmallVectorImpl<Decl *> &Decls) {
6489 SourceManager &SM = getSourceManager();
6490
6491 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6492 if (I == FileDeclIDs.end())
6493 return;
6494
6495 FileDeclsInfo &DInfo = I->second;
6496 if (DInfo.Decls.empty())
6497 return;
6498
6499 SourceLocation
6500 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6501 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6502
6503 DeclIDComp DIDComp(*this, *DInfo.Mod);
6504 ArrayRef<serialization::LocalDeclID>::iterator
6505 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6506 BeginLoc, DIDComp);
6507 if (BeginIt != DInfo.Decls.begin())
6508 --BeginIt;
6509
6510 // If we are pointing at a top-level decl inside an objc container, we need
6511 // to backtrack until we find it otherwise we will fail to report that the
6512 // region overlaps with an objc container.
6513 while (BeginIt != DInfo.Decls.begin() &&
6514 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6515 ->isTopLevelDeclInObjCContainer())
6516 --BeginIt;
6517
6518 ArrayRef<serialization::LocalDeclID>::iterator
6519 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6520 EndLoc, DIDComp);
6521 if (EndIt != DInfo.Decls.end())
6522 ++EndIt;
6523
6524 for (ArrayRef<serialization::LocalDeclID>::iterator
6525 DIt = BeginIt; DIt != EndIt; ++DIt)
6526 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6527}
6528
6529namespace {
6530 /// \brief ModuleFile visitor used to perform name lookup into a
6531 /// declaration context.
6532 class DeclContextNameLookupVisitor {
6533 ASTReader &Reader;
Richard Smith8c913ec2014-08-14 02:21:01 +00006534 ArrayRef<const DeclContext *> Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006535 DeclarationName Name;
6536 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006537 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006538
6539 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006540 DeclContextNameLookupVisitor(ASTReader &Reader,
6541 ArrayRef<const DeclContext *> Contexts,
Guy Benyei11169dd2012-12-18 14:30:41 +00006542 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006543 SmallVectorImpl<NamedDecl *> &Decls,
6544 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
6545 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls),
6546 DeclSet(DeclSet) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006547
6548 static bool visit(ModuleFile &M, void *UserData) {
6549 DeclContextNameLookupVisitor *This
6550 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6551
6552 // Check whether we have any visible declaration information for
6553 // this context in this module.
6554 ModuleFile::DeclContextInfosMap::iterator Info;
6555 bool FoundInfo = false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006556 for (auto *DC : This->Contexts) {
6557 Info = M.DeclContextInfos.find(DC);
6558 if (Info != M.DeclContextInfos.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006559 Info->second.NameLookupTableData) {
6560 FoundInfo = true;
6561 break;
6562 }
6563 }
6564
6565 if (!FoundInfo)
6566 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006567
Guy Benyei11169dd2012-12-18 14:30:41 +00006568 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006569 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006570 Info->second.NameLookupTableData;
6571 ASTDeclContextNameLookupTable::iterator Pos
6572 = LookupTable->find(This->Name);
6573 if (Pos == LookupTable->end())
6574 return false;
6575
6576 bool FoundAnything = false;
6577 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6578 for (; Data.first != Data.second; ++Data.first) {
6579 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6580 if (!ND)
6581 continue;
6582
6583 if (ND->getDeclName() != This->Name) {
6584 // A name might be null because the decl's redeclarable part is
6585 // currently read before reading its name. The lookup is triggered by
6586 // building that decl (likely indirectly), and so it is later in the
6587 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006588 // FIXME: This should not happen; deserializing declarations should
6589 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006590 continue;
6591 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006592
Guy Benyei11169dd2012-12-18 14:30:41 +00006593 // Record this declaration.
6594 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006595 if (This->DeclSet.insert(ND).second)
6596 This->Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006597 }
6598
6599 return FoundAnything;
6600 }
6601 };
6602}
6603
Douglas Gregor9f782892013-01-21 15:25:38 +00006604/// \brief Retrieve the "definitive" module file for the definition of the
6605/// given declaration context, if there is one.
6606///
6607/// The "definitive" module file is the only place where we need to look to
6608/// find information about the declarations within the given declaration
6609/// context. For example, C++ and Objective-C classes, C structs/unions, and
6610/// Objective-C protocols, categories, and extensions are all defined in a
6611/// single place in the source code, so they have definitive module files
6612/// associated with them. C++ namespaces, on the other hand, can have
6613/// definitions in multiple different module files.
6614///
6615/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6616/// NDEBUG checking.
6617static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6618 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006619 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6620 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006621
Craig Toppera13603a2014-05-22 05:54:18 +00006622 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006623}
6624
Richard Smith9ce12e32013-02-07 03:30:24 +00006625bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006626ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6627 DeclarationName Name) {
6628 assert(DC->hasExternalVisibleStorage() &&
6629 "DeclContext has no visible decls in storage");
6630 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006631 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006632
Richard Smith8c913ec2014-08-14 02:21:01 +00006633 Deserializing LookupResults(this);
6634
Guy Benyei11169dd2012-12-18 14:30:41 +00006635 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006636 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006637
Guy Benyei11169dd2012-12-18 14:30:41 +00006638 // Compute the declaration contexts we need to look into. Multiple such
6639 // declaration contexts occur when two declaration contexts from disjoint
6640 // modules get merged, e.g., when two namespaces with the same name are
6641 // independently defined in separate modules.
6642 SmallVector<const DeclContext *, 2> Contexts;
6643 Contexts.push_back(DC);
Richard Smith8c913ec2014-08-14 02:21:01 +00006644
Guy Benyei11169dd2012-12-18 14:30:41 +00006645 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006646 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006647 if (Merged != MergedDecls.end()) {
6648 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6649 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6650 }
6651 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006652
6653 auto LookUpInContexts = [&](ArrayRef<const DeclContext*> Contexts) {
Richard Smith52874ec2015-02-13 20:17:14 +00006654 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls, DeclSet);
Richard Smith8c913ec2014-08-14 02:21:01 +00006655
6656 // If we can definitively determine which module file to look into,
6657 // only look there. Otherwise, look in all module files.
6658 ModuleFile *Definitive;
6659 if (Contexts.size() == 1 &&
6660 (Definitive = getDefinitiveModuleFileFor(Contexts[0], *this))) {
6661 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6662 } else {
6663 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6664 }
6665 };
6666
6667 LookUpInContexts(Contexts);
6668
6669 // If this might be an implicit special member function, then also search
6670 // all merged definitions of the surrounding class. We need to search them
6671 // individually, because finding an entity in one of them doesn't imply that
6672 // we can't find a different entity in another one.
Richard Smithcd45dbc2014-04-19 03:48:30 +00006673 if (isa<CXXRecordDecl>(DC)) {
Richard Smith8c913ec2014-08-14 02:21:01 +00006674 auto Kind = Name.getNameKind();
6675 if (Kind == DeclarationName::CXXConstructorName ||
6676 Kind == DeclarationName::CXXDestructorName ||
6677 (Kind == DeclarationName::CXXOperatorName &&
6678 Name.getCXXOverloadedOperator() == OO_Equal)) {
6679 auto Merged = MergedLookups.find(DC);
Richard Smithe0612472014-11-21 05:16:13 +00006680 if (Merged != MergedLookups.end()) {
6681 for (unsigned I = 0; I != Merged->second.size(); ++I) {
Daniel Jasperc0b7c802015-02-18 14:13:46 +00006682 const DeclContext *Context = Merged->second[I];
6683 LookUpInContexts(Context);
Richard Smithe0612472014-11-21 05:16:13 +00006684 // We might have just added some more merged lookups. If so, our
6685 // iterator is now invalid, so grab a fresh one before continuing.
6686 Merged = MergedLookups.find(DC);
6687 }
6688 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006689 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006690 }
6691
Guy Benyei11169dd2012-12-18 14:30:41 +00006692 ++NumVisibleDeclContextsRead;
6693 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006694 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006695}
6696
6697namespace {
6698 /// \brief ModuleFile visitor used to retrieve all visible names in a
6699 /// declaration context.
6700 class DeclContextAllNamesVisitor {
6701 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006702 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006703 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006704 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006705 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006706
6707 public:
6708 DeclContextAllNamesVisitor(ASTReader &Reader,
6709 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006710 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006711 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006712
6713 static bool visit(ModuleFile &M, void *UserData) {
6714 DeclContextAllNamesVisitor *This
6715 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6716
6717 // Check whether we have any visible declaration information for
6718 // this context in this module.
6719 ModuleFile::DeclContextInfosMap::iterator Info;
6720 bool FoundInfo = false;
6721 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6722 Info = M.DeclContextInfos.find(This->Contexts[I]);
6723 if (Info != M.DeclContextInfos.end() &&
6724 Info->second.NameLookupTableData) {
6725 FoundInfo = true;
6726 break;
6727 }
6728 }
6729
6730 if (!FoundInfo)
6731 return false;
6732
Richard Smith52e3fba2014-03-11 07:17:35 +00006733 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006734 Info->second.NameLookupTableData;
6735 bool FoundAnything = false;
6736 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006737 I = LookupTable->data_begin(), E = LookupTable->data_end();
6738 I != E;
6739 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006740 ASTDeclContextNameLookupTrait::data_type Data = *I;
6741 for (; Data.first != Data.second; ++Data.first) {
6742 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6743 *Data.first);
6744 if (!ND)
6745 continue;
6746
6747 // Record this declaration.
6748 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006749 if (This->DeclSet.insert(ND).second)
6750 This->Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006751 }
6752 }
6753
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006754 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006755 }
6756 };
6757}
6758
6759void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6760 if (!DC->hasExternalVisibleStorage())
6761 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006762 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006763
6764 // Compute the declaration contexts we need to look into. Multiple such
6765 // declaration contexts occur when two declaration contexts from disjoint
6766 // modules get merged, e.g., when two namespaces with the same name are
6767 // independently defined in separate modules.
6768 SmallVector<const DeclContext *, 2> Contexts;
6769 Contexts.push_back(DC);
6770
6771 if (DC->isNamespace()) {
6772 MergedDeclsMap::iterator Merged
6773 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6774 if (Merged != MergedDecls.end()) {
6775 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6776 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6777 }
6778 }
6779
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006780 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6781 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006782 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6783 ++NumVisibleDeclContextsRead;
6784
Craig Topper79be4cd2013-07-05 04:33:53 +00006785 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006786 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6787 }
6788 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6789}
6790
6791/// \brief Under non-PCH compilation the consumer receives the objc methods
6792/// before receiving the implementation, and codegen depends on this.
6793/// We simulate this by deserializing and passing to consumer the methods of the
6794/// implementation before passing the deserialized implementation decl.
6795static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6796 ASTConsumer *Consumer) {
6797 assert(ImplD && Consumer);
6798
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006799 for (auto *I : ImplD->methods())
6800 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006801
6802 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6803}
6804
6805void ASTReader::PassInterestingDeclsToConsumer() {
6806 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006807
6808 if (PassingDeclsToConsumer)
6809 return;
6810
6811 // Guard variable to avoid recursively redoing the process of passing
6812 // decls to consumer.
6813 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6814 true);
6815
Guy Benyei11169dd2012-12-18 14:30:41 +00006816 while (!InterestingDecls.empty()) {
6817 Decl *D = InterestingDecls.front();
6818 InterestingDecls.pop_front();
6819
6820 PassInterestingDeclToConsumer(D);
6821 }
6822}
6823
6824void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6825 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6826 PassObjCImplDeclToConsumer(ImplD, Consumer);
6827 else
6828 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6829}
6830
6831void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6832 this->Consumer = Consumer;
6833
6834 if (!Consumer)
6835 return;
6836
Ben Langmuir332aafe2014-01-31 01:06:56 +00006837 for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006838 // Force deserialization of this decl, which will cause it to be queued for
6839 // passing to the consumer.
Ben Langmuir332aafe2014-01-31 01:06:56 +00006840 GetDecl(EagerlyDeserializedDecls[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006841 }
Ben Langmuir332aafe2014-01-31 01:06:56 +00006842 EagerlyDeserializedDecls.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006843
6844 PassInterestingDeclsToConsumer();
6845}
6846
6847void ASTReader::PrintStats() {
6848 std::fprintf(stderr, "*** AST File Statistics:\n");
6849
6850 unsigned NumTypesLoaded
6851 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6852 QualType());
6853 unsigned NumDeclsLoaded
6854 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006855 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006856 unsigned NumIdentifiersLoaded
6857 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6858 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006859 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006860 unsigned NumMacrosLoaded
6861 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6862 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006863 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006864 unsigned NumSelectorsLoaded
6865 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6866 SelectorsLoaded.end(),
6867 Selector());
6868
6869 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6870 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6871 NumSLocEntriesRead, TotalNumSLocEntries,
6872 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6873 if (!TypesLoaded.empty())
6874 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6875 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6876 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6877 if (!DeclsLoaded.empty())
6878 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6879 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6880 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6881 if (!IdentifiersLoaded.empty())
6882 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6883 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6884 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6885 if (!MacrosLoaded.empty())
6886 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6887 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6888 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6889 if (!SelectorsLoaded.empty())
6890 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6891 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6892 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6893 if (TotalNumStatements)
6894 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6895 NumStatementsRead, TotalNumStatements,
6896 ((float)NumStatementsRead/TotalNumStatements * 100));
6897 if (TotalNumMacros)
6898 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6899 NumMacrosRead, TotalNumMacros,
6900 ((float)NumMacrosRead/TotalNumMacros * 100));
6901 if (TotalLexicalDeclContexts)
6902 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6903 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6904 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6905 * 100));
6906 if (TotalVisibleDeclContexts)
6907 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6908 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6909 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6910 * 100));
6911 if (TotalNumMethodPoolEntries) {
6912 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6913 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6914 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6915 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006916 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006917 if (NumMethodPoolLookups) {
6918 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6919 NumMethodPoolHits, NumMethodPoolLookups,
6920 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6921 }
6922 if (NumMethodPoolTableLookups) {
6923 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6924 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6925 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6926 * 100.0));
6927 }
6928
Douglas Gregor00a50f72013-01-25 00:38:33 +00006929 if (NumIdentifierLookupHits) {
6930 std::fprintf(stderr,
6931 " %u / %u identifier table lookups succeeded (%f%%)\n",
6932 NumIdentifierLookupHits, NumIdentifierLookups,
6933 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6934 }
6935
Douglas Gregore060e572013-01-25 01:03:03 +00006936 if (GlobalIndex) {
6937 std::fprintf(stderr, "\n");
6938 GlobalIndex->printStats();
6939 }
6940
Guy Benyei11169dd2012-12-18 14:30:41 +00006941 std::fprintf(stderr, "\n");
6942 dump();
6943 std::fprintf(stderr, "\n");
6944}
6945
6946template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6947static void
6948dumpModuleIDMap(StringRef Name,
6949 const ContinuousRangeMap<Key, ModuleFile *,
6950 InitialCapacity> &Map) {
6951 if (Map.begin() == Map.end())
6952 return;
6953
6954 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6955 llvm::errs() << Name << ":\n";
6956 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6957 I != IEnd; ++I) {
6958 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6959 << "\n";
6960 }
6961}
6962
6963void ASTReader::dump() {
6964 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6965 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6966 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6967 dumpModuleIDMap("Global type map", GlobalTypeMap);
6968 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6969 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6970 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6971 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6972 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6973 dumpModuleIDMap("Global preprocessed entity map",
6974 GlobalPreprocessedEntityMap);
6975
6976 llvm::errs() << "\n*** PCH/Modules Loaded:";
6977 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6978 MEnd = ModuleMgr.end();
6979 M != MEnd; ++M)
6980 (*M)->dump();
6981}
6982
6983/// Return the amount of memory used by memory buffers, breaking down
6984/// by heap-backed versus mmap'ed memory.
6985void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6986 for (ModuleConstIterator I = ModuleMgr.begin(),
6987 E = ModuleMgr.end(); I != E; ++I) {
6988 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6989 size_t bytes = buf->getBufferSize();
6990 switch (buf->getBufferKind()) {
6991 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6992 sizes.malloc_bytes += bytes;
6993 break;
6994 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6995 sizes.mmap_bytes += bytes;
6996 break;
6997 }
6998 }
6999 }
7000}
7001
7002void ASTReader::InitializeSema(Sema &S) {
7003 SemaObj = &S;
7004 S.addExternalSource(this);
7005
7006 // Makes sure any declarations that were deserialized "too early"
7007 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00007008 for (uint64_t ID : PreloadedDeclIDs) {
7009 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7010 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007011 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007012 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007013
Richard Smith3d8e97e2013-10-18 06:54:39 +00007014 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007015 if (!FPPragmaOptions.empty()) {
7016 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7017 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
7018 }
7019
Richard Smith3d8e97e2013-10-18 06:54:39 +00007020 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007021 if (!OpenCLExtensions.empty()) {
7022 unsigned I = 0;
7023#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
7024#include "clang/Basic/OpenCLExtensions.def"
7025
7026 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
7027 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00007028
7029 UpdateSema();
7030}
7031
7032void ASTReader::UpdateSema() {
7033 assert(SemaObj && "no Sema to update");
7034
7035 // Load the offsets of the declarations that Sema references.
7036 // They will be lazily deserialized when needed.
7037 if (!SemaDeclRefs.empty()) {
7038 assert(SemaDeclRefs.size() % 2 == 0);
7039 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
7040 if (!SemaObj->StdNamespace)
7041 SemaObj->StdNamespace = SemaDeclRefs[I];
7042 if (!SemaObj->StdBadAlloc)
7043 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
7044 }
7045 SemaDeclRefs.clear();
7046 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007047
7048 // Update the state of 'pragma clang optimize'. Use the same API as if we had
7049 // encountered the pragma in the source.
7050 if(OptimizeOffPragmaLocation.isValid())
7051 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00007052}
7053
7054IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
7055 // Note that we are loading an identifier.
7056 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007057 StringRef Name(NameStart, NameEnd - NameStart);
7058
7059 // If there is a global index, look there first to determine which modules
7060 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00007061 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00007062 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00007063 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00007064 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7065 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00007066 }
7067 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00007068 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007069 NumIdentifierLookups,
7070 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00007071 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007072 IdentifierInfo *II = Visitor.getIdentifierInfo();
7073 markIdentifierUpToDate(II);
7074 return II;
7075}
7076
7077namespace clang {
7078 /// \brief An identifier-lookup iterator that enumerates all of the
7079 /// identifiers stored within a set of AST files.
7080 class ASTIdentifierIterator : public IdentifierIterator {
7081 /// \brief The AST reader whose identifiers are being enumerated.
7082 const ASTReader &Reader;
7083
7084 /// \brief The current index into the chain of AST files stored in
7085 /// the AST reader.
7086 unsigned Index;
7087
7088 /// \brief The current position within the identifier lookup table
7089 /// of the current AST file.
7090 ASTIdentifierLookupTable::key_iterator Current;
7091
7092 /// \brief The end position within the identifier lookup table of
7093 /// the current AST file.
7094 ASTIdentifierLookupTable::key_iterator End;
7095
7096 public:
7097 explicit ASTIdentifierIterator(const ASTReader &Reader);
7098
Craig Topper3e89dfe2014-03-13 02:13:41 +00007099 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007100 };
7101}
7102
7103ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
7104 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
7105 ASTIdentifierLookupTable *IdTable
7106 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
7107 Current = IdTable->key_begin();
7108 End = IdTable->key_end();
7109}
7110
7111StringRef ASTIdentifierIterator::Next() {
7112 while (Current == End) {
7113 // If we have exhausted all of our AST files, we're done.
7114 if (Index == 0)
7115 return StringRef();
7116
7117 --Index;
7118 ASTIdentifierLookupTable *IdTable
7119 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
7120 IdentifierLookupTable;
7121 Current = IdTable->key_begin();
7122 End = IdTable->key_end();
7123 }
7124
7125 // We have any identifiers remaining in the current AST file; return
7126 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007127 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007128 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007129 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007130}
7131
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007132IdentifierIterator *ASTReader::getIdentifiers() {
7133 if (!loadGlobalIndex())
7134 return GlobalIndex->createIdentifierIterator();
7135
Guy Benyei11169dd2012-12-18 14:30:41 +00007136 return new ASTIdentifierIterator(*this);
7137}
7138
7139namespace clang { namespace serialization {
7140 class ReadMethodPoolVisitor {
7141 ASTReader &Reader;
7142 Selector Sel;
7143 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007144 unsigned InstanceBits;
7145 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007146 bool InstanceHasMoreThanOneDecl;
7147 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007148 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7149 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007150
7151 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007152 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007153 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007154 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007155 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7156 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007157
Guy Benyei11169dd2012-12-18 14:30:41 +00007158 static bool visit(ModuleFile &M, void *UserData) {
7159 ReadMethodPoolVisitor *This
7160 = static_cast<ReadMethodPoolVisitor *>(UserData);
7161
7162 if (!M.SelectorLookupTable)
7163 return false;
7164
7165 // If we've already searched this module file, skip it now.
7166 if (M.Generation <= This->PriorGeneration)
7167 return true;
7168
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007169 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007170 ASTSelectorLookupTable *PoolTable
7171 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
7172 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
7173 if (Pos == PoolTable->end())
7174 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007175
7176 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00007177 ++This->Reader.NumSelectorsRead;
7178 // FIXME: Not quite happy with the statistics here. We probably should
7179 // disable this tracking when called via LoadSelector.
7180 // Also, should entries without methods count as misses?
7181 ++This->Reader.NumMethodPoolEntriesRead;
7182 ASTSelectorLookupTrait::data_type Data = *Pos;
7183 if (This->Reader.DeserializationListener)
7184 This->Reader.DeserializationListener->SelectorRead(Data.ID,
7185 This->Sel);
7186
7187 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7188 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007189 This->InstanceBits = Data.InstanceBits;
7190 This->FactoryBits = Data.FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007191 This->InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7192 This->FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007193 return true;
7194 }
7195
7196 /// \brief Retrieve the instance methods found by this visitor.
7197 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7198 return InstanceMethods;
7199 }
7200
7201 /// \brief Retrieve the instance methods found by this visitor.
7202 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7203 return FactoryMethods;
7204 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007205
7206 unsigned getInstanceBits() const { return InstanceBits; }
7207 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007208 bool instanceHasMoreThanOneDecl() const {
7209 return InstanceHasMoreThanOneDecl;
7210 }
7211 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007212 };
7213} } // end namespace clang::serialization
7214
7215/// \brief Add the given set of methods to the method list.
7216static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7217 ObjCMethodList &List) {
7218 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7219 S.addMethodToGlobalList(&List, Methods[I]);
7220 }
7221}
7222
7223void ASTReader::ReadMethodPool(Selector Sel) {
7224 // Get the selector generation and update it to the current generation.
7225 unsigned &Generation = SelectorGeneration[Sel];
7226 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007227 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007228
7229 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007230 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007231 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7232 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
7233
7234 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007235 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007236 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007237
7238 ++NumMethodPoolHits;
7239
Guy Benyei11169dd2012-12-18 14:30:41 +00007240 if (!getSema())
7241 return;
7242
7243 Sema &S = *getSema();
7244 Sema::GlobalMethodPool::iterator Pos
7245 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007246
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007247 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007248 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007249 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007250 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007251
7252 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7253 // when building a module we keep every method individually and may need to
7254 // update hasMoreThanOneDecl as we add the methods.
7255 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7256 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007257}
7258
7259void ASTReader::ReadKnownNamespaces(
7260 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7261 Namespaces.clear();
7262
7263 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7264 if (NamespaceDecl *Namespace
7265 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7266 Namespaces.push_back(Namespace);
7267 }
7268}
7269
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007270void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007271 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007272 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7273 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007274 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007275 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007276 Undefined.insert(std::make_pair(D, Loc));
7277 }
7278}
Nick Lewycky8334af82013-01-26 00:35:08 +00007279
Guy Benyei11169dd2012-12-18 14:30:41 +00007280void ASTReader::ReadTentativeDefinitions(
7281 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7282 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7283 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7284 if (Var)
7285 TentativeDefs.push_back(Var);
7286 }
7287 TentativeDefinitions.clear();
7288}
7289
7290void ASTReader::ReadUnusedFileScopedDecls(
7291 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7292 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7293 DeclaratorDecl *D
7294 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7295 if (D)
7296 Decls.push_back(D);
7297 }
7298 UnusedFileScopedDecls.clear();
7299}
7300
7301void ASTReader::ReadDelegatingConstructors(
7302 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7303 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7304 CXXConstructorDecl *D
7305 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7306 if (D)
7307 Decls.push_back(D);
7308 }
7309 DelegatingCtorDecls.clear();
7310}
7311
7312void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7313 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7314 TypedefNameDecl *D
7315 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7316 if (D)
7317 Decls.push_back(D);
7318 }
7319 ExtVectorDecls.clear();
7320}
7321
Nico Weber72889432014-09-06 01:25:55 +00007322void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7323 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7324 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7325 ++I) {
7326 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7327 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7328 if (D)
7329 Decls.insert(D);
7330 }
7331 UnusedLocalTypedefNameCandidates.clear();
7332}
7333
Guy Benyei11169dd2012-12-18 14:30:41 +00007334void ASTReader::ReadReferencedSelectors(
7335 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7336 if (ReferencedSelectorsData.empty())
7337 return;
7338
7339 // If there are @selector references added them to its pool. This is for
7340 // implementation of -Wselector.
7341 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7342 unsigned I = 0;
7343 while (I < DataSize) {
7344 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7345 SourceLocation SelLoc
7346 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7347 Sels.push_back(std::make_pair(Sel, SelLoc));
7348 }
7349 ReferencedSelectorsData.clear();
7350}
7351
7352void ASTReader::ReadWeakUndeclaredIdentifiers(
7353 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7354 if (WeakUndeclaredIdentifiers.empty())
7355 return;
7356
7357 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7358 IdentifierInfo *WeakId
7359 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7360 IdentifierInfo *AliasId
7361 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7362 SourceLocation Loc
7363 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7364 bool Used = WeakUndeclaredIdentifiers[I++];
7365 WeakInfo WI(AliasId, Loc);
7366 WI.setUsed(Used);
7367 WeakIDs.push_back(std::make_pair(WeakId, WI));
7368 }
7369 WeakUndeclaredIdentifiers.clear();
7370}
7371
7372void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7373 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7374 ExternalVTableUse VT;
7375 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7376 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7377 VT.DefinitionRequired = VTableUses[Idx++];
7378 VTables.push_back(VT);
7379 }
7380
7381 VTableUses.clear();
7382}
7383
7384void ASTReader::ReadPendingInstantiations(
7385 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7386 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7387 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7388 SourceLocation Loc
7389 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7390
7391 Pending.push_back(std::make_pair(D, Loc));
7392 }
7393 PendingInstantiations.clear();
7394}
7395
Richard Smithe40f2ba2013-08-07 21:41:30 +00007396void ASTReader::ReadLateParsedTemplates(
7397 llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7398 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7399 /* In loop */) {
7400 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7401
7402 LateParsedTemplate *LT = new LateParsedTemplate;
7403 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7404
7405 ModuleFile *F = getOwningModuleFile(LT->D);
7406 assert(F && "No module");
7407
7408 unsigned TokN = LateParsedTemplates[Idx++];
7409 LT->Toks.reserve(TokN);
7410 for (unsigned T = 0; T < TokN; ++T)
7411 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7412
7413 LPTMap[FD] = LT;
7414 }
7415
7416 LateParsedTemplates.clear();
7417}
7418
Guy Benyei11169dd2012-12-18 14:30:41 +00007419void ASTReader::LoadSelector(Selector Sel) {
7420 // It would be complicated to avoid reading the methods anyway. So don't.
7421 ReadMethodPool(Sel);
7422}
7423
7424void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7425 assert(ID && "Non-zero identifier ID required");
7426 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7427 IdentifiersLoaded[ID - 1] = II;
7428 if (DeserializationListener)
7429 DeserializationListener->IdentifierRead(ID, II);
7430}
7431
7432/// \brief Set the globally-visible declarations associated with the given
7433/// identifier.
7434///
7435/// If the AST reader is currently in a state where the given declaration IDs
7436/// cannot safely be resolved, they are queued until it is safe to resolve
7437/// them.
7438///
7439/// \param II an IdentifierInfo that refers to one or more globally-visible
7440/// declarations.
7441///
7442/// \param DeclIDs the set of declaration IDs with the name @p II that are
7443/// visible at global scope.
7444///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007445/// \param Decls if non-null, this vector will be populated with the set of
7446/// deserialized declarations. These declarations will not be pushed into
7447/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007448void
7449ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7450 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007451 SmallVectorImpl<Decl *> *Decls) {
7452 if (NumCurrentElementsDeserializing && !Decls) {
7453 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007454 return;
7455 }
7456
7457 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007458 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007459 // Queue this declaration so that it will be added to the
7460 // translation unit scope and identifier's declaration chain
7461 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007462 PreloadedDeclIDs.push_back(DeclIDs[I]);
7463 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007464 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007465
7466 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7467
7468 // If we're simply supposed to record the declarations, do so now.
7469 if (Decls) {
7470 Decls->push_back(D);
7471 continue;
7472 }
7473
7474 // Introduce this declaration into the translation-unit scope
7475 // and add it to the declaration chain for this identifier, so
7476 // that (unqualified) name lookup will find it.
7477 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007478 }
7479}
7480
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007481IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007482 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007483 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007484
7485 if (IdentifiersLoaded.empty()) {
7486 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007487 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007488 }
7489
7490 ID -= 1;
7491 if (!IdentifiersLoaded[ID]) {
7492 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7493 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7494 ModuleFile *M = I->second;
7495 unsigned Index = ID - M->BaseIdentifierID;
7496 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7497
7498 // All of the strings in the AST file are preceded by a 16-bit length.
7499 // Extract that 16-bit length to avoid having to execute strlen().
7500 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7501 // unsigned integers. This is important to avoid integer overflow when
7502 // we cast them to 'unsigned'.
7503 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7504 unsigned StrLen = (((unsigned) StrLenPtr[0])
7505 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007506 IdentifiersLoaded[ID]
7507 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007508 if (DeserializationListener)
7509 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7510 }
7511
7512 return IdentifiersLoaded[ID];
7513}
7514
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007515IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7516 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007517}
7518
7519IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7520 if (LocalID < NUM_PREDEF_IDENT_IDS)
7521 return LocalID;
7522
7523 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7524 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7525 assert(I != M.IdentifierRemap.end()
7526 && "Invalid index into identifier index remap");
7527
7528 return LocalID + I->second;
7529}
7530
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007531MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007532 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007533 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007534
7535 if (MacrosLoaded.empty()) {
7536 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007537 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007538 }
7539
7540 ID -= NUM_PREDEF_MACRO_IDS;
7541 if (!MacrosLoaded[ID]) {
7542 GlobalMacroMapType::iterator I
7543 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7544 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7545 ModuleFile *M = I->second;
7546 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007547 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7548
7549 if (DeserializationListener)
7550 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7551 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007552 }
7553
7554 return MacrosLoaded[ID];
7555}
7556
7557MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7558 if (LocalID < NUM_PREDEF_MACRO_IDS)
7559 return LocalID;
7560
7561 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7562 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7563 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7564
7565 return LocalID + I->second;
7566}
7567
7568serialization::SubmoduleID
7569ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7570 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7571 return LocalID;
7572
7573 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7574 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7575 assert(I != M.SubmoduleRemap.end()
7576 && "Invalid index into submodule index remap");
7577
7578 return LocalID + I->second;
7579}
7580
7581Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7582 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7583 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007584 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007585 }
7586
7587 if (GlobalID > SubmodulesLoaded.size()) {
7588 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007589 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007590 }
7591
7592 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7593}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007594
7595Module *ASTReader::getModule(unsigned ID) {
7596 return getSubmodule(ID);
7597}
7598
Guy Benyei11169dd2012-12-18 14:30:41 +00007599Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7600 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7601}
7602
7603Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7604 if (ID == 0)
7605 return Selector();
7606
7607 if (ID > SelectorsLoaded.size()) {
7608 Error("selector ID out of range in AST file");
7609 return Selector();
7610 }
7611
Craig Toppera13603a2014-05-22 05:54:18 +00007612 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007613 // Load this selector from the selector table.
7614 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7615 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7616 ModuleFile &M = *I->second;
7617 ASTSelectorLookupTrait Trait(*this, M);
7618 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7619 SelectorsLoaded[ID - 1] =
7620 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7621 if (DeserializationListener)
7622 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7623 }
7624
7625 return SelectorsLoaded[ID - 1];
7626}
7627
7628Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7629 return DecodeSelector(ID);
7630}
7631
7632uint32_t ASTReader::GetNumExternalSelectors() {
7633 // ID 0 (the null selector) is considered an external selector.
7634 return getTotalNumSelectors() + 1;
7635}
7636
7637serialization::SelectorID
7638ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7639 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7640 return LocalID;
7641
7642 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7643 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7644 assert(I != M.SelectorRemap.end()
7645 && "Invalid index into selector index remap");
7646
7647 return LocalID + I->second;
7648}
7649
7650DeclarationName
7651ASTReader::ReadDeclarationName(ModuleFile &F,
7652 const RecordData &Record, unsigned &Idx) {
7653 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7654 switch (Kind) {
7655 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007656 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007657
7658 case DeclarationName::ObjCZeroArgSelector:
7659 case DeclarationName::ObjCOneArgSelector:
7660 case DeclarationName::ObjCMultiArgSelector:
7661 return DeclarationName(ReadSelector(F, Record, Idx));
7662
7663 case DeclarationName::CXXConstructorName:
7664 return Context.DeclarationNames.getCXXConstructorName(
7665 Context.getCanonicalType(readType(F, Record, Idx)));
7666
7667 case DeclarationName::CXXDestructorName:
7668 return Context.DeclarationNames.getCXXDestructorName(
7669 Context.getCanonicalType(readType(F, Record, Idx)));
7670
7671 case DeclarationName::CXXConversionFunctionName:
7672 return Context.DeclarationNames.getCXXConversionFunctionName(
7673 Context.getCanonicalType(readType(F, Record, Idx)));
7674
7675 case DeclarationName::CXXOperatorName:
7676 return Context.DeclarationNames.getCXXOperatorName(
7677 (OverloadedOperatorKind)Record[Idx++]);
7678
7679 case DeclarationName::CXXLiteralOperatorName:
7680 return Context.DeclarationNames.getCXXLiteralOperatorName(
7681 GetIdentifierInfo(F, Record, Idx));
7682
7683 case DeclarationName::CXXUsingDirective:
7684 return DeclarationName::getUsingDirectiveName();
7685 }
7686
7687 llvm_unreachable("Invalid NameKind!");
7688}
7689
7690void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7691 DeclarationNameLoc &DNLoc,
7692 DeclarationName Name,
7693 const RecordData &Record, unsigned &Idx) {
7694 switch (Name.getNameKind()) {
7695 case DeclarationName::CXXConstructorName:
7696 case DeclarationName::CXXDestructorName:
7697 case DeclarationName::CXXConversionFunctionName:
7698 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7699 break;
7700
7701 case DeclarationName::CXXOperatorName:
7702 DNLoc.CXXOperatorName.BeginOpNameLoc
7703 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7704 DNLoc.CXXOperatorName.EndOpNameLoc
7705 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7706 break;
7707
7708 case DeclarationName::CXXLiteralOperatorName:
7709 DNLoc.CXXLiteralOperatorName.OpNameLoc
7710 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7711 break;
7712
7713 case DeclarationName::Identifier:
7714 case DeclarationName::ObjCZeroArgSelector:
7715 case DeclarationName::ObjCOneArgSelector:
7716 case DeclarationName::ObjCMultiArgSelector:
7717 case DeclarationName::CXXUsingDirective:
7718 break;
7719 }
7720}
7721
7722void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7723 DeclarationNameInfo &NameInfo,
7724 const RecordData &Record, unsigned &Idx) {
7725 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7726 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7727 DeclarationNameLoc DNLoc;
7728 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7729 NameInfo.setInfo(DNLoc);
7730}
7731
7732void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7733 const RecordData &Record, unsigned &Idx) {
7734 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7735 unsigned NumTPLists = Record[Idx++];
7736 Info.NumTemplParamLists = NumTPLists;
7737 if (NumTPLists) {
7738 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7739 for (unsigned i=0; i != NumTPLists; ++i)
7740 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7741 }
7742}
7743
7744TemplateName
7745ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7746 unsigned &Idx) {
7747 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7748 switch (Kind) {
7749 case TemplateName::Template:
7750 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7751
7752 case TemplateName::OverloadedTemplate: {
7753 unsigned size = Record[Idx++];
7754 UnresolvedSet<8> Decls;
7755 while (size--)
7756 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7757
7758 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7759 }
7760
7761 case TemplateName::QualifiedTemplate: {
7762 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7763 bool hasTemplKeyword = Record[Idx++];
7764 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7765 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7766 }
7767
7768 case TemplateName::DependentTemplate: {
7769 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7770 if (Record[Idx++]) // isIdentifier
7771 return Context.getDependentTemplateName(NNS,
7772 GetIdentifierInfo(F, Record,
7773 Idx));
7774 return Context.getDependentTemplateName(NNS,
7775 (OverloadedOperatorKind)Record[Idx++]);
7776 }
7777
7778 case TemplateName::SubstTemplateTemplateParm: {
7779 TemplateTemplateParmDecl *param
7780 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7781 if (!param) return TemplateName();
7782 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7783 return Context.getSubstTemplateTemplateParm(param, replacement);
7784 }
7785
7786 case TemplateName::SubstTemplateTemplateParmPack: {
7787 TemplateTemplateParmDecl *Param
7788 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7789 if (!Param)
7790 return TemplateName();
7791
7792 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7793 if (ArgPack.getKind() != TemplateArgument::Pack)
7794 return TemplateName();
7795
7796 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7797 }
7798 }
7799
7800 llvm_unreachable("Unhandled template name kind!");
7801}
7802
7803TemplateArgument
7804ASTReader::ReadTemplateArgument(ModuleFile &F,
7805 const RecordData &Record, unsigned &Idx) {
7806 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7807 switch (Kind) {
7808 case TemplateArgument::Null:
7809 return TemplateArgument();
7810 case TemplateArgument::Type:
7811 return TemplateArgument(readType(F, Record, Idx));
7812 case TemplateArgument::Declaration: {
7813 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007814 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007815 }
7816 case TemplateArgument::NullPtr:
7817 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7818 case TemplateArgument::Integral: {
7819 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7820 QualType T = readType(F, Record, Idx);
7821 return TemplateArgument(Context, Value, T);
7822 }
7823 case TemplateArgument::Template:
7824 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7825 case TemplateArgument::TemplateExpansion: {
7826 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007827 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007828 if (unsigned NumExpansions = Record[Idx++])
7829 NumTemplateExpansions = NumExpansions - 1;
7830 return TemplateArgument(Name, NumTemplateExpansions);
7831 }
7832 case TemplateArgument::Expression:
7833 return TemplateArgument(ReadExpr(F));
7834 case TemplateArgument::Pack: {
7835 unsigned NumArgs = Record[Idx++];
7836 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7837 for (unsigned I = 0; I != NumArgs; ++I)
7838 Args[I] = ReadTemplateArgument(F, Record, Idx);
7839 return TemplateArgument(Args, NumArgs);
7840 }
7841 }
7842
7843 llvm_unreachable("Unhandled template argument kind!");
7844}
7845
7846TemplateParameterList *
7847ASTReader::ReadTemplateParameterList(ModuleFile &F,
7848 const RecordData &Record, unsigned &Idx) {
7849 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7850 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7851 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7852
7853 unsigned NumParams = Record[Idx++];
7854 SmallVector<NamedDecl *, 16> Params;
7855 Params.reserve(NumParams);
7856 while (NumParams--)
7857 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7858
7859 TemplateParameterList* TemplateParams =
7860 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7861 Params.data(), Params.size(), RAngleLoc);
7862 return TemplateParams;
7863}
7864
7865void
7866ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007867ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007868 ModuleFile &F, const RecordData &Record,
7869 unsigned &Idx) {
7870 unsigned NumTemplateArgs = Record[Idx++];
7871 TemplArgs.reserve(NumTemplateArgs);
7872 while (NumTemplateArgs--)
7873 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7874}
7875
7876/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007877void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007878 const RecordData &Record, unsigned &Idx) {
7879 unsigned NumDecls = Record[Idx++];
7880 Set.reserve(Context, NumDecls);
7881 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007882 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007883 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007884 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007885 }
7886}
7887
7888CXXBaseSpecifier
7889ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7890 const RecordData &Record, unsigned &Idx) {
7891 bool isVirtual = static_cast<bool>(Record[Idx++]);
7892 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7893 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7894 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7895 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7896 SourceRange Range = ReadSourceRange(F, Record, Idx);
7897 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7898 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7899 EllipsisLoc);
7900 Result.setInheritConstructors(inheritConstructors);
7901 return Result;
7902}
7903
7904std::pair<CXXCtorInitializer **, unsigned>
7905ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7906 unsigned &Idx) {
Craig Toppera13603a2014-05-22 05:54:18 +00007907 CXXCtorInitializer **CtorInitializers = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007908 unsigned NumInitializers = Record[Idx++];
7909 if (NumInitializers) {
7910 CtorInitializers
7911 = new (Context) CXXCtorInitializer*[NumInitializers];
7912 for (unsigned i=0; i != NumInitializers; ++i) {
Craig Toppera13603a2014-05-22 05:54:18 +00007913 TypeSourceInfo *TInfo = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007914 bool IsBaseVirtual = false;
Craig Toppera13603a2014-05-22 05:54:18 +00007915 FieldDecl *Member = nullptr;
7916 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007917
7918 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7919 switch (Type) {
7920 case CTOR_INITIALIZER_BASE:
7921 TInfo = GetTypeSourceInfo(F, Record, Idx);
7922 IsBaseVirtual = Record[Idx++];
7923 break;
7924
7925 case CTOR_INITIALIZER_DELEGATING:
7926 TInfo = GetTypeSourceInfo(F, Record, Idx);
7927 break;
7928
7929 case CTOR_INITIALIZER_MEMBER:
7930 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7931 break;
7932
7933 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7934 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7935 break;
7936 }
7937
7938 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7939 Expr *Init = ReadExpr(F);
7940 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7941 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7942 bool IsWritten = Record[Idx++];
7943 unsigned SourceOrderOrNumArrayIndices;
7944 SmallVector<VarDecl *, 8> Indices;
7945 if (IsWritten) {
7946 SourceOrderOrNumArrayIndices = Record[Idx++];
7947 } else {
7948 SourceOrderOrNumArrayIndices = Record[Idx++];
7949 Indices.reserve(SourceOrderOrNumArrayIndices);
7950 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7951 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7952 }
7953
7954 CXXCtorInitializer *BOMInit;
7955 if (Type == CTOR_INITIALIZER_BASE) {
7956 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7957 LParenLoc, Init, RParenLoc,
7958 MemberOrEllipsisLoc);
7959 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7960 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7961 Init, RParenLoc);
7962 } else if (IsWritten) {
7963 if (Member)
7964 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7965 LParenLoc, Init, RParenLoc);
7966 else
7967 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7968 MemberOrEllipsisLoc, LParenLoc,
7969 Init, RParenLoc);
7970 } else {
Argyrios Kyrtzidis794671d2013-05-30 23:59:46 +00007971 if (IndirectMember) {
7972 assert(Indices.empty() && "Indirect field improperly initialized");
7973 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7974 MemberOrEllipsisLoc, LParenLoc,
7975 Init, RParenLoc);
7976 } else {
7977 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7978 LParenLoc, Init, RParenLoc,
7979 Indices.data(), Indices.size());
7980 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007981 }
7982
7983 if (IsWritten)
7984 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7985 CtorInitializers[i] = BOMInit;
7986 }
7987 }
7988
7989 return std::make_pair(CtorInitializers, NumInitializers);
7990}
7991
7992NestedNameSpecifier *
7993ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7994 const RecordData &Record, unsigned &Idx) {
7995 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007996 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007997 for (unsigned I = 0; I != N; ++I) {
7998 NestedNameSpecifier::SpecifierKind Kind
7999 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8000 switch (Kind) {
8001 case NestedNameSpecifier::Identifier: {
8002 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8003 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8004 break;
8005 }
8006
8007 case NestedNameSpecifier::Namespace: {
8008 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8009 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8010 break;
8011 }
8012
8013 case NestedNameSpecifier::NamespaceAlias: {
8014 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8015 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8016 break;
8017 }
8018
8019 case NestedNameSpecifier::TypeSpec:
8020 case NestedNameSpecifier::TypeSpecWithTemplate: {
8021 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8022 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008023 return nullptr;
8024
Guy Benyei11169dd2012-12-18 14:30:41 +00008025 bool Template = Record[Idx++];
8026 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8027 break;
8028 }
8029
8030 case NestedNameSpecifier::Global: {
8031 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8032 // No associated value, and there can't be a prefix.
8033 break;
8034 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008035
8036 case NestedNameSpecifier::Super: {
8037 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8038 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8039 break;
8040 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008041 }
8042 Prev = NNS;
8043 }
8044 return NNS;
8045}
8046
8047NestedNameSpecifierLoc
8048ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8049 unsigned &Idx) {
8050 unsigned N = Record[Idx++];
8051 NestedNameSpecifierLocBuilder Builder;
8052 for (unsigned I = 0; I != N; ++I) {
8053 NestedNameSpecifier::SpecifierKind Kind
8054 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8055 switch (Kind) {
8056 case NestedNameSpecifier::Identifier: {
8057 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8058 SourceRange Range = ReadSourceRange(F, Record, Idx);
8059 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8060 break;
8061 }
8062
8063 case NestedNameSpecifier::Namespace: {
8064 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8065 SourceRange Range = ReadSourceRange(F, Record, Idx);
8066 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8067 break;
8068 }
8069
8070 case NestedNameSpecifier::NamespaceAlias: {
8071 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8072 SourceRange Range = ReadSourceRange(F, Record, Idx);
8073 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8074 break;
8075 }
8076
8077 case NestedNameSpecifier::TypeSpec:
8078 case NestedNameSpecifier::TypeSpecWithTemplate: {
8079 bool Template = Record[Idx++];
8080 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8081 if (!T)
8082 return NestedNameSpecifierLoc();
8083 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8084
8085 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8086 Builder.Extend(Context,
8087 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8088 T->getTypeLoc(), ColonColonLoc);
8089 break;
8090 }
8091
8092 case NestedNameSpecifier::Global: {
8093 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8094 Builder.MakeGlobal(Context, ColonColonLoc);
8095 break;
8096 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008097
8098 case NestedNameSpecifier::Super: {
8099 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8100 SourceRange Range = ReadSourceRange(F, Record, Idx);
8101 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8102 break;
8103 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008104 }
8105 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008106
Guy Benyei11169dd2012-12-18 14:30:41 +00008107 return Builder.getWithLocInContext(Context);
8108}
8109
8110SourceRange
8111ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8112 unsigned &Idx) {
8113 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8114 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8115 return SourceRange(beg, end);
8116}
8117
8118/// \brief Read an integral value
8119llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8120 unsigned BitWidth = Record[Idx++];
8121 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8122 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8123 Idx += NumWords;
8124 return Result;
8125}
8126
8127/// \brief Read a signed integral value
8128llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8129 bool isUnsigned = Record[Idx++];
8130 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8131}
8132
8133/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008134llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8135 const llvm::fltSemantics &Sem,
8136 unsigned &Idx) {
8137 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008138}
8139
8140// \brief Read a string
8141std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8142 unsigned Len = Record[Idx++];
8143 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8144 Idx += Len;
8145 return Result;
8146}
8147
Richard Smith7ed1bc92014-12-05 22:42:13 +00008148std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8149 unsigned &Idx) {
8150 std::string Filename = ReadString(Record, Idx);
8151 ResolveImportedPath(F, Filename);
8152 return Filename;
8153}
8154
Guy Benyei11169dd2012-12-18 14:30:41 +00008155VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8156 unsigned &Idx) {
8157 unsigned Major = Record[Idx++];
8158 unsigned Minor = Record[Idx++];
8159 unsigned Subminor = Record[Idx++];
8160 if (Minor == 0)
8161 return VersionTuple(Major);
8162 if (Subminor == 0)
8163 return VersionTuple(Major, Minor - 1);
8164 return VersionTuple(Major, Minor - 1, Subminor - 1);
8165}
8166
8167CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8168 const RecordData &Record,
8169 unsigned &Idx) {
8170 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8171 return CXXTemporary::Create(Context, Decl);
8172}
8173
8174DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008175 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008176}
8177
8178DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8179 return Diags.Report(Loc, DiagID);
8180}
8181
8182/// \brief Retrieve the identifier table associated with the
8183/// preprocessor.
8184IdentifierTable &ASTReader::getIdentifierTable() {
8185 return PP.getIdentifierTable();
8186}
8187
8188/// \brief Record that the given ID maps to the given switch-case
8189/// statement.
8190void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008191 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008192 "Already have a SwitchCase with this ID");
8193 (*CurrSwitchCaseStmts)[ID] = SC;
8194}
8195
8196/// \brief Retrieve the switch-case statement with the given ID.
8197SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008198 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008199 return (*CurrSwitchCaseStmts)[ID];
8200}
8201
8202void ASTReader::ClearSwitchCaseIDs() {
8203 CurrSwitchCaseStmts->clear();
8204}
8205
8206void ASTReader::ReadComments() {
8207 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008208 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008209 serialization::ModuleFile *> >::iterator
8210 I = CommentsCursors.begin(),
8211 E = CommentsCursors.end();
8212 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008213 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008214 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008215 serialization::ModuleFile &F = *I->second;
8216 SavedStreamPosition SavedPosition(Cursor);
8217
8218 RecordData Record;
8219 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008220 llvm::BitstreamEntry Entry =
8221 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008222
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008223 switch (Entry.Kind) {
8224 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8225 case llvm::BitstreamEntry::Error:
8226 Error("malformed block record in AST file");
8227 return;
8228 case llvm::BitstreamEntry::EndBlock:
8229 goto NextCursor;
8230 case llvm::BitstreamEntry::Record:
8231 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008232 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008233 }
8234
8235 // Read a record.
8236 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008237 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008238 case COMMENTS_RAW_COMMENT: {
8239 unsigned Idx = 0;
8240 SourceRange SR = ReadSourceRange(F, Record, Idx);
8241 RawComment::CommentKind Kind =
8242 (RawComment::CommentKind) Record[Idx++];
8243 bool IsTrailingComment = Record[Idx++];
8244 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008245 Comments.push_back(new (Context) RawComment(
8246 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8247 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008248 break;
8249 }
8250 }
8251 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008252 NextCursor:
8253 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008254 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008255}
8256
Argyrios Kyrtzidis1bde1172014-11-18 05:24:18 +00008257void ASTReader::getInputFiles(ModuleFile &F,
8258 SmallVectorImpl<serialization::InputFile> &Files) {
8259 for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
8260 unsigned ID = I+1;
8261 Files.push_back(getInputFile(F, ID));
8262 }
8263}
8264
Richard Smithcd45dbc2014-04-19 03:48:30 +00008265std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8266 // If we know the owning module, use it.
8267 if (Module *M = D->getOwningModule())
8268 return M->getFullModuleName();
8269
8270 // Otherwise, use the name of the top-level module the decl is within.
8271 if (ModuleFile *M = getOwningModuleFile(D))
8272 return M->ModuleName;
8273
8274 // Not from a module.
8275 return "";
8276}
8277
Guy Benyei11169dd2012-12-18 14:30:41 +00008278void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008279 while (!PendingIdentifierInfos.empty() ||
8280 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008281 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008282 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008283 // If any identifiers with corresponding top-level declarations have
8284 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008285 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8286 TopLevelDeclsMap;
8287 TopLevelDeclsMap TopLevelDecls;
8288
Guy Benyei11169dd2012-12-18 14:30:41 +00008289 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008290 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008291 SmallVector<uint32_t, 4> DeclIDs =
8292 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008293 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008294
8295 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008296 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008297
Richard Smith851072e2014-05-19 20:59:20 +00008298 // For each decl chain that we wanted to complete while deserializing, mark
8299 // it as "still needs to be completed".
8300 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8301 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8302 }
8303 PendingIncompleteDeclChains.clear();
8304
Guy Benyei11169dd2012-12-18 14:30:41 +00008305 // Load pending declaration chains.
Richard Smithfe620d22015-03-05 23:24:12 +00008306 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
Richard Smithfe620d22015-03-05 23:24:12 +00008307 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
Richard Smithe687bf82015-03-16 20:54:07 +00008308 loadPendingDeclChain(PendingDeclChains[I]);
Richard Smithfe620d22015-03-05 23:24:12 +00008309 }
8310 assert(PendingDeclChainsKnown.empty());
Guy Benyei11169dd2012-12-18 14:30:41 +00008311 PendingDeclChains.clear();
8312
Douglas Gregor6168bd22013-02-18 15:53:43 +00008313 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008314 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8315 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008316 IdentifierInfo *II = TLD->first;
8317 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008318 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008319 }
8320 }
8321
Guy Benyei11169dd2012-12-18 14:30:41 +00008322 // Load any pending macro definitions.
8323 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008324 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8325 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8326 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8327 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008328 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008329 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008330 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008331 if (Info.M->Kind != MK_ImplicitModule &&
8332 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008333 resolvePendingMacro(II, Info);
8334 }
8335 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008336 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008337 ++IDIdx) {
8338 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008339 if (Info.M->Kind == MK_ImplicitModule ||
8340 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008341 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008342 }
8343 }
8344 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008345
8346 // Wire up the DeclContexts for Decls that we delayed setting until
8347 // recursive loading is completed.
8348 while (!PendingDeclContextInfos.empty()) {
8349 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8350 PendingDeclContextInfos.pop_front();
8351 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8352 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8353 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8354 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008355
Richard Smithd1c46742014-04-30 02:24:17 +00008356 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008357 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008358 auto Update = PendingUpdateRecords.pop_back_val();
8359 ReadingKindTracker ReadingKind(Read_Decl, *this);
8360 loadDeclUpdateRecords(Update.first, Update.second);
8361 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008362 }
Richard Smith8a639892015-01-24 01:07:20 +00008363
8364 // At this point, all update records for loaded decls are in place, so any
8365 // fake class definitions should have become real.
8366 assert(PendingFakeDefinitionData.empty() &&
8367 "faked up a class definition but never saw the real one");
8368
Guy Benyei11169dd2012-12-18 14:30:41 +00008369 // If we deserialized any C++ or Objective-C class definitions, any
8370 // Objective-C protocol definitions, or any redeclarable templates, make sure
8371 // that all redeclarations point to the definitions. Note that this can only
8372 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008373 for (Decl *D : PendingDefinitions) {
8374 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008375 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008376 // Make sure that the TagType points at the definition.
8377 const_cast<TagType*>(TagT)->decl = TD;
8378 }
Richard Smith8ce51082015-03-11 01:44:51 +00008379
Craig Topperc6914d02014-08-25 04:15:02 +00008380 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008381 for (auto *R = getMostRecentExistingDecl(RD); R;
8382 R = R->getPreviousDecl()) {
8383 assert((R == D) ==
8384 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008385 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008386 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008387 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008388 }
8389
8390 continue;
8391 }
Richard Smith8ce51082015-03-11 01:44:51 +00008392
Craig Topperc6914d02014-08-25 04:15:02 +00008393 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008394 // Make sure that the ObjCInterfaceType points at the definition.
8395 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8396 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008397
8398 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8399 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8400
Guy Benyei11169dd2012-12-18 14:30:41 +00008401 continue;
8402 }
Richard Smith8ce51082015-03-11 01:44:51 +00008403
Craig Topperc6914d02014-08-25 04:15:02 +00008404 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008405 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8406 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8407
Guy Benyei11169dd2012-12-18 14:30:41 +00008408 continue;
8409 }
Richard Smith8ce51082015-03-11 01:44:51 +00008410
Craig Topperc6914d02014-08-25 04:15:02 +00008411 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008412 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8413 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008414 }
8415 PendingDefinitions.clear();
8416
8417 // Load the bodies of any functions or methods we've encountered. We do
8418 // this now (delayed) so that we can be sure that the declaration chains
8419 // have been fully wired up.
Richard Smith8ce51082015-03-11 01:44:51 +00008420 // FIXME: There seems to be no point in delaying this, it does not depend
8421 // on the redecl chains having been wired up.
Guy Benyei11169dd2012-12-18 14:30:41 +00008422 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8423 PBEnd = PendingBodies.end();
8424 PB != PBEnd; ++PB) {
8425 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8426 // FIXME: Check for =delete/=default?
8427 // FIXME: Complain about ODR violations here?
8428 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8429 FD->setLazyBody(PB->second);
8430 continue;
8431 }
8432
8433 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8434 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8435 MD->setLazyBody(PB->second);
8436 }
8437 PendingBodies.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008438}
8439
8440void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008441 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8442 return;
8443
Richard Smitha0ce9c42014-07-29 23:23:27 +00008444 // Trigger the import of the full definition of each class that had any
8445 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008446 // These updates may in turn find and diagnose some ODR failures, so take
8447 // ownership of the set first.
8448 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8449 PendingOdrMergeFailures.clear();
8450 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008451 Merge.first->buildLookup();
8452 Merge.first->decls_begin();
8453 Merge.first->bases_begin();
8454 Merge.first->vbases_begin();
8455 for (auto *RD : Merge.second) {
8456 RD->decls_begin();
8457 RD->bases_begin();
8458 RD->vbases_begin();
8459 }
8460 }
8461
8462 // For each declaration from a merged context, check that the canonical
8463 // definition of that context also contains a declaration of the same
8464 // entity.
8465 //
8466 // Caution: this loop does things that might invalidate iterators into
8467 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8468 while (!PendingOdrMergeChecks.empty()) {
8469 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8470
8471 // FIXME: Skip over implicit declarations for now. This matters for things
8472 // like implicitly-declared special member functions. This isn't entirely
8473 // correct; we can end up with multiple unmerged declarations of the same
8474 // implicit entity.
8475 if (D->isImplicit())
8476 continue;
8477
8478 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008479
8480 bool Found = false;
8481 const Decl *DCanon = D->getCanonicalDecl();
8482
Richard Smith01bdb7a2014-08-28 05:44:07 +00008483 for (auto RI : D->redecls()) {
8484 if (RI->getLexicalDeclContext() == CanonDef) {
8485 Found = true;
8486 break;
8487 }
8488 }
8489 if (Found)
8490 continue;
8491
Richard Smitha0ce9c42014-07-29 23:23:27 +00008492 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith01bdb7a2014-08-28 05:44:07 +00008493 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
Richard Smitha0ce9c42014-07-29 23:23:27 +00008494 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8495 !Found && I != E; ++I) {
8496 for (auto RI : (*I)->redecls()) {
8497 if (RI->getLexicalDeclContext() == CanonDef) {
8498 // This declaration is present in the canonical definition. If it's
8499 // in the same redecl chain, it's the one we're looking for.
8500 if (RI->getCanonicalDecl() == DCanon)
8501 Found = true;
8502 else
8503 Candidates.push_back(cast<NamedDecl>(RI));
8504 break;
8505 }
8506 }
8507 }
8508
8509 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008510 // The AST doesn't like TagDecls becoming invalid after they've been
8511 // completed. We only really need to mark FieldDecls as invalid here.
8512 if (!isa<TagDecl>(D))
8513 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008514
8515 // Ensure we don't accidentally recursively enter deserialization while
8516 // we're producing our diagnostic.
8517 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008518
8519 std::string CanonDefModule =
8520 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8521 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8522 << D << getOwningModuleNameForDiagnostic(D)
8523 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8524
8525 if (Candidates.empty())
8526 Diag(cast<Decl>(CanonDef)->getLocation(),
8527 diag::note_module_odr_violation_no_possible_decls) << D;
8528 else {
8529 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8530 Diag(Candidates[I]->getLocation(),
8531 diag::note_module_odr_violation_possible_decl)
8532 << Candidates[I];
8533 }
8534
8535 DiagnosedOdrMergeFailures.insert(CanonDef);
8536 }
8537 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008538
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008539 if (OdrMergeFailures.empty())
8540 return;
8541
8542 // Ensure we don't accidentally recursively enter deserialization while
8543 // we're producing our diagnostics.
8544 Deserializing RecursionGuard(this);
8545
Richard Smithcd45dbc2014-04-19 03:48:30 +00008546 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008547 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008548 // If we've already pointed out a specific problem with this class, don't
8549 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008550 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008551 continue;
8552
8553 bool Diagnosed = false;
8554 for (auto *RD : Merge.second) {
8555 // Multiple different declarations got merged together; tell the user
8556 // where they came from.
8557 if (Merge.first != RD) {
8558 // FIXME: Walk the definition, figure out what's different,
8559 // and diagnose that.
8560 if (!Diagnosed) {
8561 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8562 Diag(Merge.first->getLocation(),
8563 diag::err_module_odr_violation_different_definitions)
8564 << Merge.first << Module.empty() << Module;
8565 Diagnosed = true;
8566 }
8567
8568 Diag(RD->getLocation(),
8569 diag::note_module_odr_violation_different_definitions)
8570 << getOwningModuleNameForDiagnostic(RD);
8571 }
8572 }
8573
8574 if (!Diagnosed) {
8575 // All definitions are updates to the same declaration. This happens if a
8576 // module instantiates the declaration of a class template specialization
8577 // and two or more other modules instantiate its definition.
8578 //
8579 // FIXME: Indicate which modules had instantiations of this definition.
8580 // FIXME: How can this even happen?
8581 Diag(Merge.first->getLocation(),
8582 diag::err_module_odr_violation_different_instantiations)
8583 << Merge.first;
8584 }
8585 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008586}
8587
8588void ASTReader::FinishedDeserializing() {
8589 assert(NumCurrentElementsDeserializing &&
8590 "FinishedDeserializing not paired with StartedDeserializing");
8591 if (NumCurrentElementsDeserializing == 1) {
8592 // We decrease NumCurrentElementsDeserializing only after pending actions
8593 // are finished, to avoid recursively re-calling finishPendingActions().
8594 finishPendingActions();
8595 }
8596 --NumCurrentElementsDeserializing;
8597
Richard Smitha0ce9c42014-07-29 23:23:27 +00008598 if (NumCurrentElementsDeserializing == 0) {
8599 diagnoseOdrViolations();
8600
Richard Smith04d05b52014-03-23 00:27:18 +00008601 // We are not in recursive loading, so it's safe to pass the "interesting"
8602 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008603 if (Consumer)
8604 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008605 }
8606}
8607
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008608void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +00008609 D = D->getMostRecentDecl();
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008610
8611 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8612 SemaObj->TUScope->AddDecl(D);
8613 } else if (SemaObj->TUScope) {
8614 // Adding the decl to IdResolver may have failed because it was already in
8615 // (even though it was not added in scope). If it is already in, make sure
8616 // it gets in the scope as well.
8617 if (std::find(SemaObj->IdResolver.begin(Name),
8618 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8619 SemaObj->TUScope->AddDecl(D);
8620 }
8621}
8622
Nico Weber824285e2014-05-08 04:26:47 +00008623ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8624 bool DisableValidation, bool AllowASTWithCompilerErrors,
8625 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008626 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008627 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008628 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Craig Toppera13603a2014-05-22 05:54:18 +00008629 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
8630 SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
8631 ModuleMgr(PP.getFileManager()), isysroot(isysroot),
8632 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008633 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8634 AllowConfigurationMismatch(AllowConfigurationMismatch),
8635 ValidateSystemInputs(ValidateSystemInputs),
8636 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Richard Smith053f6c62014-05-16 23:01:30 +00008637 CurrSwitchCaseStmts(&SwitchCaseStmts),
Nico Weber824285e2014-05-08 04:26:47 +00008638 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8639 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8640 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8641 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8642 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8643 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8644 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8645 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8646 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8647 PassingDeclsToConsumer(false), NumCXXBaseSpecifiersLoaded(0),
8648 ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008649 SourceMgr.setExternalSLocEntrySource(this);
8650}
8651
8652ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008653 if (OwnsDeserializationListener)
8654 delete DeserializationListener;
8655
Guy Benyei11169dd2012-12-18 14:30:41 +00008656 for (DeclContextVisibleUpdatesPending::iterator
8657 I = PendingVisibleUpdates.begin(),
8658 E = PendingVisibleUpdates.end();
8659 I != E; ++I) {
8660 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8661 F = I->second.end();
8662 J != F; ++J)
8663 delete J->first;
8664 }
8665}