blob: 847f1ff88175b1f69bf14618ce91590d989e68ce [file] [log] [blame]
Richard Smith9e2341d2015-03-23 03:25:59 +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;
780 bool hadMacroDefinition = Bits & 0x01;
781 Bits >>= 1;
782
783 assert(Bits == 0 && "Extra bits in the identifier?");
784 DataLen -= 8;
785
786 // Build the IdentifierInfo itself and link the identifier ID with
787 // the new IdentifierInfo.
788 IdentifierInfo *II = KnownII;
789 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000790 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000791 KnownII = II;
792 }
793 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000794 if (!II->isFromAST()) {
795 bool WasInteresting = isInterestingIdentifier(*II);
796 II->setIsFromAST();
797 if (WasInteresting)
798 II->setChangedSinceDeserialization();
799 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000800
801 // Set or check the various bits in the IdentifierInfo structure.
802 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000803 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000804 II->RevertTokenIDToIdentifier();
805 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
806 assert(II->isExtensionToken() == ExtensionToken &&
807 "Incorrect extension token flag");
808 (void)ExtensionToken;
809 if (Poisoned)
810 II->setIsPoisoned(true);
811 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
812 "Incorrect C++ operator keyword flag");
813 (void)CPlusPlusOperatorKeyword;
814
815 // If this identifier is a macro, deserialize the macro
816 // definition.
817 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000818 uint32_t MacroDirectivesOffset =
819 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000820 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000821
Richard Smithd7329392015-04-21 21:46:32 +0000822 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000823 }
824
825 Reader.SetIdentifierInfo(ID, II);
826
827 // Read all of the declarations visible at global scope with this
828 // name.
829 if (DataLen > 0) {
830 SmallVector<uint32_t, 4> DeclIDs;
831 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000832 DeclIDs.push_back(Reader.getGlobalDeclID(
833 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000834 Reader.SetGloballyVisibleDecls(II, DeclIDs);
835 }
836
837 return II;
838}
839
840unsigned
841ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
842 llvm::FoldingSetNodeID ID;
843 ID.AddInteger(Key.Kind);
844
845 switch (Key.Kind) {
846 case DeclarationName::Identifier:
847 case DeclarationName::CXXLiteralOperatorName:
848 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
849 break;
850 case DeclarationName::ObjCZeroArgSelector:
851 case DeclarationName::ObjCOneArgSelector:
852 case DeclarationName::ObjCMultiArgSelector:
853 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
854 break;
855 case DeclarationName::CXXOperatorName:
856 ID.AddInteger((OverloadedOperatorKind)Key.Data);
857 break;
858 case DeclarationName::CXXConstructorName:
859 case DeclarationName::CXXDestructorName:
860 case DeclarationName::CXXConversionFunctionName:
861 case DeclarationName::CXXUsingDirective:
862 break;
863 }
864
865 return ID.ComputeHash();
866}
867
868ASTDeclContextNameLookupTrait::internal_key_type
869ASTDeclContextNameLookupTrait::GetInternalKey(
870 const external_key_type& Name) const {
871 DeclNameKey Key;
872 Key.Kind = Name.getNameKind();
873 switch (Name.getNameKind()) {
874 case DeclarationName::Identifier:
875 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
876 break;
877 case DeclarationName::ObjCZeroArgSelector:
878 case DeclarationName::ObjCOneArgSelector:
879 case DeclarationName::ObjCMultiArgSelector:
880 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
881 break;
882 case DeclarationName::CXXOperatorName:
883 Key.Data = Name.getCXXOverloadedOperator();
884 break;
885 case DeclarationName::CXXLiteralOperatorName:
886 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
887 break;
888 case DeclarationName::CXXConstructorName:
889 case DeclarationName::CXXDestructorName:
890 case DeclarationName::CXXConversionFunctionName:
891 case DeclarationName::CXXUsingDirective:
892 Key.Data = 0;
893 break;
894 }
895
896 return Key;
897}
898
899std::pair<unsigned, unsigned>
900ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000901 using namespace llvm::support;
902 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
903 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000904 return std::make_pair(KeyLen, DataLen);
905}
906
907ASTDeclContextNameLookupTrait::internal_key_type
908ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000909 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000910
911 DeclNameKey Key;
912 Key.Kind = (DeclarationName::NameKind)*d++;
913 switch (Key.Kind) {
914 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000915 Key.Data = (uint64_t)Reader.getLocalIdentifier(
916 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000917 break;
918 case DeclarationName::ObjCZeroArgSelector:
919 case DeclarationName::ObjCOneArgSelector:
920 case DeclarationName::ObjCMultiArgSelector:
921 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000922 (uint64_t)Reader.getLocalSelector(
923 F, endian::readNext<uint32_t, little, unaligned>(
924 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000925 break;
926 case DeclarationName::CXXOperatorName:
927 Key.Data = *d++; // OverloadedOperatorKind
928 break;
929 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000930 Key.Data = (uint64_t)Reader.getLocalIdentifier(
931 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000932 break;
933 case DeclarationName::CXXConstructorName:
934 case DeclarationName::CXXDestructorName:
935 case DeclarationName::CXXConversionFunctionName:
936 case DeclarationName::CXXUsingDirective:
937 Key.Data = 0;
938 break;
939 }
940
941 return Key;
942}
943
944ASTDeclContextNameLookupTrait::data_type
945ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
946 const unsigned char* d,
947 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000948 using namespace llvm::support;
949 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000950 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
951 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000952 return std::make_pair(Start, Start + NumDecls);
953}
954
955bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000956 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000957 const std::pair<uint64_t, uint64_t> &Offsets,
958 DeclContextInfo &Info) {
959 SavedStreamPosition SavedPosition(Cursor);
960 // First the lexical decls.
961 if (Offsets.first != 0) {
962 Cursor.JumpToBit(Offsets.first);
963
964 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000965 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000966 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000967 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000968 if (RecCode != DECL_CONTEXT_LEXICAL) {
969 Error("Expected lexical block");
970 return true;
971 }
972
Chris Lattner0e6c9402013-01-20 02:38:54 +0000973 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
974 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000975 }
976
977 // Now the lookup table.
978 if (Offsets.second != 0) {
979 Cursor.JumpToBit(Offsets.second);
980
981 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000982 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000983 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000984 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000985 if (RecCode != DECL_CONTEXT_VISIBLE) {
986 Error("Expected visible lookup table block");
987 return true;
988 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000989 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
990 (const unsigned char *)Blob.data() + Record[0],
991 (const unsigned char *)Blob.data() + sizeof(uint32_t),
992 (const unsigned char *)Blob.data(),
993 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +0000994 }
995
996 return false;
997}
998
999void ASTReader::Error(StringRef Msg) {
1000 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +00001001 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
1002 Diag(diag::note_module_cache_path)
1003 << PP.getHeaderSearchInfo().getModuleCachePath();
1004 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001005}
1006
1007void ASTReader::Error(unsigned DiagID,
1008 StringRef Arg1, StringRef Arg2) {
1009 if (Diags.isDiagnosticInFlight())
1010 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1011 else
1012 Diag(DiagID) << Arg1 << Arg2;
1013}
1014
1015//===----------------------------------------------------------------------===//
1016// Source Manager Deserialization
1017//===----------------------------------------------------------------------===//
1018
1019/// \brief Read the line table in the source manager block.
1020/// \returns true if there was an error.
1021bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001022 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001023 unsigned Idx = 0;
1024 LineTableInfo &LineTable = SourceMgr.getLineTable();
1025
1026 // Parse the file names
1027 std::map<int, int> FileIDs;
1028 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1029 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001030 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001031 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1032 }
1033
1034 // Parse the line entries
1035 std::vector<LineEntry> Entries;
1036 while (Idx < Record.size()) {
1037 int FID = Record[Idx++];
1038 assert(FID >= 0 && "Serialized line entries for non-local file.");
1039 // Remap FileID from 1-based old view.
1040 FID += F.SLocEntryBaseID - 1;
1041
1042 // Extract the line entries
1043 unsigned NumEntries = Record[Idx++];
1044 assert(NumEntries && "Numentries is 00000");
1045 Entries.clear();
1046 Entries.reserve(NumEntries);
1047 for (unsigned I = 0; I != NumEntries; ++I) {
1048 unsigned FileOffset = Record[Idx++];
1049 unsigned LineNo = Record[Idx++];
1050 int FilenameID = FileIDs[Record[Idx++]];
1051 SrcMgr::CharacteristicKind FileKind
1052 = (SrcMgr::CharacteristicKind)Record[Idx++];
1053 unsigned IncludeOffset = Record[Idx++];
1054 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1055 FileKind, IncludeOffset));
1056 }
1057 LineTable.AddEntry(FileID::get(FID), Entries);
1058 }
1059
1060 return false;
1061}
1062
1063/// \brief Read a source manager block
1064bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1065 using namespace SrcMgr;
1066
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001067 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001068
1069 // Set the source-location entry cursor to the current position in
1070 // the stream. This cursor will be used to read the contents of the
1071 // source manager block initially, and then lazily read
1072 // source-location entries as needed.
1073 SLocEntryCursor = F.Stream;
1074
1075 // The stream itself is going to skip over the source manager block.
1076 if (F.Stream.SkipBlock()) {
1077 Error("malformed block record in AST file");
1078 return true;
1079 }
1080
1081 // Enter the source manager block.
1082 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1083 Error("malformed source manager block record in AST file");
1084 return true;
1085 }
1086
1087 RecordData Record;
1088 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001089 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1090
1091 switch (E.Kind) {
1092 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1093 case llvm::BitstreamEntry::Error:
1094 Error("malformed block record in AST file");
1095 return true;
1096 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001097 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001098 case llvm::BitstreamEntry::Record:
1099 // The interesting case.
1100 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001101 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001102
Guy Benyei11169dd2012-12-18 14:30:41 +00001103 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001104 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001105 StringRef Blob;
1106 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001107 default: // Default behavior: ignore.
1108 break;
1109
1110 case SM_SLOC_FILE_ENTRY:
1111 case SM_SLOC_BUFFER_ENTRY:
1112 case SM_SLOC_EXPANSION_ENTRY:
1113 // Once we hit one of the source location entries, we're done.
1114 return false;
1115 }
1116 }
1117}
1118
1119/// \brief If a header file is not found at the path that we expect it to be
1120/// and the PCH file was moved from its original location, try to resolve the
1121/// file by assuming that header+PCH were moved together and the header is in
1122/// the same place relative to the PCH.
1123static std::string
1124resolveFileRelativeToOriginalDir(const std::string &Filename,
1125 const std::string &OriginalDir,
1126 const std::string &CurrDir) {
1127 assert(OriginalDir != CurrDir &&
1128 "No point trying to resolve the file if the PCH dir didn't change");
1129 using namespace llvm::sys;
1130 SmallString<128> filePath(Filename);
1131 fs::make_absolute(filePath);
1132 assert(path::is_absolute(OriginalDir));
1133 SmallString<128> currPCHPath(CurrDir);
1134
1135 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1136 fileDirE = path::end(path::parent_path(filePath));
1137 path::const_iterator origDirI = path::begin(OriginalDir),
1138 origDirE = path::end(OriginalDir);
1139 // Skip the common path components from filePath and OriginalDir.
1140 while (fileDirI != fileDirE && origDirI != origDirE &&
1141 *fileDirI == *origDirI) {
1142 ++fileDirI;
1143 ++origDirI;
1144 }
1145 for (; origDirI != origDirE; ++origDirI)
1146 path::append(currPCHPath, "..");
1147 path::append(currPCHPath, fileDirI, fileDirE);
1148 path::append(currPCHPath, path::filename(Filename));
1149 return currPCHPath.str();
1150}
1151
1152bool ASTReader::ReadSLocEntry(int ID) {
1153 if (ID == 0)
1154 return false;
1155
1156 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1157 Error("source location entry ID out-of-range for AST file");
1158 return true;
1159 }
1160
1161 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1162 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001163 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001164 unsigned BaseOffset = F->SLocEntryBaseOffset;
1165
1166 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001167 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1168 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001169 Error("incorrectly-formatted source location entry in AST file");
1170 return true;
1171 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001172
Guy Benyei11169dd2012-12-18 14:30:41 +00001173 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001174 StringRef Blob;
1175 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001176 default:
1177 Error("incorrectly-formatted source location entry in AST file");
1178 return true;
1179
1180 case SM_SLOC_FILE_ENTRY: {
1181 // We will detect whether a file changed and return 'Failure' for it, but
1182 // we will also try to fail gracefully by setting up the SLocEntry.
1183 unsigned InputID = Record[4];
1184 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001185 const FileEntry *File = IF.getFile();
1186 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001187
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001188 // Note that we only check if a File was returned. If it was out-of-date
1189 // we have complained but we will continue creating a FileID to recover
1190 // gracefully.
1191 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001192 return true;
1193
1194 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1195 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1196 // This is the module's main file.
1197 IncludeLoc = getImportLocation(F);
1198 }
1199 SrcMgr::CharacteristicKind
1200 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1201 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1202 ID, BaseOffset + Record[0]);
1203 SrcMgr::FileInfo &FileInfo =
1204 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1205 FileInfo.NumCreatedFIDs = Record[5];
1206 if (Record[3])
1207 FileInfo.setHasLineDirectives();
1208
1209 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1210 unsigned NumFileDecls = Record[7];
1211 if (NumFileDecls) {
1212 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1213 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1214 NumFileDecls));
1215 }
1216
1217 const SrcMgr::ContentCache *ContentCache
1218 = SourceMgr.getOrCreateContentCache(File,
1219 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1220 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1221 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1222 unsigned Code = SLocEntryCursor.ReadCode();
1223 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001224 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001225
1226 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1227 Error("AST record has invalid code");
1228 return true;
1229 }
1230
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001231 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001232 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001233 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001234 }
1235
1236 break;
1237 }
1238
1239 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001240 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001241 unsigned Offset = Record[0];
1242 SrcMgr::CharacteristicKind
1243 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1244 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001245 if (IncludeLoc.isInvalid() &&
1246 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001247 IncludeLoc = getImportLocation(F);
1248 }
1249 unsigned Code = SLocEntryCursor.ReadCode();
1250 Record.clear();
1251 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001252 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001253
1254 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1255 Error("AST record has invalid code");
1256 return true;
1257 }
1258
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001259 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1260 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001261 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001262 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001263 break;
1264 }
1265
1266 case SM_SLOC_EXPANSION_ENTRY: {
1267 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1268 SourceMgr.createExpansionLoc(SpellingLoc,
1269 ReadSourceLocation(*F, Record[2]),
1270 ReadSourceLocation(*F, Record[3]),
1271 Record[4],
1272 ID,
1273 BaseOffset + Record[0]);
1274 break;
1275 }
1276 }
1277
1278 return false;
1279}
1280
1281std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1282 if (ID == 0)
1283 return std::make_pair(SourceLocation(), "");
1284
1285 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1286 Error("source location entry ID out-of-range for AST file");
1287 return std::make_pair(SourceLocation(), "");
1288 }
1289
1290 // Find which module file this entry lands in.
1291 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001292 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001293 return std::make_pair(SourceLocation(), "");
1294
1295 // FIXME: Can we map this down to a particular submodule? That would be
1296 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001297 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001298}
1299
1300/// \brief Find the location where the module F is imported.
1301SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1302 if (F->ImportLoc.isValid())
1303 return F->ImportLoc;
1304
1305 // Otherwise we have a PCH. It's considered to be "imported" at the first
1306 // location of its includer.
1307 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001308 // Main file is the importer.
1309 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1310 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001311 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001312 return F->ImportedBy[0]->FirstLoc;
1313}
1314
1315/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1316/// specified cursor. Read the abbreviations that are at the top of the block
1317/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001318bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001319 if (Cursor.EnterSubBlock(BlockID)) {
1320 Error("malformed block record in AST file");
1321 return Failure;
1322 }
1323
1324 while (true) {
1325 uint64_t Offset = Cursor.GetCurrentBitNo();
1326 unsigned Code = Cursor.ReadCode();
1327
1328 // We expect all abbrevs to be at the start of the block.
1329 if (Code != llvm::bitc::DEFINE_ABBREV) {
1330 Cursor.JumpToBit(Offset);
1331 return false;
1332 }
1333 Cursor.ReadAbbrevRecord();
1334 }
1335}
1336
Richard Smithe40f2ba2013-08-07 21:41:30 +00001337Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001338 unsigned &Idx) {
1339 Token Tok;
1340 Tok.startToken();
1341 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1342 Tok.setLength(Record[Idx++]);
1343 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1344 Tok.setIdentifierInfo(II);
1345 Tok.setKind((tok::TokenKind)Record[Idx++]);
1346 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1347 return Tok;
1348}
1349
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001350MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001351 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001352
1353 // Keep track of where we are in the stream, then jump back there
1354 // after reading this macro.
1355 SavedStreamPosition SavedPosition(Stream);
1356
1357 Stream.JumpToBit(Offset);
1358 RecordData Record;
1359 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001360 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001361
Guy Benyei11169dd2012-12-18 14:30:41 +00001362 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001363 // Advance to the next record, but if we get to the end of the block, don't
1364 // pop it (removing all the abbreviations from the cursor) since we want to
1365 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001366 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001367 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1368
1369 switch (Entry.Kind) {
1370 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1371 case llvm::BitstreamEntry::Error:
1372 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001373 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001374 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001375 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001376 case llvm::BitstreamEntry::Record:
1377 // The interesting case.
1378 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001379 }
1380
1381 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001382 Record.clear();
1383 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001384 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001385 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001386 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001387 case PP_MACRO_DIRECTIVE_HISTORY:
1388 return Macro;
1389
Guy Benyei11169dd2012-12-18 14:30:41 +00001390 case PP_MACRO_OBJECT_LIKE:
1391 case PP_MACRO_FUNCTION_LIKE: {
1392 // If we already have a macro, that means that we've hit the end
1393 // of the definition of the macro we were looking for. We're
1394 // done.
1395 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001396 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001397
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001398 unsigned NextIndex = 1; // Skip identifier ID.
1399 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001400 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001401 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001402 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001403 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001404 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001405
Guy Benyei11169dd2012-12-18 14:30:41 +00001406 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1407 // Decode function-like macro info.
1408 bool isC99VarArgs = Record[NextIndex++];
1409 bool isGNUVarArgs = Record[NextIndex++];
1410 bool hasCommaPasting = Record[NextIndex++];
1411 MacroArgs.clear();
1412 unsigned NumArgs = Record[NextIndex++];
1413 for (unsigned i = 0; i != NumArgs; ++i)
1414 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1415
1416 // Install function-like macro info.
1417 MI->setIsFunctionLike();
1418 if (isC99VarArgs) MI->setIsC99Varargs();
1419 if (isGNUVarArgs) MI->setIsGNUVarargs();
1420 if (hasCommaPasting) MI->setHasCommaPasting();
1421 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1422 PP.getPreprocessorAllocator());
1423 }
1424
Guy Benyei11169dd2012-12-18 14:30:41 +00001425 // Remember that we saw this macro last so that we add the tokens that
1426 // form its body to it.
1427 Macro = MI;
1428
1429 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1430 Record[NextIndex]) {
1431 // We have a macro definition. Register the association
1432 PreprocessedEntityID
1433 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1434 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001435 PreprocessingRecord::PPEntityID
1436 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1437 MacroDefinition *PPDef =
1438 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1439 if (PPDef)
1440 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001441 }
1442
1443 ++NumMacrosRead;
1444 break;
1445 }
1446
1447 case PP_TOKEN: {
1448 // If we see a TOKEN before a PP_MACRO_*, then the file is
1449 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001450 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001451
John McCallf413f5e2013-05-03 00:10:13 +00001452 unsigned Idx = 0;
1453 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001454 Macro->AddTokenToBody(Tok);
1455 break;
1456 }
1457 }
1458 }
1459}
1460
1461PreprocessedEntityID
1462ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1463 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1464 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1465 assert(I != M.PreprocessedEntityRemap.end()
1466 && "Invalid index into preprocessed entity index remap");
1467
1468 return LocalID + I->second;
1469}
1470
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001471unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1472 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001473}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001474
Guy Benyei11169dd2012-12-18 14:30:41 +00001475HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001476HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1477 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
Richard Smith7ed1bc92014-12-05 22:42:13 +00001478 FE->getName(), /*Imported*/false };
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001479 return ikey;
1480}
Guy Benyei11169dd2012-12-18 14:30:41 +00001481
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001482bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1483 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001484 return false;
1485
Richard Smith7ed1bc92014-12-05 22:42:13 +00001486 if (llvm::sys::path::is_absolute(a.Filename) &&
1487 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001488 return true;
1489
Guy Benyei11169dd2012-12-18 14:30:41 +00001490 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001491 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001492 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1493 if (!Key.Imported)
1494 return FileMgr.getFile(Key.Filename);
1495
1496 std::string Resolved = Key.Filename;
1497 Reader.ResolveImportedPath(M, Resolved);
1498 return FileMgr.getFile(Resolved);
1499 };
1500
1501 const FileEntry *FEA = GetFile(a);
1502 const FileEntry *FEB = GetFile(b);
1503 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001504}
1505
1506std::pair<unsigned, unsigned>
1507HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001508 using namespace llvm::support;
1509 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001510 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001511 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001512}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001513
1514HeaderFileInfoTrait::internal_key_type
1515HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001516 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001517 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001518 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1519 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001520 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001521 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001522 return ikey;
1523}
1524
Guy Benyei11169dd2012-12-18 14:30:41 +00001525HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001526HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001527 unsigned DataLen) {
1528 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001529 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001530 HeaderFileInfo HFI;
1531 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001532 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1533 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001534 HFI.isImport = (Flags >> 5) & 0x01;
1535 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1536 HFI.DirInfo = (Flags >> 2) & 0x03;
1537 HFI.Resolved = (Flags >> 1) & 0x01;
1538 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001539 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1540 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1541 M, endian::readNext<uint32_t, little, unaligned>(d));
1542 if (unsigned FrameworkOffset =
1543 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001544 // The framework offset is 1 greater than the actual offset,
1545 // since 0 is used as an indicator for "no framework name".
1546 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1547 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1548 }
1549
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001550 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001551 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001552 if (LocalSMID) {
1553 // This header is part of a module. Associate it with the module to enable
1554 // implicit module import.
1555 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1556 Module *Mod = Reader.getSubmodule(GlobalSMID);
1557 HFI.isModuleHeader = true;
1558 FileManager &FileMgr = Reader.getFileManager();
1559 ModuleMap &ModMap =
1560 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001561 // FIXME: This information should be propagated through the
1562 // SUBMODULE_HEADER etc records rather than from here.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001563 // FIXME: We don't ever mark excluded headers.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001564 std::string Filename = key.Filename;
1565 if (key.Imported)
1566 Reader.ResolveImportedPath(M, Filename);
1567 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Hans Wennborg0101b542014-12-02 02:13:09 +00001568 ModMap.addHeader(Mod, H, HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001569 }
1570 }
1571
Guy Benyei11169dd2012-12-18 14:30:41 +00001572 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1573 (void)End;
1574
1575 // This HeaderFileInfo was externally loaded.
1576 HFI.External = true;
1577 return HFI;
1578}
1579
Richard Smithd7329392015-04-21 21:46:32 +00001580void ASTReader::addPendingMacro(IdentifierInfo *II,
1581 ModuleFile *M,
1582 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001583 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1584 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001585}
1586
1587void ASTReader::ReadDefinedMacros() {
1588 // Note that we are loading defined macros.
1589 Deserializing Macros(this);
1590
1591 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1592 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001593 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001594
1595 // If there was no preprocessor block, skip this file.
1596 if (!MacroCursor.getBitStreamReader())
1597 continue;
1598
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001599 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001600 Cursor.JumpToBit((*I)->MacroStartOffset);
1601
1602 RecordData Record;
1603 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001604 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1605
1606 switch (E.Kind) {
1607 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1608 case llvm::BitstreamEntry::Error:
1609 Error("malformed block record in AST file");
1610 return;
1611 case llvm::BitstreamEntry::EndBlock:
1612 goto NextCursor;
1613
1614 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001615 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001616 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001617 default: // Default behavior: ignore.
1618 break;
1619
1620 case PP_MACRO_OBJECT_LIKE:
1621 case PP_MACRO_FUNCTION_LIKE:
1622 getLocalIdentifier(**I, Record[0]);
1623 break;
1624
1625 case PP_TOKEN:
1626 // Ignore tokens.
1627 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001628 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001629 break;
1630 }
1631 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001632 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001633 }
1634}
1635
1636namespace {
1637 /// \brief Visitor class used to look up identifirs in an AST file.
1638 class IdentifierLookupVisitor {
1639 StringRef Name;
1640 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001641 unsigned &NumIdentifierLookups;
1642 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001643 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001644
Guy Benyei11169dd2012-12-18 14:30:41 +00001645 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001646 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1647 unsigned &NumIdentifierLookups,
1648 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001649 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001650 NumIdentifierLookups(NumIdentifierLookups),
1651 NumIdentifierLookupHits(NumIdentifierLookupHits),
1652 Found()
1653 {
1654 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001655
1656 static bool visit(ModuleFile &M, void *UserData) {
1657 IdentifierLookupVisitor *This
1658 = static_cast<IdentifierLookupVisitor *>(UserData);
1659
1660 // If we've already searched this module file, skip it now.
1661 if (M.Generation <= This->PriorGeneration)
1662 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001663
Guy Benyei11169dd2012-12-18 14:30:41 +00001664 ASTIdentifierLookupTable *IdTable
1665 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1666 if (!IdTable)
1667 return false;
1668
1669 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1670 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001671 ++This->NumIdentifierLookups;
1672 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001673 if (Pos == IdTable->end())
1674 return false;
1675
1676 // Dereferencing the iterator has the effect of building the
1677 // IdentifierInfo node and populating it with the various
1678 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001679 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001680 This->Found = *Pos;
1681 return true;
1682 }
1683
1684 // \brief Retrieve the identifier info found within the module
1685 // files.
1686 IdentifierInfo *getIdentifierInfo() const { return Found; }
1687 };
1688}
1689
1690void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1691 // Note that we are loading an identifier.
1692 Deserializing AnIdentifier(this);
1693
1694 unsigned PriorGeneration = 0;
1695 if (getContext().getLangOpts().Modules)
1696 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001697
1698 // If there is a global index, look there first to determine which modules
1699 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001700 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001701 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001702 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001703 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1704 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001705 }
1706 }
1707
Douglas Gregor7211ac12013-01-25 23:32:03 +00001708 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001709 NumIdentifierLookups,
1710 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001711 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001712 markIdentifierUpToDate(&II);
1713}
1714
1715void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1716 if (!II)
1717 return;
1718
1719 II->setOutOfDate(false);
1720
1721 // Update the generation for this identifier.
1722 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001723 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001724}
1725
Richard Smith49f906a2014-03-01 00:08:04 +00001726struct ASTReader::ModuleMacroInfo {
Richard Smith713369b2015-04-23 20:40:50 +00001727 ModuleMacro *MM;
Richard Smith49f906a2014-03-01 00:08:04 +00001728 // FIXME: Remove this.
1729 ModuleFile *F;
1730
Richard Smith713369b2015-04-23 20:40:50 +00001731 bool isDefine() const { return MM->getMacroInfo(); }
Richard Smith49f906a2014-03-01 00:08:04 +00001732
Richard Smith713369b2015-04-23 20:40:50 +00001733 ArrayRef<ModuleMacro *> getOverriddenMacros() const {
1734 return MM->overrides();
1735 }
Richard Smith49f906a2014-03-01 00:08:04 +00001736
Richard Smithdaa69e02014-07-25 04:40:03 +00001737 MacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
Richard Smith713369b2015-04-23 20:40:50 +00001738 if (auto *MI = MM->getMacroInfo())
1739 return PP.AllocateDefMacroDirective(MI, ImportLoc, MM);
1740 return PP.AllocateUndefMacroDirective(ImportLoc, MM);
Richard Smith49f906a2014-03-01 00:08:04 +00001741 }
1742};
1743
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001744void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1745 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001746 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001747
1748 BitstreamCursor &Cursor = M.MacroCursor;
1749 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001750 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001751
Richard Smith713369b2015-04-23 20:40:50 +00001752 struct ModuleMacroRecord {
1753 SubmoduleID SubModID;
1754 MacroInfo *MI;
1755 SmallVector<SubmoduleID, 8> Overrides;
1756 };
1757 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001758
Richard Smithd7329392015-04-21 21:46:32 +00001759 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1760 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1761 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001762 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001763 while (true) {
1764 llvm::BitstreamEntry Entry =
1765 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1766 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1767 Error("malformed block record in AST file");
1768 return;
1769 }
1770
1771 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001772 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001773 case PP_MACRO_DIRECTIVE_HISTORY:
1774 break;
1775
1776 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001777 ModuleMacros.push_back(ModuleMacroRecord());
1778 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001779 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1780 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001781 for (int I = 2, N = Record.size(); I != N; ++I)
1782 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001783 continue;
1784 }
1785
1786 default:
1787 Error("malformed block record in AST file");
1788 return;
1789 }
1790
1791 // We found the macro directive history; that's the last record
1792 // for this macro.
1793 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001794 }
1795
Richard Smithd7329392015-04-21 21:46:32 +00001796 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001797 {
1798 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001799 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001800 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001801 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001802 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001803 Module *Mod = getSubmodule(ModID);
1804 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001805 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001806 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001807 }
1808
1809 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001810 Module *Owner = getSubmodule(MMR.SubModID);
1811 auto *MM = PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001812 if (!Inserted)
1813 continue;
1814
Richard Smith713369b2015-04-23 20:40:50 +00001815 ModuleMacroInfo MMI = { MM, &M };
Richard Smithe56c8bc2015-04-22 00:26:11 +00001816 if (Owner->NameVisibility == Module::Hidden) {
1817 // Macros in the owning module are hidden. Just remember this macro to
1818 // install if we make this module visible.
1819 HiddenNamesMap[Owner].HiddenMacros.insert(
Richard Smith5dbef922015-04-22 02:09:43 +00001820 std::make_pair(II, new (Context) ModuleMacroInfo(MMI)));
Richard Smithe56c8bc2015-04-22 00:26:11 +00001821 } else {
1822 installImportedMacro(II, MMI, Owner);
1823 }
Richard Smithd7329392015-04-21 21:46:32 +00001824 }
1825 }
1826
1827 // Don't read the directive history for a module; we don't have anywhere
1828 // to put it.
1829 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1830 return;
1831
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001832 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001833 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001834 unsigned Idx = 0, N = Record.size();
1835 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001836 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001837 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001838 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1839 switch (K) {
1840 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001841 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smithdaa69e02014-07-25 04:40:03 +00001842 bool IsAmbiguous = Record[Idx++];
Richard Smith713369b2015-04-23 20:40:50 +00001843 ModuleMacro *MM = nullptr;
1844 if (SubmoduleID ImportedFrom = getGlobalSubmoduleID(M, Record[Idx++]))
1845 MM = PP.getModuleMacro(getSubmodule(ImportedFrom), II);
1846 DefMacroDirective *DefMD = PP.AllocateDefMacroDirective(MI, Loc, MM);
Richard Smithdaa69e02014-07-25 04:40:03 +00001847 DefMD->setAmbiguous(IsAmbiguous);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001848 MD = DefMD;
1849 break;
1850 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001851 case MacroDirective::MD_Undefine: {
Richard Smith713369b2015-04-23 20:40:50 +00001852 ModuleMacro *MM = nullptr;
1853 if (SubmoduleID ImportedFrom = getGlobalSubmoduleID(M, Record[Idx++]))
1854 MM = PP.getModuleMacro(getSubmodule(ImportedFrom), II);
1855 MD = PP.AllocateUndefMacroDirective(Loc, MM);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001856 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001857 }
1858 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001859 bool isPublic = Record[Idx++];
1860 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1861 break;
1862 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001863
1864 if (!Latest)
1865 Latest = MD;
1866 if (Earliest)
1867 Earliest->setPrevious(MD);
1868 Earliest = MD;
1869 }
1870
1871 PP.setLoadedMacroDirective(II, Latest);
1872}
1873
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001874/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001875/// modules.
1876static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001877 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001878 assert(PrevMI && NewMI);
Craig Toppera13603a2014-05-22 05:54:18 +00001879 Module *PrevOwner = nullptr;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001880 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1881 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001882 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001883 return false;
Chandler Carruthc2132d82015-03-13 08:29:54 +00001884 SourceManager &SrcMgr = Reader.getSourceManager();
1885 bool PrevInSystem = (PrevOwner && PrevOwner->IsSystem) ||
1886 SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1887 bool NewInSystem = (NewOwner && NewOwner->IsSystem) ||
1888 SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
Douglas Gregor5e461192013-06-07 22:56:11 +00001889 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001890}
1891
Richard Smith49f906a2014-03-01 00:08:04 +00001892void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001893 SourceLocation ImportLoc,
Richard Smith49f906a2014-03-01 00:08:04 +00001894 AmbiguousMacros &Ambig,
Richard Smith713369b2015-04-23 20:40:50 +00001895 ArrayRef<ModuleMacro *> Overrides) {
1896 for (ModuleMacro *Overridden : Overrides) {
1897 Module *Owner = Overridden->getOwningModule();
Richard Smith49f906a2014-03-01 00:08:04 +00001898 // If this macro is not yet visible, remove it from the hidden names list.
Richard Smithbb853c72014-08-13 01:23:33 +00001899 // It won't be there if we're in the middle of making the owner visible.
Richard Smithbb853c72014-08-13 01:23:33 +00001900 auto HiddenIt = HiddenNamesMap.find(Owner);
1901 if (HiddenIt != HiddenNamesMap.end()) {
1902 HiddenNames &Hidden = HiddenIt->second;
1903 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1904 if (HI != Hidden.HiddenMacros.end()) {
1905 // Register the macro now so we don't lose it when we re-export.
1906 PP.appendMacroDirective(II, HI->second->import(PP, ImportLoc));
Richard Smithdaa69e02014-07-25 04:40:03 +00001907
Richard Smith713369b2015-04-23 20:40:50 +00001908 auto SubOverrides = HI->second->getOverriddenMacros();
Richard Smithbb853c72014-08-13 01:23:33 +00001909 Hidden.HiddenMacros.erase(HI);
1910 removeOverriddenMacros(II, ImportLoc, Ambig, SubOverrides);
1911 }
Richard Smith49f906a2014-03-01 00:08:04 +00001912 }
1913
1914 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001915 Ambig.erase(
1916 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
Richard Smith713369b2015-04-23 20:40:50 +00001917 return getSubmodule(MD->getInfo()->getOwningModuleID()) == Owner;
Richard Smithbb29e512014-03-06 00:33:23 +00001918 }),
1919 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001920 }
1921}
1922
1923ASTReader::AmbiguousMacros *
1924ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001925 SourceLocation ImportLoc,
Richard Smith713369b2015-04-23 20:40:50 +00001926 ArrayRef<ModuleMacro *> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001927 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001928 if (!Prev && Overrides.empty())
Craig Toppera13603a2014-05-22 05:54:18 +00001929 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001930
Craig Toppera13603a2014-05-22 05:54:18 +00001931 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective()
1932 : nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001933 if (PrevDef && PrevDef->isAmbiguous()) {
1934 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1935 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1936 Ambig.push_back(PrevDef);
1937
Richard Smithdaa69e02014-07-25 04:40:03 +00001938 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001939
1940 if (!Ambig.empty())
1941 return &Ambig;
1942
1943 AmbiguousMacroDefs.erase(II);
1944 } else {
1945 // There's no ambiguity yet. Maybe we're introducing one.
Benjamin Kramer834652a2014-05-03 18:44:26 +00001946 AmbiguousMacros Ambig;
Richard Smith49f906a2014-03-01 00:08:04 +00001947 if (PrevDef)
1948 Ambig.push_back(PrevDef);
1949
Richard Smithdaa69e02014-07-25 04:40:03 +00001950 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001951
1952 if (!Ambig.empty()) {
1953 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
Benjamin Kramer834652a2014-05-03 18:44:26 +00001954 std::swap(Result, Ambig);
Richard Smith49f906a2014-03-01 00:08:04 +00001955 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001956 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001957 }
Richard Smith49f906a2014-03-01 00:08:04 +00001958
1959 // We ended up with no ambiguity.
Craig Toppera13603a2014-05-22 05:54:18 +00001960 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001961}
1962
Richard Smithe56c8bc2015-04-22 00:26:11 +00001963void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo &MMI,
Richard Smithdaa69e02014-07-25 04:40:03 +00001964 Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00001965 assert(II && Owner);
1966
1967 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
Richard Smith49f906a2014-03-01 00:08:04 +00001968
Benjamin Kramer834652a2014-05-03 18:44:26 +00001969 AmbiguousMacros *Prev =
Richard Smith713369b2015-04-23 20:40:50 +00001970 removeOverriddenMacros(II, ImportLoc, MMI.getOverriddenMacros());
Richard Smith49f906a2014-03-01 00:08:04 +00001971
Richard Smith49f906a2014-03-01 00:08:04 +00001972 // Create a synthetic macro definition corresponding to the import (or null
1973 // if this was an undefinition of the macro).
Richard Smithe56c8bc2015-04-22 00:26:11 +00001974 MacroDirective *Imported = MMI.import(PP, ImportLoc);
Richard Smithdaa69e02014-07-25 04:40:03 +00001975 DefMacroDirective *MD = dyn_cast<DefMacroDirective>(Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00001976
1977 // If there's no ambiguity, just install the macro.
1978 if (!Prev) {
Richard Smithdaa69e02014-07-25 04:40:03 +00001979 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00001980 return;
1981 }
1982 assert(!Prev->empty());
1983
1984 if (!MD) {
1985 // We imported a #undef that didn't remove all prior definitions. The most
1986 // recent prior definition remains, and we install it in the place of the
Richard Smithdaa69e02014-07-25 04:40:03 +00001987 // imported directive, as if by a local #pragma pop_macro.
Richard Smith49f906a2014-03-01 00:08:04 +00001988 MacroInfo *NewMI = Prev->back()->getInfo();
1989 Prev->pop_back();
Richard Smithdaa69e02014-07-25 04:40:03 +00001990 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc);
1991
1992 // Install our #undef first so that we don't lose track of it. We'll replace
1993 // this with whichever macro definition ends up winning.
1994 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00001995 }
1996
1997 // We're introducing a macro definition that creates or adds to an ambiguity.
1998 // We can resolve that ambiguity if this macro is token-for-token identical to
1999 // all of the existing definitions.
2000 MacroInfo *NewMI = MD->getInfo();
2001 assert(NewMI && "macro definition with no MacroInfo?");
2002 while (!Prev->empty()) {
2003 MacroInfo *PrevMI = Prev->back()->getInfo();
2004 assert(PrevMI && "macro definition with no MacroInfo?");
2005
2006 // Before marking the macros as ambiguous, check if this is a case where
2007 // both macros are in system headers. If so, we trust that the system
2008 // did not get it wrong. This also handles cases where Clang's own
2009 // headers have a different spelling of certain system macros:
2010 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
2011 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
2012 //
2013 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
2014 // overrides the system limits.h's macros, so there's no conflict here.
2015 if (NewMI != PrevMI &&
2016 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
2017 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
2018 break;
2019
2020 // The previous definition is the same as this one (or both are defined in
2021 // system modules so we can assume they're equivalent); we don't need to
2022 // track it any more.
2023 Prev->pop_back();
2024 }
2025
2026 if (!Prev->empty())
2027 MD->setAmbiguous(true);
2028
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002029 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002030}
2031
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002032ASTReader::InputFileInfo
2033ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002034 // Go find this input file.
2035 BitstreamCursor &Cursor = F.InputFilesCursor;
2036 SavedStreamPosition SavedPosition(Cursor);
2037 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2038
2039 unsigned Code = Cursor.ReadCode();
2040 RecordData Record;
2041 StringRef Blob;
2042
2043 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2044 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2045 "invalid record type for input file");
2046 (void)Result;
2047
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002048 std::string Filename;
2049 off_t StoredSize;
2050 time_t StoredTime;
2051 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002052
Ben Langmuir198c1682014-03-07 07:27:49 +00002053 assert(Record[0] == ID && "Bogus stored ID or offset");
2054 StoredSize = static_cast<off_t>(Record[1]);
2055 StoredTime = static_cast<time_t>(Record[2]);
2056 Overridden = static_cast<bool>(Record[3]);
2057 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002058 ResolveImportedPath(F, Filename);
2059
Hans Wennborg73945142014-03-14 17:45:06 +00002060 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
2061 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002062}
2063
2064std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002065 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00002066}
2067
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002068InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002069 // If this ID is bogus, just return an empty input file.
2070 if (ID == 0 || ID > F.InputFilesLoaded.size())
2071 return InputFile();
2072
2073 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002074 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002075 return F.InputFilesLoaded[ID-1];
2076
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002077 if (F.InputFilesLoaded[ID-1].isNotFound())
2078 return InputFile();
2079
Guy Benyei11169dd2012-12-18 14:30:41 +00002080 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002081 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002082 SavedStreamPosition SavedPosition(Cursor);
2083 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2084
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002085 InputFileInfo FI = readInputFileInfo(F, ID);
2086 off_t StoredSize = FI.StoredSize;
2087 time_t StoredTime = FI.StoredTime;
2088 bool Overridden = FI.Overridden;
2089 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002090
Ben Langmuir198c1682014-03-07 07:27:49 +00002091 const FileEntry *File
2092 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
2093 : FileMgr.getFile(Filename, /*OpenFile=*/false);
2094
2095 // If we didn't find the file, resolve it relative to the
2096 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002097 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002098 F.OriginalDir != CurrentDir) {
2099 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2100 F.OriginalDir,
2101 CurrentDir);
2102 if (!Resolved.empty())
2103 File = FileMgr.getFile(Resolved);
2104 }
2105
2106 // For an overridden file, create a virtual file with the stored
2107 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00002108 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002109 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2110 }
2111
Craig Toppera13603a2014-05-22 05:54:18 +00002112 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002113 if (Complain) {
2114 std::string ErrorStr = "could not find file '";
2115 ErrorStr += Filename;
2116 ErrorStr += "' referenced by AST file";
2117 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00002118 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002119 // Record that we didn't find the file.
2120 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2121 return InputFile();
2122 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002123
Ben Langmuir198c1682014-03-07 07:27:49 +00002124 // Check if there was a request to override the contents of the file
2125 // that was part of the precompiled header. Overridding such a file
2126 // can lead to problems when lexing using the source locations from the
2127 // PCH.
2128 SourceManager &SM = getSourceManager();
2129 if (!Overridden && SM.isFileOverridden(File)) {
2130 if (Complain)
2131 Error(diag::err_fe_pch_file_overridden, Filename);
2132 // After emitting the diagnostic, recover by disabling the override so
2133 // that the original file will be used.
2134 SM.disableFileContentsOverride(File);
2135 // The FileEntry is a virtual file entry with the size of the contents
2136 // that would override the original contents. Set it to the original's
2137 // size/time.
2138 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2139 StoredSize, StoredTime);
2140 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002141
Ben Langmuir198c1682014-03-07 07:27:49 +00002142 bool IsOutOfDate = false;
2143
2144 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002145 if (!Overridden && //
2146 (StoredSize != File->getSize() ||
2147#if defined(LLVM_ON_WIN32)
2148 false
2149#else
Ben Langmuir198c1682014-03-07 07:27:49 +00002150 // In our regression testing, the Windows file system seems to
2151 // have inconsistent modification times that sometimes
2152 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00002153 //
2154 // This also happens in networked file systems, so disable this
2155 // check if validation is disabled or if we have an explicitly
2156 // built PCM file.
2157 //
2158 // FIXME: Should we also do this for PCH files? They could also
2159 // reasonably get shared across a network during a distributed build.
2160 (StoredTime != File->getModificationTime() && !DisableValidation &&
2161 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00002162#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002163 )) {
2164 if (Complain) {
2165 // Build a list of the PCH imports that got us here (in reverse).
2166 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2167 while (ImportStack.back()->ImportedBy.size() > 0)
2168 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002169
Ben Langmuir198c1682014-03-07 07:27:49 +00002170 // The top-level PCH is stale.
2171 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2172 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002173
Ben Langmuir198c1682014-03-07 07:27:49 +00002174 // Print the import stack.
2175 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2176 Diag(diag::note_pch_required_by)
2177 << Filename << ImportStack[0]->FileName;
2178 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002179 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002180 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002181 }
2182
Ben Langmuir198c1682014-03-07 07:27:49 +00002183 if (!Diags.isDiagnosticInFlight())
2184 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002185 }
2186
Ben Langmuir198c1682014-03-07 07:27:49 +00002187 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002188 }
2189
Ben Langmuir198c1682014-03-07 07:27:49 +00002190 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2191
2192 // Note that we've loaded this input file.
2193 F.InputFilesLoaded[ID-1] = IF;
2194 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002195}
2196
Richard Smith7ed1bc92014-12-05 22:42:13 +00002197/// \brief If we are loading a relocatable PCH or module file, and the filename
2198/// is not an absolute path, add the system or module root to the beginning of
2199/// the file name.
2200void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2201 // Resolve relative to the base directory, if we have one.
2202 if (!M.BaseDirectory.empty())
2203 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002204}
2205
Richard Smith7ed1bc92014-12-05 22:42:13 +00002206void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002207 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2208 return;
2209
Richard Smith7ed1bc92014-12-05 22:42:13 +00002210 SmallString<128> Buffer;
2211 llvm::sys::path::append(Buffer, Prefix, Filename);
2212 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002213}
2214
2215ASTReader::ASTReadResult
2216ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002217 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002218 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002219 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002220 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002221
2222 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2223 Error("malformed block record in AST file");
2224 return Failure;
2225 }
2226
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002227 // Should we allow the configuration of the module file to differ from the
2228 // configuration of the current translation unit in a compatible way?
2229 //
2230 // FIXME: Allow this for files explicitly specified with -include-pch too.
2231 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2232
Guy Benyei11169dd2012-12-18 14:30:41 +00002233 // Read all of the records and blocks in the control block.
2234 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002235 unsigned NumInputs = 0;
2236 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002237 while (1) {
2238 llvm::BitstreamEntry Entry = Stream.advance();
2239
2240 switch (Entry.Kind) {
2241 case llvm::BitstreamEntry::Error:
2242 Error("malformed block record in AST file");
2243 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002244 case llvm::BitstreamEntry::EndBlock: {
2245 // Validate input files.
2246 const HeaderSearchOptions &HSOpts =
2247 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002248
Richard Smitha1825302014-10-23 22:18:29 +00002249 // All user input files reside at the index range [0, NumUserInputs), and
2250 // system input files reside at [NumUserInputs, NumInputs).
Ben Langmuiracb803e2014-11-10 22:13:10 +00002251 if (!DisableValidation) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002252 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002253
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002254 // If we are reading a module, we will create a verification timestamp,
2255 // so we verify all input files. Otherwise, verify only user input
2256 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002257
2258 unsigned N = NumUserInputs;
2259 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002260 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002261 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002262 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002263 N = NumInputs;
2264
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002265 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002266 InputFile IF = getInputFile(F, I+1, Complain);
2267 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002268 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002269 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002270 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002271
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002272 if (Listener)
2273 Listener->visitModuleFile(F.FileName);
2274
Ben Langmuircb69b572014-03-07 06:40:32 +00002275 if (Listener && Listener->needsInputFileVisitation()) {
2276 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2277 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002278 for (unsigned I = 0; I < N; ++I) {
2279 bool IsSystem = I >= NumUserInputs;
2280 InputFileInfo FI = readInputFileInfo(F, I+1);
2281 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2282 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002283 }
2284
Guy Benyei11169dd2012-12-18 14:30:41 +00002285 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002286 }
2287
Chris Lattnere7b154b2013-01-19 21:39:22 +00002288 case llvm::BitstreamEntry::SubBlock:
2289 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002290 case INPUT_FILES_BLOCK_ID:
2291 F.InputFilesCursor = Stream;
2292 if (Stream.SkipBlock() || // Skip with the main cursor
2293 // Read the abbreviations
2294 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2295 Error("malformed block record in AST file");
2296 return Failure;
2297 }
2298 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002299
Guy Benyei11169dd2012-12-18 14:30:41 +00002300 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002301 if (Stream.SkipBlock()) {
2302 Error("malformed block record in AST file");
2303 return Failure;
2304 }
2305 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002306 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002307
2308 case llvm::BitstreamEntry::Record:
2309 // The interesting case.
2310 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002311 }
2312
2313 // Read and process a record.
2314 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002315 StringRef Blob;
2316 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002317 case METADATA: {
2318 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2319 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002320 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2321 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002322 return VersionMismatch;
2323 }
2324
2325 bool hasErrors = Record[5];
2326 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2327 Diag(diag::err_pch_with_compiler_errors);
2328 return HadErrors;
2329 }
2330
2331 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002332 // Relative paths in a relocatable PCH are relative to our sysroot.
2333 if (F.RelocatablePCH)
2334 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002335
2336 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002337 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002338 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2339 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002340 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002341 return VersionMismatch;
2342 }
2343 break;
2344 }
2345
Ben Langmuir487ea142014-10-23 18:05:36 +00002346 case SIGNATURE:
2347 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2348 F.Signature = Record[0];
2349 break;
2350
Guy Benyei11169dd2012-12-18 14:30:41 +00002351 case IMPORTS: {
2352 // Load each of the imported PCH files.
2353 unsigned Idx = 0, N = Record.size();
2354 while (Idx < N) {
2355 // Read information about the AST file.
2356 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2357 // The import location will be the local one for now; we will adjust
2358 // all import locations of module imports after the global source
2359 // location info are setup.
2360 SourceLocation ImportLoc =
2361 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002362 off_t StoredSize = (off_t)Record[Idx++];
2363 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002364 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002365 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002366
2367 // Load the AST file.
2368 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00002369 StoredSize, StoredModTime, StoredSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00002370 ClientLoadCapabilities)) {
2371 case Failure: return Failure;
2372 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002373 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002374 case OutOfDate: return OutOfDate;
2375 case VersionMismatch: return VersionMismatch;
2376 case ConfigurationMismatch: return ConfigurationMismatch;
2377 case HadErrors: return HadErrors;
2378 case Success: break;
2379 }
2380 }
2381 break;
2382 }
2383
Richard Smith7f330cd2015-03-18 01:42:29 +00002384 case KNOWN_MODULE_FILES:
2385 break;
2386
Guy Benyei11169dd2012-12-18 14:30:41 +00002387 case LANGUAGE_OPTIONS: {
2388 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002389 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002390 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002391 ParseLanguageOptions(Record, Complain, *Listener,
2392 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002393 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002394 return ConfigurationMismatch;
2395 break;
2396 }
2397
2398 case TARGET_OPTIONS: {
2399 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2400 if (Listener && &F == *ModuleMgr.begin() &&
Chandler Carruth0d745bc2015-03-14 04:47:43 +00002401 ParseTargetOptions(Record, Complain, *Listener,
2402 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002403 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002404 return ConfigurationMismatch;
2405 break;
2406 }
2407
2408 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002409 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002410 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002411 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002412 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002413 !DisableValidation)
2414 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002415 break;
2416 }
2417
2418 case FILE_SYSTEM_OPTIONS: {
2419 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2420 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002421 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002422 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002423 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002424 return ConfigurationMismatch;
2425 break;
2426 }
2427
2428 case HEADER_SEARCH_OPTIONS: {
2429 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2430 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002431 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002432 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002433 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002434 return ConfigurationMismatch;
2435 break;
2436 }
2437
2438 case PREPROCESSOR_OPTIONS: {
2439 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2440 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002441 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002442 ParsePreprocessorOptions(Record, Complain, *Listener,
2443 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002444 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002445 return ConfigurationMismatch;
2446 break;
2447 }
2448
2449 case ORIGINAL_FILE:
2450 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002451 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002452 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002453 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002454 break;
2455
2456 case ORIGINAL_FILE_ID:
2457 F.OriginalSourceFileID = FileID::get(Record[0]);
2458 break;
2459
2460 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002461 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002462 break;
2463
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002464 case MODULE_NAME:
2465 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002466 if (Listener)
2467 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002468 break;
2469
Richard Smith223d3f22014-12-06 03:21:08 +00002470 case MODULE_DIRECTORY: {
2471 assert(!F.ModuleName.empty() &&
2472 "MODULE_DIRECTORY found before MODULE_NAME");
2473 // If we've already loaded a module map file covering this module, we may
2474 // have a better path for it (relative to the current build).
2475 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2476 if (M && M->Directory) {
2477 // If we're implicitly loading a module, the base directory can't
2478 // change between the build and use.
2479 if (F.Kind != MK_ExplicitModule) {
2480 const DirectoryEntry *BuildDir =
2481 PP.getFileManager().getDirectory(Blob);
2482 if (!BuildDir || BuildDir != M->Directory) {
2483 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2484 Diag(diag::err_imported_module_relocated)
2485 << F.ModuleName << Blob << M->Directory->getName();
2486 return OutOfDate;
2487 }
2488 }
2489 F.BaseDirectory = M->Directory->getName();
2490 } else {
2491 F.BaseDirectory = Blob;
2492 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002493 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002494 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002495
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002496 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002497 if (ASTReadResult Result =
2498 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2499 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002500 break;
2501
Guy Benyei11169dd2012-12-18 14:30:41 +00002502 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002503 NumInputs = Record[0];
2504 NumUserInputs = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00002505 F.InputFileOffsets = (const uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002506 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002507 break;
2508 }
2509 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002510}
2511
Ben Langmuir2c9af442014-04-10 17:57:43 +00002512ASTReader::ASTReadResult
2513ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002514 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002515
2516 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2517 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002518 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002519 }
2520
2521 // Read all of the records and blocks for the AST file.
2522 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002523 while (1) {
2524 llvm::BitstreamEntry Entry = Stream.advance();
2525
2526 switch (Entry.Kind) {
2527 case llvm::BitstreamEntry::Error:
2528 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002529 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002530 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002531 // Outside of C++, we do not store a lookup map for the translation unit.
2532 // Instead, mark it as needing a lookup map to be built if this module
2533 // contains any declarations lexically within it (which it always does!).
2534 // This usually has no cost, since we very rarely need the lookup map for
2535 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002536 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002537 if (DC->hasExternalLexicalStorage() &&
2538 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002539 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002540
Ben Langmuir2c9af442014-04-10 17:57:43 +00002541 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002542 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002543 case llvm::BitstreamEntry::SubBlock:
2544 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002545 case DECLTYPES_BLOCK_ID:
2546 // We lazily load the decls block, but we want to set up the
2547 // DeclsCursor cursor to point into it. Clone our current bitcode
2548 // cursor to it, enter the block and read the abbrevs in that block.
2549 // With the main cursor, we just skip over it.
2550 F.DeclsCursor = Stream;
2551 if (Stream.SkipBlock() || // Skip with the main cursor.
2552 // Read the abbrevs.
2553 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2554 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002555 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002556 }
2557 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002558
Guy Benyei11169dd2012-12-18 14:30:41 +00002559 case PREPROCESSOR_BLOCK_ID:
2560 F.MacroCursor = Stream;
2561 if (!PP.getExternalSource())
2562 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002563
Guy Benyei11169dd2012-12-18 14:30:41 +00002564 if (Stream.SkipBlock() ||
2565 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2566 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002567 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002568 }
2569 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2570 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002571
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 case PREPROCESSOR_DETAIL_BLOCK_ID:
2573 F.PreprocessorDetailCursor = Stream;
2574 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002575 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002576 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002577 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002578 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002579 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002580 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002581 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2582
Guy Benyei11169dd2012-12-18 14:30:41 +00002583 if (!PP.getPreprocessingRecord())
2584 PP.createPreprocessingRecord();
2585 if (!PP.getPreprocessingRecord()->getExternalSource())
2586 PP.getPreprocessingRecord()->SetExternalSource(*this);
2587 break;
2588
2589 case SOURCE_MANAGER_BLOCK_ID:
2590 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002591 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002592 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002593
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002595 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2596 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002597 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002598
Guy Benyei11169dd2012-12-18 14:30:41 +00002599 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002600 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002601 if (Stream.SkipBlock() ||
2602 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2603 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002604 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002605 }
2606 CommentsCursors.push_back(std::make_pair(C, &F));
2607 break;
2608 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002609
Guy Benyei11169dd2012-12-18 14:30:41 +00002610 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002611 if (Stream.SkipBlock()) {
2612 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002613 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002614 }
2615 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002616 }
2617 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002618
2619 case llvm::BitstreamEntry::Record:
2620 // The interesting case.
2621 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002622 }
2623
2624 // Read and process a record.
2625 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002626 StringRef Blob;
2627 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002628 default: // Default behavior: ignore.
2629 break;
2630
2631 case TYPE_OFFSET: {
2632 if (F.LocalNumTypes != 0) {
2633 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002634 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002636 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002637 F.LocalNumTypes = Record[0];
2638 unsigned LocalBaseTypeIndex = Record[1];
2639 F.BaseTypeIndex = getTotalNumTypes();
2640
2641 if (F.LocalNumTypes > 0) {
2642 // Introduce the global -> local mapping for types within this module.
2643 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2644
2645 // Introduce the local -> global mapping for types within this module.
2646 F.TypeRemap.insertOrReplace(
2647 std::make_pair(LocalBaseTypeIndex,
2648 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002649
2650 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002651 }
2652 break;
2653 }
2654
2655 case DECL_OFFSET: {
2656 if (F.LocalNumDecls != 0) {
2657 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002658 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002659 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002660 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 F.LocalNumDecls = Record[0];
2662 unsigned LocalBaseDeclID = Record[1];
2663 F.BaseDeclID = getTotalNumDecls();
2664
2665 if (F.LocalNumDecls > 0) {
2666 // Introduce the global -> local mapping for declarations within this
2667 // module.
2668 GlobalDeclMap.insert(
2669 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2670
2671 // Introduce the local -> global mapping for declarations within this
2672 // module.
2673 F.DeclRemap.insertOrReplace(
2674 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2675
2676 // Introduce the global -> local mapping for declarations within this
2677 // module.
2678 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002679
Ben Langmuir52ca6782014-10-20 16:27:32 +00002680 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2681 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002682 break;
2683 }
2684
2685 case TU_UPDATE_LEXICAL: {
2686 DeclContext *TU = Context.getTranslationUnitDecl();
2687 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002688 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002689 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002690 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 TU->setHasExternalLexicalStorage(true);
2692 break;
2693 }
2694
2695 case UPDATE_VISIBLE: {
2696 unsigned Idx = 0;
2697 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2698 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002699 ASTDeclContextNameLookupTable::Create(
2700 (const unsigned char *)Blob.data() + Record[Idx++],
2701 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2702 (const unsigned char *)Blob.data(),
2703 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002704 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002705 auto *DC = cast<DeclContext>(D);
2706 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002707 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2708 delete LookupTable;
2709 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002710 } else
2711 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2712 break;
2713 }
2714
2715 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002716 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002717 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002718 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2719 (const unsigned char *)F.IdentifierTableData + Record[0],
2720 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2721 (const unsigned char *)F.IdentifierTableData,
2722 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002723
2724 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2725 }
2726 break;
2727
2728 case IDENTIFIER_OFFSET: {
2729 if (F.LocalNumIdentifiers != 0) {
2730 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002731 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002732 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002733 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002734 F.LocalNumIdentifiers = Record[0];
2735 unsigned LocalBaseIdentifierID = Record[1];
2736 F.BaseIdentifierID = getTotalNumIdentifiers();
2737
2738 if (F.LocalNumIdentifiers > 0) {
2739 // Introduce the global -> local mapping for identifiers within this
2740 // module.
2741 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2742 &F));
2743
2744 // Introduce the local -> global mapping for identifiers within this
2745 // module.
2746 F.IdentifierRemap.insertOrReplace(
2747 std::make_pair(LocalBaseIdentifierID,
2748 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002749
Ben Langmuir52ca6782014-10-20 16:27:32 +00002750 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2751 + F.LocalNumIdentifiers);
2752 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002753 break;
2754 }
2755
Ben Langmuir332aafe2014-01-31 01:06:56 +00002756 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002757 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2758 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002759 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002760 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002761 break;
2762
2763 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002764 if (SpecialTypes.empty()) {
2765 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2766 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2767 break;
2768 }
2769
2770 if (SpecialTypes.size() != Record.size()) {
2771 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002772 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002773 }
2774
2775 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2776 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2777 if (!SpecialTypes[I])
2778 SpecialTypes[I] = ID;
2779 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2780 // merge step?
2781 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002782 break;
2783
2784 case STATISTICS:
2785 TotalNumStatements += Record[0];
2786 TotalNumMacros += Record[1];
2787 TotalLexicalDeclContexts += Record[2];
2788 TotalVisibleDeclContexts += Record[3];
2789 break;
2790
2791 case UNUSED_FILESCOPED_DECLS:
2792 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2793 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2794 break;
2795
2796 case DELEGATING_CTORS:
2797 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2798 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2799 break;
2800
2801 case WEAK_UNDECLARED_IDENTIFIERS:
2802 if (Record.size() % 4 != 0) {
2803 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002804 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002805 }
2806
2807 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2808 // files. This isn't the way to do it :)
2809 WeakUndeclaredIdentifiers.clear();
2810
2811 // Translate the weak, undeclared identifiers into global IDs.
2812 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2813 WeakUndeclaredIdentifiers.push_back(
2814 getGlobalIdentifierID(F, Record[I++]));
2815 WeakUndeclaredIdentifiers.push_back(
2816 getGlobalIdentifierID(F, Record[I++]));
2817 WeakUndeclaredIdentifiers.push_back(
2818 ReadSourceLocation(F, Record, I).getRawEncoding());
2819 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2820 }
2821 break;
2822
Guy Benyei11169dd2012-12-18 14:30:41 +00002823 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002824 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002825 F.LocalNumSelectors = Record[0];
2826 unsigned LocalBaseSelectorID = Record[1];
2827 F.BaseSelectorID = getTotalNumSelectors();
2828
2829 if (F.LocalNumSelectors > 0) {
2830 // Introduce the global -> local mapping for selectors within this
2831 // module.
2832 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2833
2834 // Introduce the local -> global mapping for selectors within this
2835 // module.
2836 F.SelectorRemap.insertOrReplace(
2837 std::make_pair(LocalBaseSelectorID,
2838 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002839
2840 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002841 }
2842 break;
2843 }
2844
2845 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002846 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002847 if (Record[0])
2848 F.SelectorLookupTable
2849 = ASTSelectorLookupTable::Create(
2850 F.SelectorLookupTableData + Record[0],
2851 F.SelectorLookupTableData,
2852 ASTSelectorLookupTrait(*this, F));
2853 TotalNumMethodPoolEntries += Record[1];
2854 break;
2855
2856 case REFERENCED_SELECTOR_POOL:
2857 if (!Record.empty()) {
2858 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2859 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2860 Record[Idx++]));
2861 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2862 getRawEncoding());
2863 }
2864 }
2865 break;
2866
2867 case PP_COUNTER_VALUE:
2868 if (!Record.empty() && Listener)
2869 Listener->ReadCounter(F, Record[0]);
2870 break;
2871
2872 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002873 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002874 F.NumFileSortedDecls = Record[0];
2875 break;
2876
2877 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002878 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002879 F.LocalNumSLocEntries = Record[0];
2880 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002881 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002882 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002883 SLocSpaceSize);
2884 // Make our entry in the range map. BaseID is negative and growing, so
2885 // we invert it. Because we invert it, though, we need the other end of
2886 // the range.
2887 unsigned RangeStart =
2888 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2889 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2890 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2891
2892 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2893 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2894 GlobalSLocOffsetMap.insert(
2895 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2896 - SLocSpaceSize,&F));
2897
2898 // Initialize the remapping table.
2899 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002900 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002901 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002902 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002903 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2904
2905 TotalNumSLocEntries += F.LocalNumSLocEntries;
2906 break;
2907 }
2908
2909 case MODULE_OFFSET_MAP: {
2910 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002911 const unsigned char *Data = (const unsigned char*)Blob.data();
2912 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002913
2914 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2915 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2916 F.SLocRemap.insert(std::make_pair(0U, 0));
2917 F.SLocRemap.insert(std::make_pair(2U, 1));
2918 }
2919
Guy Benyei11169dd2012-12-18 14:30:41 +00002920 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002921 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2922 RemapBuilder;
2923 RemapBuilder SLocRemap(F.SLocRemap);
2924 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2925 RemapBuilder MacroRemap(F.MacroRemap);
2926 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2927 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2928 RemapBuilder SelectorRemap(F.SelectorRemap);
2929 RemapBuilder DeclRemap(F.DeclRemap);
2930 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002931
2932 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002933 using namespace llvm::support;
2934 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002935 StringRef Name = StringRef((const char*)Data, Len);
2936 Data += Len;
2937 ModuleFile *OM = ModuleMgr.lookup(Name);
2938 if (!OM) {
2939 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002940 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002941 }
2942
Justin Bogner57ba0b22014-03-28 22:03:24 +00002943 uint32_t SLocOffset =
2944 endian::readNext<uint32_t, little, unaligned>(Data);
2945 uint32_t IdentifierIDOffset =
2946 endian::readNext<uint32_t, little, unaligned>(Data);
2947 uint32_t MacroIDOffset =
2948 endian::readNext<uint32_t, little, unaligned>(Data);
2949 uint32_t PreprocessedEntityIDOffset =
2950 endian::readNext<uint32_t, little, unaligned>(Data);
2951 uint32_t SubmoduleIDOffset =
2952 endian::readNext<uint32_t, little, unaligned>(Data);
2953 uint32_t SelectorIDOffset =
2954 endian::readNext<uint32_t, little, unaligned>(Data);
2955 uint32_t DeclIDOffset =
2956 endian::readNext<uint32_t, little, unaligned>(Data);
2957 uint32_t TypeIndexOffset =
2958 endian::readNext<uint32_t, little, unaligned>(Data);
2959
Ben Langmuir785180e2014-10-20 16:27:30 +00002960 uint32_t None = std::numeric_limits<uint32_t>::max();
2961
2962 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2963 RemapBuilder &Remap) {
2964 if (Offset != None)
2965 Remap.insert(std::make_pair(Offset,
2966 static_cast<int>(BaseOffset - Offset)));
2967 };
2968 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2969 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2970 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2971 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2972 PreprocessedEntityRemap);
2973 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2974 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2975 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2976 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002977
2978 // Global -> local mappings.
2979 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2980 }
2981 break;
2982 }
2983
2984 case SOURCE_MANAGER_LINE_TABLE:
2985 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002986 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002987 break;
2988
2989 case SOURCE_LOCATION_PRELOADS: {
2990 // Need to transform from the local view (1-based IDs) to the global view,
2991 // which is based off F.SLocEntryBaseID.
2992 if (!F.PreloadSLocEntries.empty()) {
2993 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002994 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002995 }
2996
2997 F.PreloadSLocEntries.swap(Record);
2998 break;
2999 }
3000
3001 case EXT_VECTOR_DECLS:
3002 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3003 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3004 break;
3005
3006 case VTABLE_USES:
3007 if (Record.size() % 3 != 0) {
3008 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003009 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003010 }
3011
3012 // Later tables overwrite earlier ones.
3013 // FIXME: Modules will have some trouble with this. This is clearly not
3014 // the right way to do this.
3015 VTableUses.clear();
3016
3017 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3018 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3019 VTableUses.push_back(
3020 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3021 VTableUses.push_back(Record[Idx++]);
3022 }
3023 break;
3024
Guy Benyei11169dd2012-12-18 14:30:41 +00003025 case PENDING_IMPLICIT_INSTANTIATIONS:
3026 if (PendingInstantiations.size() % 2 != 0) {
3027 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003028 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003029 }
3030
3031 if (Record.size() % 2 != 0) {
3032 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003033 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003034 }
3035
3036 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3037 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3038 PendingInstantiations.push_back(
3039 ReadSourceLocation(F, Record, I).getRawEncoding());
3040 }
3041 break;
3042
3043 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00003044 if (Record.size() != 2) {
3045 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003046 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003047 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003048 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3049 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3050 break;
3051
3052 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003053 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3054 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3055 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003056
3057 unsigned LocalBasePreprocessedEntityID = Record[0];
3058
3059 unsigned StartingID;
3060 if (!PP.getPreprocessingRecord())
3061 PP.createPreprocessingRecord();
3062 if (!PP.getPreprocessingRecord()->getExternalSource())
3063 PP.getPreprocessingRecord()->SetExternalSource(*this);
3064 StartingID
3065 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003066 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003067 F.BasePreprocessedEntityID = StartingID;
3068
3069 if (F.NumPreprocessedEntities > 0) {
3070 // Introduce the global -> local mapping for preprocessed entities in
3071 // this module.
3072 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3073
3074 // Introduce the local -> global mapping for preprocessed entities in
3075 // this module.
3076 F.PreprocessedEntityRemap.insertOrReplace(
3077 std::make_pair(LocalBasePreprocessedEntityID,
3078 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3079 }
3080
3081 break;
3082 }
3083
3084 case DECL_UPDATE_OFFSETS: {
3085 if (Record.size() % 2 != 0) {
3086 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003087 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003088 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003089 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3090 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3091 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3092
3093 // If we've already loaded the decl, perform the updates when we finish
3094 // loading this block.
3095 if (Decl *D = GetExistingDecl(ID))
3096 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3097 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003098 break;
3099 }
3100
3101 case DECL_REPLACEMENTS: {
3102 if (Record.size() % 3 != 0) {
3103 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003104 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003105 }
3106 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3107 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3108 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3109 break;
3110 }
3111
3112 case OBJC_CATEGORIES_MAP: {
3113 if (F.LocalNumObjCCategoriesInMap != 0) {
3114 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003115 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003116 }
3117
3118 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003119 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003120 break;
3121 }
3122
3123 case OBJC_CATEGORIES:
3124 F.ObjCCategories.swap(Record);
3125 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003126
Guy Benyei11169dd2012-12-18 14:30:41 +00003127 case CXX_BASE_SPECIFIER_OFFSETS: {
3128 if (F.LocalNumCXXBaseSpecifiers != 0) {
3129 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003130 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003131 }
Richard Smithc2bb8182015-03-24 06:36:48 +00003132
Guy Benyei11169dd2012-12-18 14:30:41 +00003133 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003134 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00003135 break;
3136 }
3137
3138 case CXX_CTOR_INITIALIZERS_OFFSETS: {
3139 if (F.LocalNumCXXCtorInitializers != 0) {
3140 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
3141 return Failure;
3142 }
3143
3144 F.LocalNumCXXCtorInitializers = Record[0];
3145 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003146 break;
3147 }
3148
3149 case DIAG_PRAGMA_MAPPINGS:
3150 if (F.PragmaDiagMappings.empty())
3151 F.PragmaDiagMappings.swap(Record);
3152 else
3153 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3154 Record.begin(), Record.end());
3155 break;
3156
3157 case CUDA_SPECIAL_DECL_REFS:
3158 // Later tables overwrite earlier ones.
3159 // FIXME: Modules will have trouble with this.
3160 CUDASpecialDeclRefs.clear();
3161 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3162 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3163 break;
3164
3165 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003166 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003167 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003168 if (Record[0]) {
3169 F.HeaderFileInfoTable
3170 = HeaderFileInfoLookupTable::Create(
3171 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3172 (const unsigned char *)F.HeaderFileInfoTableData,
3173 HeaderFileInfoTrait(*this, F,
3174 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003175 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003176
3177 PP.getHeaderSearchInfo().SetExternalSource(this);
3178 if (!PP.getHeaderSearchInfo().getExternalLookup())
3179 PP.getHeaderSearchInfo().SetExternalLookup(this);
3180 }
3181 break;
3182 }
3183
3184 case FP_PRAGMA_OPTIONS:
3185 // Later tables overwrite earlier ones.
3186 FPPragmaOptions.swap(Record);
3187 break;
3188
3189 case OPENCL_EXTENSIONS:
3190 // Later tables overwrite earlier ones.
3191 OpenCLExtensions.swap(Record);
3192 break;
3193
3194 case TENTATIVE_DEFINITIONS:
3195 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3196 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3197 break;
3198
3199 case KNOWN_NAMESPACES:
3200 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3201 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3202 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003203
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003204 case UNDEFINED_BUT_USED:
3205 if (UndefinedButUsed.size() % 2 != 0) {
3206 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003207 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003208 }
3209
3210 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003211 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003212 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003213 }
3214 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003215 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3216 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003217 ReadSourceLocation(F, Record, I).getRawEncoding());
3218 }
3219 break;
3220
Guy Benyei11169dd2012-12-18 14:30:41 +00003221 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003222 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003223 // If we aren't loading a module (which has its own exports), make
3224 // all of the imported modules visible.
3225 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003226 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3227 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3228 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3229 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003230 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003231 }
3232 }
3233 break;
3234 }
3235
3236 case LOCAL_REDECLARATIONS: {
3237 F.RedeclarationChains.swap(Record);
3238 break;
3239 }
3240
3241 case LOCAL_REDECLARATIONS_MAP: {
3242 if (F.LocalNumRedeclarationsInMap != 0) {
3243 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003244 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003245 }
3246
3247 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003248 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003249 break;
3250 }
3251
Guy Benyei11169dd2012-12-18 14:30:41 +00003252 case MACRO_OFFSET: {
3253 if (F.LocalNumMacros != 0) {
3254 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003255 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003256 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003257 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003258 F.LocalNumMacros = Record[0];
3259 unsigned LocalBaseMacroID = Record[1];
3260 F.BaseMacroID = getTotalNumMacros();
3261
3262 if (F.LocalNumMacros > 0) {
3263 // Introduce the global -> local mapping for macros within this module.
3264 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3265
3266 // Introduce the local -> global mapping for macros within this module.
3267 F.MacroRemap.insertOrReplace(
3268 std::make_pair(LocalBaseMacroID,
3269 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003270
3271 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003272 }
3273 break;
3274 }
3275
Richard Smithe40f2ba2013-08-07 21:41:30 +00003276 case LATE_PARSED_TEMPLATE: {
3277 LateParsedTemplates.append(Record.begin(), Record.end());
3278 break;
3279 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003280
3281 case OPTIMIZE_PRAGMA_OPTIONS:
3282 if (Record.size() != 1) {
3283 Error("invalid pragma optimize record");
3284 return Failure;
3285 }
3286 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3287 break;
Nico Weber72889432014-09-06 01:25:55 +00003288
3289 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3290 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3291 UnusedLocalTypedefNameCandidates.push_back(
3292 getGlobalDeclID(F, Record[I]));
3293 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003294 }
3295 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003296}
3297
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003298ASTReader::ASTReadResult
3299ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3300 const ModuleFile *ImportedBy,
3301 unsigned ClientLoadCapabilities) {
3302 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003303 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003304
Richard Smithe842a472014-10-22 02:05:46 +00003305 if (F.Kind == MK_ExplicitModule) {
3306 // For an explicitly-loaded module, we don't care whether the original
3307 // module map file exists or matches.
3308 return Success;
3309 }
3310
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003311 // Try to resolve ModuleName in the current header search context and
3312 // verify that it is found in the same module map file as we saved. If the
3313 // top-level AST file is a main file, skip this check because there is no
3314 // usable header search context.
3315 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003316 "MODULE_NAME should come before MODULE_MAP_FILE");
3317 if (F.Kind == MK_ImplicitModule &&
3318 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3319 // An implicitly-loaded module file should have its module listed in some
3320 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003321 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003322 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3323 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3324 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003325 assert(ImportedBy && "top-level import should be verified");
3326 if ((ClientLoadCapabilities & ARR_Missing) == 0)
Richard Smithe842a472014-10-22 02:05:46 +00003327 Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3328 << ImportedBy->FileName
3329 << F.ModuleMapPath;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003330 return Missing;
3331 }
3332
Richard Smithe842a472014-10-22 02:05:46 +00003333 assert(M->Name == F.ModuleName && "found module with different name");
3334
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003335 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003336 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003337 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3338 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003339 assert(ImportedBy && "top-level import should be verified");
3340 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3341 Diag(diag::err_imported_module_modmap_changed)
3342 << F.ModuleName << ImportedBy->FileName
3343 << ModMap->getName() << F.ModuleMapPath;
3344 return OutOfDate;
3345 }
3346
3347 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3348 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3349 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003350 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003351 const FileEntry *F =
3352 FileMgr.getFile(Filename, false, false);
3353 if (F == nullptr) {
3354 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3355 Error("could not find file '" + Filename +"' referenced by AST file");
3356 return OutOfDate;
3357 }
3358 AdditionalStoredMaps.insert(F);
3359 }
3360
3361 // Check any additional module map files (e.g. module.private.modulemap)
3362 // that are not in the pcm.
3363 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3364 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3365 // Remove files that match
3366 // Note: SmallPtrSet::erase is really remove
3367 if (!AdditionalStoredMaps.erase(ModMap)) {
3368 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3369 Diag(diag::err_module_different_modmap)
3370 << F.ModuleName << /*new*/0 << ModMap->getName();
3371 return OutOfDate;
3372 }
3373 }
3374 }
3375
3376 // Check any additional module map files that are in the pcm, but not
3377 // found in header search. Cases that match are already removed.
3378 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3379 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3380 Diag(diag::err_module_different_modmap)
3381 << F.ModuleName << /*not new*/1 << ModMap->getName();
3382 return OutOfDate;
3383 }
3384 }
3385
3386 if (Listener)
3387 Listener->ReadModuleMapFile(F.ModuleMapPath);
3388 return Success;
3389}
3390
3391
Douglas Gregorc1489562013-02-12 23:36:21 +00003392/// \brief Move the given method to the back of the global list of methods.
3393static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3394 // Find the entry for this selector in the method pool.
3395 Sema::GlobalMethodPool::iterator Known
3396 = S.MethodPool.find(Method->getSelector());
3397 if (Known == S.MethodPool.end())
3398 return;
3399
3400 // Retrieve the appropriate method list.
3401 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3402 : Known->second.second;
3403 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003404 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003405 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003406 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003407 Found = true;
3408 } else {
3409 // Keep searching.
3410 continue;
3411 }
3412 }
3413
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003414 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003415 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003416 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003417 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003418 }
3419}
3420
Richard Smithde711422015-04-23 21:20:19 +00003421void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
3422 assert(Owner->NameVisibility >= Module::MacrosVisible &&
3423 "nothing to make visible?");
3424
Richard Smithe657bbd2014-07-18 22:13:40 +00003425 // FIXME: Only do this if Owner->NameVisibility == AllVisible.
Richard Smith57721ac2014-07-21 04:10:40 +00003426 for (Decl *D : Names.HiddenDecls) {
Richard Smith49f906a2014-03-01 00:08:04 +00003427 bool wasHidden = D->Hidden;
3428 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003429
Richard Smith49f906a2014-03-01 00:08:04 +00003430 if (wasHidden && SemaObj) {
3431 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3432 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003433 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003434 }
3435 }
Richard Smith49f906a2014-03-01 00:08:04 +00003436
Richard Smithde711422015-04-23 21:20:19 +00003437 for (const auto &Macro : Names.HiddenMacros)
3438 installImportedMacro(Macro.first, *Macro.second, Owner);
Guy Benyei11169dd2012-12-18 14:30:41 +00003439}
3440
Richard Smith49f906a2014-03-01 00:08:04 +00003441void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003442 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003443 SourceLocation ImportLoc,
3444 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003445 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003446 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003447 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003448 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003449 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003450
3451 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003452 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003453 // there is nothing more to do.
3454 continue;
3455 }
Richard Smith49f906a2014-03-01 00:08:04 +00003456
Guy Benyei11169dd2012-12-18 14:30:41 +00003457 if (!Mod->isAvailable()) {
3458 // Modules that aren't available cannot be made visible.
3459 continue;
3460 }
3461
3462 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003463 if (NameVisibility >= Module::MacrosVisible &&
3464 Mod->NameVisibility < Module::MacrosVisible)
3465 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003466 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003467
Guy Benyei11169dd2012-12-18 14:30:41 +00003468 // If we've already deserialized any names from this module,
3469 // mark them as visible.
3470 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3471 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003472 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003473 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003474 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003475 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3476 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003477 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003478
Guy Benyei11169dd2012-12-18 14:30:41 +00003479 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003480 SmallVector<Module *, 16> Exports;
3481 Mod->getExportedModules(Exports);
3482 for (SmallVectorImpl<Module *>::iterator
3483 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3484 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003485 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003486 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003487 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003488
3489 // Detect any conflicts.
3490 if (Complain) {
3491 assert(ImportLoc.isValid() && "Missing import location");
3492 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3493 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3494 Diag(ImportLoc, diag::warn_module_conflict)
3495 << Mod->getFullModuleName()
3496 << Mod->Conflicts[I].Other->getFullModuleName()
3497 << Mod->Conflicts[I].Message;
3498 // FIXME: Need note where the other module was imported.
3499 }
3500 }
3501 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003502 }
3503}
3504
Douglas Gregore060e572013-01-25 01:03:03 +00003505bool ASTReader::loadGlobalIndex() {
3506 if (GlobalIndex)
3507 return false;
3508
3509 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3510 !Context.getLangOpts().Modules)
3511 return true;
3512
3513 // Try to load the global index.
3514 TriedLoadingGlobalIndex = true;
3515 StringRef ModuleCachePath
3516 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3517 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003518 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003519 if (!Result.first)
3520 return true;
3521
3522 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003523 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003524 return false;
3525}
3526
3527bool ASTReader::isGlobalIndexUnavailable() const {
3528 return Context.getLangOpts().Modules && UseGlobalIndex &&
3529 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3530}
3531
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003532static void updateModuleTimestamp(ModuleFile &MF) {
3533 // Overwrite the timestamp file contents so that file's mtime changes.
3534 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003535 std::error_code EC;
3536 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3537 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003538 return;
3539 OS << "Timestamp file\n";
3540}
3541
Guy Benyei11169dd2012-12-18 14:30:41 +00003542ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3543 ModuleKind Type,
3544 SourceLocation ImportLoc,
3545 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003546 llvm::SaveAndRestore<SourceLocation>
3547 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3548
Richard Smithd1c46742014-04-30 02:24:17 +00003549 // Defer any pending actions until we get to the end of reading the AST file.
3550 Deserializing AnASTFile(this);
3551
Guy Benyei11169dd2012-12-18 14:30:41 +00003552 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003553 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003554
3555 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003556 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003557 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003558 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003559 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003560 ClientLoadCapabilities)) {
3561 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003562 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003563 case OutOfDate:
3564 case VersionMismatch:
3565 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003566 case HadErrors: {
3567 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3568 for (const ImportedModule &IM : Loaded)
3569 LoadedSet.insert(IM.Mod);
3570
Douglas Gregor7029ce12013-03-19 00:28:20 +00003571 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003572 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003573 Context.getLangOpts().Modules
3574 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003575 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003576
3577 // If we find that any modules are unusable, the global index is going
3578 // to be out-of-date. Just remove it.
3579 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003580 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003581 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003582 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003583 case Success:
3584 break;
3585 }
3586
3587 // Here comes stuff that we only do once the entire chain is loaded.
3588
3589 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003590 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3591 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003592 M != MEnd; ++M) {
3593 ModuleFile &F = *M->Mod;
3594
3595 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003596 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3597 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003598
3599 // Once read, set the ModuleFile bit base offset and update the size in
3600 // bits of all files we've seen.
3601 F.GlobalBitOffset = TotalModulesSizeInBits;
3602 TotalModulesSizeInBits += F.SizeInBits;
3603 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3604
3605 // Preload SLocEntries.
3606 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3607 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3608 // Load it through the SourceManager and don't call ReadSLocEntry()
3609 // directly because the entry may have already been loaded in which case
3610 // calling ReadSLocEntry() directly would trigger an assertion in
3611 // SourceManager.
3612 SourceMgr.getLoadedSLocEntryByID(Index);
3613 }
3614 }
3615
Douglas Gregor603cd862013-03-22 18:50:14 +00003616 // Setup the import locations and notify the module manager that we've
3617 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003618 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3619 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003620 M != MEnd; ++M) {
3621 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003622
3623 ModuleMgr.moduleFileAccepted(&F);
3624
3625 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003626 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003627 if (!M->ImportedBy)
3628 F.ImportLoc = M->ImportLoc;
3629 else
3630 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3631 M->ImportLoc.getRawEncoding());
3632 }
3633
3634 // Mark all of the identifiers in the identifier table as being out of date,
3635 // so that various accessors know to check the loaded modules when the
3636 // identifier is used.
3637 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3638 IdEnd = PP.getIdentifierTable().end();
3639 Id != IdEnd; ++Id)
3640 Id->second->setOutOfDate(true);
3641
3642 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003643 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3644 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003645 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3646 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003647
3648 switch (Unresolved.Kind) {
3649 case UnresolvedModuleRef::Conflict:
3650 if (ResolvedMod) {
3651 Module::Conflict Conflict;
3652 Conflict.Other = ResolvedMod;
3653 Conflict.Message = Unresolved.String.str();
3654 Unresolved.Mod->Conflicts.push_back(Conflict);
3655 }
3656 continue;
3657
3658 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003659 if (ResolvedMod)
3660 Unresolved.Mod->Imports.push_back(ResolvedMod);
3661 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003662
Douglas Gregorfb912652013-03-20 21:10:35 +00003663 case UnresolvedModuleRef::Export:
3664 if (ResolvedMod || Unresolved.IsWildcard)
3665 Unresolved.Mod->Exports.push_back(
3666 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3667 continue;
3668 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003669 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003670 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003671
3672 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3673 // Might be unnecessary as use declarations are only used to build the
3674 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003675
3676 InitializeContext();
3677
Richard Smith3d8e97e2013-10-18 06:54:39 +00003678 if (SemaObj)
3679 UpdateSema();
3680
Guy Benyei11169dd2012-12-18 14:30:41 +00003681 if (DeserializationListener)
3682 DeserializationListener->ReaderInitialized(this);
3683
3684 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3685 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3686 PrimaryModule.OriginalSourceFileID
3687 = FileID::get(PrimaryModule.SLocEntryBaseID
3688 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3689
3690 // If this AST file is a precompiled preamble, then set the
3691 // preamble file ID of the source manager to the file source file
3692 // from which the preamble was built.
3693 if (Type == MK_Preamble) {
3694 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3695 } else if (Type == MK_MainFile) {
3696 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3697 }
3698 }
3699
3700 // For any Objective-C class definitions we have already loaded, make sure
3701 // that we load any additional categories.
3702 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3703 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3704 ObjCClassesLoaded[I],
3705 PreviousGeneration);
3706 }
Douglas Gregore060e572013-01-25 01:03:03 +00003707
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003708 if (PP.getHeaderSearchInfo()
3709 .getHeaderSearchOpts()
3710 .ModulesValidateOncePerBuildSession) {
3711 // Now we are certain that the module and all modules it depends on are
3712 // up to date. Create or update timestamp files for modules that are
3713 // located in the module cache (not for PCH files that could be anywhere
3714 // in the filesystem).
3715 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3716 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003717 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003718 updateModuleTimestamp(*M.Mod);
3719 }
3720 }
3721 }
3722
Guy Benyei11169dd2012-12-18 14:30:41 +00003723 return Success;
3724}
3725
Ben Langmuir487ea142014-10-23 18:05:36 +00003726static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3727
Ben Langmuir70a1b812015-03-24 04:43:52 +00003728/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3729static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3730 return Stream.Read(8) == 'C' &&
3731 Stream.Read(8) == 'P' &&
3732 Stream.Read(8) == 'C' &&
3733 Stream.Read(8) == 'H';
3734}
3735
Guy Benyei11169dd2012-12-18 14:30:41 +00003736ASTReader::ASTReadResult
3737ASTReader::ReadASTCore(StringRef FileName,
3738 ModuleKind Type,
3739 SourceLocation ImportLoc,
3740 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003741 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003742 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003743 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003744 unsigned ClientLoadCapabilities) {
3745 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003746 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003747 ModuleManager::AddModuleResult AddResult
3748 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003749 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003750 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003751 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003752
Douglas Gregor7029ce12013-03-19 00:28:20 +00003753 switch (AddResult) {
3754 case ModuleManager::AlreadyLoaded:
3755 return Success;
3756
3757 case ModuleManager::NewlyLoaded:
3758 // Load module file below.
3759 break;
3760
3761 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003762 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003763 // it.
3764 if (ClientLoadCapabilities & ARR_Missing)
3765 return Missing;
3766
3767 // Otherwise, return an error.
3768 {
3769 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3770 + ErrorStr;
3771 Error(Msg);
3772 }
3773 return Failure;
3774
3775 case ModuleManager::OutOfDate:
3776 // We couldn't load the module file because it is out-of-date. If the
3777 // client can handle out-of-date, return it.
3778 if (ClientLoadCapabilities & ARR_OutOfDate)
3779 return OutOfDate;
3780
3781 // Otherwise, return an error.
3782 {
3783 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3784 + ErrorStr;
3785 Error(Msg);
3786 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003787 return Failure;
3788 }
3789
Douglas Gregor7029ce12013-03-19 00:28:20 +00003790 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003791
3792 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3793 // module?
3794 if (FileName != "-") {
3795 CurrentDir = llvm::sys::path::parent_path(FileName);
3796 if (CurrentDir.empty()) CurrentDir = ".";
3797 }
3798
3799 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003800 BitstreamCursor &Stream = F.Stream;
Rafael Espindolafd832392014-11-12 14:48:44 +00003801 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003802 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3803
Guy Benyei11169dd2012-12-18 14:30:41 +00003804 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003805 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003806 Diag(diag::err_not_a_pch_file) << FileName;
3807 return Failure;
3808 }
3809
3810 // This is used for compatibility with older PCH formats.
3811 bool HaveReadControlBlock = false;
3812
Chris Lattnerefa77172013-01-20 00:00:22 +00003813 while (1) {
3814 llvm::BitstreamEntry Entry = Stream.advance();
3815
3816 switch (Entry.Kind) {
3817 case llvm::BitstreamEntry::Error:
3818 case llvm::BitstreamEntry::EndBlock:
3819 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003820 Error("invalid record at top-level of AST file");
3821 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003822
3823 case llvm::BitstreamEntry::SubBlock:
3824 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003825 }
3826
Guy Benyei11169dd2012-12-18 14:30:41 +00003827 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003828 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003829 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3830 if (Stream.ReadBlockInfoBlock()) {
3831 Error("malformed BlockInfoBlock in AST file");
3832 return Failure;
3833 }
3834 break;
3835 case CONTROL_BLOCK_ID:
3836 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003837 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003838 case Success:
3839 break;
3840
3841 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003842 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003843 case OutOfDate: return OutOfDate;
3844 case VersionMismatch: return VersionMismatch;
3845 case ConfigurationMismatch: return ConfigurationMismatch;
3846 case HadErrors: return HadErrors;
3847 }
3848 break;
3849 case AST_BLOCK_ID:
3850 if (!HaveReadControlBlock) {
3851 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003852 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003853 return VersionMismatch;
3854 }
3855
3856 // Record that we've loaded this module.
3857 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3858 return Success;
3859
3860 default:
3861 if (Stream.SkipBlock()) {
3862 Error("malformed block record in AST file");
3863 return Failure;
3864 }
3865 break;
3866 }
3867 }
3868
3869 return Success;
3870}
3871
3872void ASTReader::InitializeContext() {
3873 // If there's a listener, notify them that we "read" the translation unit.
3874 if (DeserializationListener)
3875 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3876 Context.getTranslationUnitDecl());
3877
Guy Benyei11169dd2012-12-18 14:30:41 +00003878 // FIXME: Find a better way to deal with collisions between these
3879 // built-in types. Right now, we just ignore the problem.
3880
3881 // Load the special types.
3882 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3883 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3884 if (!Context.CFConstantStringTypeDecl)
3885 Context.setCFConstantStringType(GetType(String));
3886 }
3887
3888 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3889 QualType FileType = GetType(File);
3890 if (FileType.isNull()) {
3891 Error("FILE type is NULL");
3892 return;
3893 }
3894
3895 if (!Context.FILEDecl) {
3896 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3897 Context.setFILEDecl(Typedef->getDecl());
3898 else {
3899 const TagType *Tag = FileType->getAs<TagType>();
3900 if (!Tag) {
3901 Error("Invalid FILE type in AST file");
3902 return;
3903 }
3904 Context.setFILEDecl(Tag->getDecl());
3905 }
3906 }
3907 }
3908
3909 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3910 QualType Jmp_bufType = GetType(Jmp_buf);
3911 if (Jmp_bufType.isNull()) {
3912 Error("jmp_buf type is NULL");
3913 return;
3914 }
3915
3916 if (!Context.jmp_bufDecl) {
3917 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3918 Context.setjmp_bufDecl(Typedef->getDecl());
3919 else {
3920 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3921 if (!Tag) {
3922 Error("Invalid jmp_buf type in AST file");
3923 return;
3924 }
3925 Context.setjmp_bufDecl(Tag->getDecl());
3926 }
3927 }
3928 }
3929
3930 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3931 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3932 if (Sigjmp_bufType.isNull()) {
3933 Error("sigjmp_buf type is NULL");
3934 return;
3935 }
3936
3937 if (!Context.sigjmp_bufDecl) {
3938 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3939 Context.setsigjmp_bufDecl(Typedef->getDecl());
3940 else {
3941 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3942 assert(Tag && "Invalid sigjmp_buf type in AST file");
3943 Context.setsigjmp_bufDecl(Tag->getDecl());
3944 }
3945 }
3946 }
3947
3948 if (unsigned ObjCIdRedef
3949 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3950 if (Context.ObjCIdRedefinitionType.isNull())
3951 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3952 }
3953
3954 if (unsigned ObjCClassRedef
3955 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3956 if (Context.ObjCClassRedefinitionType.isNull())
3957 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3958 }
3959
3960 if (unsigned ObjCSelRedef
3961 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3962 if (Context.ObjCSelRedefinitionType.isNull())
3963 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3964 }
3965
3966 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3967 QualType Ucontext_tType = GetType(Ucontext_t);
3968 if (Ucontext_tType.isNull()) {
3969 Error("ucontext_t type is NULL");
3970 return;
3971 }
3972
3973 if (!Context.ucontext_tDecl) {
3974 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3975 Context.setucontext_tDecl(Typedef->getDecl());
3976 else {
3977 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3978 assert(Tag && "Invalid ucontext_t type in AST file");
3979 Context.setucontext_tDecl(Tag->getDecl());
3980 }
3981 }
3982 }
3983 }
3984
3985 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3986
3987 // If there were any CUDA special declarations, deserialize them.
3988 if (!CUDASpecialDeclRefs.empty()) {
3989 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3990 Context.setcudaConfigureCallDecl(
3991 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3992 }
Richard Smith56be7542014-03-21 00:33:59 +00003993
Guy Benyei11169dd2012-12-18 14:30:41 +00003994 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00003995 // FIXME: This does not make macro-only imports visible again. It also doesn't
3996 // make #includes mapped to module imports visible.
3997 for (auto &Import : ImportedModules) {
3998 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003999 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00004000 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00004001 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00004002 }
4003 ImportedModules.clear();
4004}
4005
4006void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004007 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004008}
4009
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004010/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
4011/// cursor into the start of the given block ID, returning false on success and
4012/// true on failure.
4013static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004014 while (1) {
4015 llvm::BitstreamEntry Entry = Cursor.advance();
4016 switch (Entry.Kind) {
4017 case llvm::BitstreamEntry::Error:
4018 case llvm::BitstreamEntry::EndBlock:
4019 return true;
4020
4021 case llvm::BitstreamEntry::Record:
4022 // Ignore top-level records.
4023 Cursor.skipRecord(Entry.ID);
4024 break;
4025
4026 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004027 if (Entry.ID == BlockID) {
4028 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004029 return true;
4030 // Found it!
4031 return false;
4032 }
4033
4034 if (Cursor.SkipBlock())
4035 return true;
4036 }
4037 }
4038}
4039
Ben Langmuir70a1b812015-03-24 04:43:52 +00004040/// \brief Reads and return the signature record from \p StreamFile's control
4041/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00004042static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
4043 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004044 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00004045 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00004046
4047 // Scan for the CONTROL_BLOCK_ID block.
4048 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4049 return 0;
4050
4051 // Scan for SIGNATURE inside the control block.
4052 ASTReader::RecordData Record;
4053 while (1) {
4054 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4055 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
4056 Entry.Kind != llvm::BitstreamEntry::Record)
4057 return 0;
4058
4059 Record.clear();
4060 StringRef Blob;
4061 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4062 return Record[0];
4063 }
4064}
4065
Guy Benyei11169dd2012-12-18 14:30:41 +00004066/// \brief Retrieve the name of the original source file name
4067/// directly from the AST file, without actually loading the AST
4068/// file.
4069std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
4070 FileManager &FileMgr,
4071 DiagnosticsEngine &Diags) {
4072 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004073 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004074 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004075 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4076 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004077 return std::string();
4078 }
4079
4080 // Initialize the stream
4081 llvm::BitstreamReader StreamFile;
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004082 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
4083 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004084 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004085
4086 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004087 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004088 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4089 return std::string();
4090 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004091
Chris Lattnere7b154b2013-01-19 21:39:22 +00004092 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004093 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004094 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4095 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004096 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004097
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004098 // Scan for ORIGINAL_FILE inside the control block.
4099 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004100 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004101 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004102 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4103 return std::string();
4104
4105 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4106 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4107 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004108 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004109
Guy Benyei11169dd2012-12-18 14:30:41 +00004110 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004111 StringRef Blob;
4112 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4113 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004114 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004115}
4116
4117namespace {
4118 class SimplePCHValidator : public ASTReaderListener {
4119 const LangOptions &ExistingLangOpts;
4120 const TargetOptions &ExistingTargetOpts;
4121 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004122 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004123 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004124
Guy Benyei11169dd2012-12-18 14:30:41 +00004125 public:
4126 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4127 const TargetOptions &ExistingTargetOpts,
4128 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004129 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004130 FileManager &FileMgr)
4131 : ExistingLangOpts(ExistingLangOpts),
4132 ExistingTargetOpts(ExistingTargetOpts),
4133 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004134 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004135 FileMgr(FileMgr)
4136 {
4137 }
4138
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004139 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4140 bool AllowCompatibleDifferences) override {
4141 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4142 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004143 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004144 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4145 bool AllowCompatibleDifferences) override {
4146 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4147 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004148 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004149 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4150 StringRef SpecificModuleCachePath,
4151 bool Complain) override {
4152 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4153 ExistingModuleCachePath,
4154 nullptr, ExistingLangOpts);
4155 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004156 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4157 bool Complain,
4158 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004159 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004160 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004161 }
4162 };
4163}
4164
4165bool ASTReader::readASTFileControlBlock(StringRef Filename,
4166 FileManager &FileMgr,
4167 ASTReaderListener &Listener) {
4168 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004169 // FIXME: This allows use of the VFS; we do not allow use of the
4170 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004171 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004172 if (!Buffer) {
4173 return true;
4174 }
4175
4176 // Initialize the stream
4177 llvm::BitstreamReader StreamFile;
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004178 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
4179 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004180 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004181
4182 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004183 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004184 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004185
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004186 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004187 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004188 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004189
4190 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004191 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004192 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004193 BitstreamCursor InputFilesCursor;
4194 if (NeedsInputFiles) {
4195 InputFilesCursor = Stream;
4196 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4197 return true;
4198
4199 // Read the abbreviations
4200 while (true) {
4201 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4202 unsigned Code = InputFilesCursor.ReadCode();
4203
4204 // We expect all abbrevs to be at the start of the block.
4205 if (Code != llvm::bitc::DEFINE_ABBREV) {
4206 InputFilesCursor.JumpToBit(Offset);
4207 break;
4208 }
4209 InputFilesCursor.ReadAbbrevRecord();
4210 }
4211 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004212
4213 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004214 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004215 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004216 while (1) {
4217 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4218 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4219 return false;
4220
4221 if (Entry.Kind != llvm::BitstreamEntry::Record)
4222 return true;
4223
Guy Benyei11169dd2012-12-18 14:30:41 +00004224 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004225 StringRef Blob;
4226 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004227 switch ((ControlRecordTypes)RecCode) {
4228 case METADATA: {
4229 if (Record[0] != VERSION_MAJOR)
4230 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004231
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004232 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004233 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004234
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004235 break;
4236 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004237 case MODULE_NAME:
4238 Listener.ReadModuleName(Blob);
4239 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004240 case MODULE_DIRECTORY:
4241 ModuleDir = Blob;
4242 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004243 case MODULE_MAP_FILE: {
4244 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004245 auto Path = ReadString(Record, Idx);
4246 ResolveImportedPath(Path, ModuleDir);
4247 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004248 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004249 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004250 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004251 if (ParseLanguageOptions(Record, false, Listener,
4252 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004253 return true;
4254 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004255
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004256 case TARGET_OPTIONS:
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004257 if (ParseTargetOptions(Record, false, Listener,
4258 /*AllowCompatibleConfigurationMismatch*/ false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004259 return true;
4260 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004261
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004262 case DIAGNOSTIC_OPTIONS:
4263 if (ParseDiagnosticOptions(Record, false, Listener))
4264 return true;
4265 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004266
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004267 case FILE_SYSTEM_OPTIONS:
4268 if (ParseFileSystemOptions(Record, false, Listener))
4269 return true;
4270 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004271
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004272 case HEADER_SEARCH_OPTIONS:
4273 if (ParseHeaderSearchOptions(Record, false, Listener))
4274 return true;
4275 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004276
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004277 case PREPROCESSOR_OPTIONS: {
4278 std::string IgnoredSuggestedPredefines;
4279 if (ParsePreprocessorOptions(Record, false, Listener,
4280 IgnoredSuggestedPredefines))
4281 return true;
4282 break;
4283 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004284
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004285 case INPUT_FILE_OFFSETS: {
4286 if (!NeedsInputFiles)
4287 break;
4288
4289 unsigned NumInputFiles = Record[0];
4290 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004291 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004292 for (unsigned I = 0; I != NumInputFiles; ++I) {
4293 // Go find this input file.
4294 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004295
4296 if (isSystemFile && !NeedsSystemInputFiles)
4297 break; // the rest are system input files
4298
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004299 BitstreamCursor &Cursor = InputFilesCursor;
4300 SavedStreamPosition SavedPosition(Cursor);
4301 Cursor.JumpToBit(InputFileOffs[I]);
4302
4303 unsigned Code = Cursor.ReadCode();
4304 RecordData Record;
4305 StringRef Blob;
4306 bool shouldContinue = false;
4307 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4308 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004309 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004310 std::string Filename = Blob;
4311 ResolveImportedPath(Filename, ModuleDir);
4312 shouldContinue =
4313 Listener.visitInputFile(Filename, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004314 break;
4315 }
4316 if (!shouldContinue)
4317 break;
4318 }
4319 break;
4320 }
4321
Richard Smithd4b230b2014-10-27 23:01:16 +00004322 case IMPORTS: {
4323 if (!NeedsImports)
4324 break;
4325
4326 unsigned Idx = 0, N = Record.size();
4327 while (Idx < N) {
4328 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004329 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004330 std::string Filename = ReadString(Record, Idx);
4331 ResolveImportedPath(Filename, ModuleDir);
4332 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004333 }
4334 break;
4335 }
4336
Richard Smith7f330cd2015-03-18 01:42:29 +00004337 case KNOWN_MODULE_FILES: {
4338 // Known-but-not-technically-used module files are treated as imports.
4339 if (!NeedsImports)
4340 break;
4341
4342 unsigned Idx = 0, N = Record.size();
4343 while (Idx < N) {
4344 std::string Filename = ReadString(Record, Idx);
4345 ResolveImportedPath(Filename, ModuleDir);
4346 Listener.visitImport(Filename);
4347 }
4348 break;
4349 }
4350
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004351 default:
4352 // No other validation to perform.
4353 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004354 }
4355 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004356}
4357
4358
4359bool ASTReader::isAcceptableASTFile(StringRef Filename,
4360 FileManager &FileMgr,
4361 const LangOptions &LangOpts,
4362 const TargetOptions &TargetOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004363 const PreprocessorOptions &PPOpts,
4364 std::string ExistingModuleCachePath) {
4365 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4366 ExistingModuleCachePath, FileMgr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004367 return !readASTFileControlBlock(Filename, FileMgr, validator);
4368}
4369
Ben Langmuir2c9af442014-04-10 17:57:43 +00004370ASTReader::ASTReadResult
4371ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004372 // Enter the submodule block.
4373 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4374 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004375 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004376 }
4377
4378 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4379 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004380 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004381 RecordData Record;
4382 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004383 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4384
4385 switch (Entry.Kind) {
4386 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4387 case llvm::BitstreamEntry::Error:
4388 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004389 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004390 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004391 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004392 case llvm::BitstreamEntry::Record:
4393 // The interesting case.
4394 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004395 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004396
Guy Benyei11169dd2012-12-18 14:30:41 +00004397 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004398 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004399 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004400 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4401
4402 if ((Kind == SUBMODULE_METADATA) != First) {
4403 Error("submodule metadata record should be at beginning of block");
4404 return Failure;
4405 }
4406 First = false;
4407
4408 // Submodule information is only valid if we have a current module.
4409 // FIXME: Should we error on these cases?
4410 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4411 Kind != SUBMODULE_DEFINITION)
4412 continue;
4413
4414 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004415 default: // Default behavior: ignore.
4416 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004417
Richard Smith03478d92014-10-23 22:12:14 +00004418 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004419 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004420 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004421 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004422 }
Richard Smith03478d92014-10-23 22:12:14 +00004423
Chris Lattner0e6c9402013-01-20 02:38:54 +00004424 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004425 unsigned Idx = 0;
4426 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4427 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4428 bool IsFramework = Record[Idx++];
4429 bool IsExplicit = Record[Idx++];
4430 bool IsSystem = Record[Idx++];
4431 bool IsExternC = Record[Idx++];
4432 bool InferSubmodules = Record[Idx++];
4433 bool InferExplicitSubmodules = Record[Idx++];
4434 bool InferExportWildcard = Record[Idx++];
4435 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004436
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004437 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004438 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004439 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004440
Guy Benyei11169dd2012-12-18 14:30:41 +00004441 // Retrieve this (sub)module from the module map, creating it if
4442 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004443 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004444 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004445
4446 // FIXME: set the definition loc for CurrentModule, or call
4447 // ModMap.setInferredModuleAllowedBy()
4448
Guy Benyei11169dd2012-12-18 14:30:41 +00004449 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4450 if (GlobalIndex >= SubmodulesLoaded.size() ||
4451 SubmodulesLoaded[GlobalIndex]) {
4452 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004453 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004454 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004455
Douglas Gregor7029ce12013-03-19 00:28:20 +00004456 if (!ParentModule) {
4457 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4458 if (CurFile != F.File) {
4459 if (!Diags.isDiagnosticInFlight()) {
4460 Diag(diag::err_module_file_conflict)
4461 << CurrentModule->getTopLevelModuleName()
4462 << CurFile->getName()
4463 << F.File->getName();
4464 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004465 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004466 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004467 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004468
4469 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004470 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004471
Guy Benyei11169dd2012-12-18 14:30:41 +00004472 CurrentModule->IsFromModuleFile = true;
4473 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004474 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004475 CurrentModule->InferSubmodules = InferSubmodules;
4476 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4477 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004478 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004479 if (DeserializationListener)
4480 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4481
4482 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004483
Douglas Gregorfb912652013-03-20 21:10:35 +00004484 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004485 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004486 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004487 CurrentModule->UnresolvedConflicts.clear();
4488 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004489 break;
4490 }
4491
4492 case SUBMODULE_UMBRELLA_HEADER: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004493 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004494 if (!CurrentModule->getUmbrellaHeader())
4495 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4496 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004497 // This can be a spurious difference caused by changing the VFS to
4498 // point to a different copy of the file, and it is too late to
4499 // to rebuild safely.
4500 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4501 // after input file validation only real problems would remain and we
4502 // could just error. For now, assume it's okay.
4503 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004504 }
4505 }
4506 break;
4507 }
4508
Richard Smith202210b2014-10-24 20:23:01 +00004509 case SUBMODULE_HEADER:
4510 case SUBMODULE_EXCLUDED_HEADER:
4511 case SUBMODULE_PRIVATE_HEADER:
4512 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004513 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4514 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004515 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004516
Richard Smith202210b2014-10-24 20:23:01 +00004517 case SUBMODULE_TEXTUAL_HEADER:
4518 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4519 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4520 // them here.
4521 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004522
Guy Benyei11169dd2012-12-18 14:30:41 +00004523 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004524 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004525 break;
4526 }
4527
4528 case SUBMODULE_UMBRELLA_DIR: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004529 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004530 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004531 if (!CurrentModule->getUmbrellaDir())
4532 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4533 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004534 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4535 Error("mismatched umbrella directories in submodule");
4536 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004537 }
4538 }
4539 break;
4540 }
4541
4542 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004543 F.BaseSubmoduleID = getTotalNumSubmodules();
4544 F.LocalNumSubmodules = Record[0];
4545 unsigned LocalBaseSubmoduleID = Record[1];
4546 if (F.LocalNumSubmodules > 0) {
4547 // Introduce the global -> local mapping for submodules within this
4548 // module.
4549 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4550
4551 // Introduce the local -> global mapping for submodules within this
4552 // module.
4553 F.SubmoduleRemap.insertOrReplace(
4554 std::make_pair(LocalBaseSubmoduleID,
4555 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004556
Ben Langmuir52ca6782014-10-20 16:27:32 +00004557 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4558 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004559 break;
4560 }
4561
4562 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004563 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004564 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004565 Unresolved.File = &F;
4566 Unresolved.Mod = CurrentModule;
4567 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004568 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004569 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004570 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004571 }
4572 break;
4573 }
4574
4575 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004576 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004577 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004578 Unresolved.File = &F;
4579 Unresolved.Mod = CurrentModule;
4580 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004581 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004582 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004583 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004584 }
4585
4586 // Once we've loaded the set of exports, there's no reason to keep
4587 // the parsed, unresolved exports around.
4588 CurrentModule->UnresolvedExports.clear();
4589 break;
4590 }
4591 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004592 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004593 Context.getTargetInfo());
4594 break;
4595 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004596
4597 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004598 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004599 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004600 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004601
4602 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004603 CurrentModule->ConfigMacros.push_back(Blob.str());
4604 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004605
4606 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004607 UnresolvedModuleRef Unresolved;
4608 Unresolved.File = &F;
4609 Unresolved.Mod = CurrentModule;
4610 Unresolved.ID = Record[0];
4611 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4612 Unresolved.IsWildcard = false;
4613 Unresolved.String = Blob;
4614 UnresolvedModuleRefs.push_back(Unresolved);
4615 break;
4616 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004617 }
4618 }
4619}
4620
4621/// \brief Parse the record that corresponds to a LangOptions data
4622/// structure.
4623///
4624/// This routine parses the language options from the AST file and then gives
4625/// them to the AST listener if one is set.
4626///
4627/// \returns true if the listener deems the file unacceptable, false otherwise.
4628bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4629 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004630 ASTReaderListener &Listener,
4631 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004632 LangOptions LangOpts;
4633 unsigned Idx = 0;
4634#define LANGOPT(Name, Bits, Default, Description) \
4635 LangOpts.Name = Record[Idx++];
4636#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4637 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4638#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004639#define SANITIZER(NAME, ID) \
4640 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004641#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004642
4643 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4644 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4645 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4646
4647 unsigned Length = Record[Idx++];
4648 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4649 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004650
4651 Idx += Length;
4652
4653 // Comment options.
4654 for (unsigned N = Record[Idx++]; N; --N) {
4655 LangOpts.CommentOpts.BlockCommandNames.push_back(
4656 ReadString(Record, Idx));
4657 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004658 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004659
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004660 return Listener.ReadLanguageOptions(LangOpts, Complain,
4661 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004662}
4663
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004664bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4665 ASTReaderListener &Listener,
4666 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004667 unsigned Idx = 0;
4668 TargetOptions TargetOpts;
4669 TargetOpts.Triple = ReadString(Record, Idx);
4670 TargetOpts.CPU = ReadString(Record, Idx);
4671 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004672 for (unsigned N = Record[Idx++]; N; --N) {
4673 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4674 }
4675 for (unsigned N = Record[Idx++]; N; --N) {
4676 TargetOpts.Features.push_back(ReadString(Record, Idx));
4677 }
4678
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004679 return Listener.ReadTargetOptions(TargetOpts, Complain,
4680 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004681}
4682
4683bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4684 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004685 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004686 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004687#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004688#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004689 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004690#include "clang/Basic/DiagnosticOptions.def"
4691
Richard Smith3be1cb22014-08-07 00:24:21 +00004692 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004693 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004694 for (unsigned N = Record[Idx++]; N; --N)
4695 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004696
4697 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4698}
4699
4700bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4701 ASTReaderListener &Listener) {
4702 FileSystemOptions FSOpts;
4703 unsigned Idx = 0;
4704 FSOpts.WorkingDir = ReadString(Record, Idx);
4705 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4706}
4707
4708bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4709 bool Complain,
4710 ASTReaderListener &Listener) {
4711 HeaderSearchOptions HSOpts;
4712 unsigned Idx = 0;
4713 HSOpts.Sysroot = ReadString(Record, Idx);
4714
4715 // Include entries.
4716 for (unsigned N = Record[Idx++]; N; --N) {
4717 std::string Path = ReadString(Record, Idx);
4718 frontend::IncludeDirGroup Group
4719 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004720 bool IsFramework = Record[Idx++];
4721 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004722 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004723 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004724 }
4725
4726 // System header prefixes.
4727 for (unsigned N = Record[Idx++]; N; --N) {
4728 std::string Prefix = ReadString(Record, Idx);
4729 bool IsSystemHeader = Record[Idx++];
4730 HSOpts.SystemHeaderPrefixes.push_back(
4731 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4732 }
4733
4734 HSOpts.ResourceDir = ReadString(Record, Idx);
4735 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004736 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004737 HSOpts.DisableModuleHash = Record[Idx++];
4738 HSOpts.UseBuiltinIncludes = Record[Idx++];
4739 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4740 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4741 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004742 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004743
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004744 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4745 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004746}
4747
4748bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4749 bool Complain,
4750 ASTReaderListener &Listener,
4751 std::string &SuggestedPredefines) {
4752 PreprocessorOptions PPOpts;
4753 unsigned Idx = 0;
4754
4755 // Macro definitions/undefs
4756 for (unsigned N = Record[Idx++]; N; --N) {
4757 std::string Macro = ReadString(Record, Idx);
4758 bool IsUndef = Record[Idx++];
4759 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4760 }
4761
4762 // Includes
4763 for (unsigned N = Record[Idx++]; N; --N) {
4764 PPOpts.Includes.push_back(ReadString(Record, Idx));
4765 }
4766
4767 // Macro Includes
4768 for (unsigned N = Record[Idx++]; N; --N) {
4769 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4770 }
4771
4772 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004773 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004774 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4775 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4776 PPOpts.ObjCXXARCStandardLibrary =
4777 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4778 SuggestedPredefines.clear();
4779 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4780 SuggestedPredefines);
4781}
4782
4783std::pair<ModuleFile *, unsigned>
4784ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4785 GlobalPreprocessedEntityMapType::iterator
4786 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4787 assert(I != GlobalPreprocessedEntityMap.end() &&
4788 "Corrupted global preprocessed entity map");
4789 ModuleFile *M = I->second;
4790 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4791 return std::make_pair(M, LocalIndex);
4792}
4793
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004794llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004795ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4796 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4797 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4798 Mod.NumPreprocessedEntities);
4799
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004800 return llvm::make_range(PreprocessingRecord::iterator(),
4801 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004802}
4803
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004804llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004805ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004806 return llvm::make_range(
4807 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4808 ModuleDeclIterator(this, &Mod,
4809 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004810}
4811
4812PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4813 PreprocessedEntityID PPID = Index+1;
4814 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4815 ModuleFile &M = *PPInfo.first;
4816 unsigned LocalIndex = PPInfo.second;
4817 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4818
Guy Benyei11169dd2012-12-18 14:30:41 +00004819 if (!PP.getPreprocessingRecord()) {
4820 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004821 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004822 }
4823
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004824 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4825 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4826
4827 llvm::BitstreamEntry Entry =
4828 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4829 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004830 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004831
Guy Benyei11169dd2012-12-18 14:30:41 +00004832 // Read the record.
4833 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4834 ReadSourceLocation(M, PPOffs.End));
4835 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004836 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004837 RecordData Record;
4838 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004839 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4840 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004841 switch (RecType) {
4842 case PPD_MACRO_EXPANSION: {
4843 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004844 IdentifierInfo *Name = nullptr;
4845 MacroDefinition *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004846 if (isBuiltin)
4847 Name = getLocalIdentifier(M, Record[1]);
4848 else {
4849 PreprocessedEntityID
4850 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4851 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4852 }
4853
4854 MacroExpansion *ME;
4855 if (isBuiltin)
4856 ME = new (PPRec) MacroExpansion(Name, Range);
4857 else
4858 ME = new (PPRec) MacroExpansion(Def, Range);
4859
4860 return ME;
4861 }
4862
4863 case PPD_MACRO_DEFINITION: {
4864 // Decode the identifier info and then check again; if the macro is
4865 // still defined and associated with the identifier,
4866 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4867 MacroDefinition *MD
4868 = new (PPRec) MacroDefinition(II, Range);
4869
4870 if (DeserializationListener)
4871 DeserializationListener->MacroDefinitionRead(PPID, MD);
4872
4873 return MD;
4874 }
4875
4876 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004877 const char *FullFileNameStart = Blob.data() + Record[0];
4878 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004879 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004880 if (!FullFileName.empty())
4881 File = PP.getFileManager().getFile(FullFileName);
4882
4883 // FIXME: Stable encoding
4884 InclusionDirective::InclusionKind Kind
4885 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4886 InclusionDirective *ID
4887 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004888 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004889 Record[1], Record[3],
4890 File,
4891 Range);
4892 return ID;
4893 }
4894 }
4895
4896 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4897}
4898
4899/// \brief \arg SLocMapI points at a chunk of a module that contains no
4900/// preprocessed entities or the entities it contains are not the ones we are
4901/// looking for. Find the next module that contains entities and return the ID
4902/// of the first entry.
4903PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4904 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4905 ++SLocMapI;
4906 for (GlobalSLocOffsetMapType::const_iterator
4907 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4908 ModuleFile &M = *SLocMapI->second;
4909 if (M.NumPreprocessedEntities)
4910 return M.BasePreprocessedEntityID;
4911 }
4912
4913 return getTotalNumPreprocessedEntities();
4914}
4915
4916namespace {
4917
4918template <unsigned PPEntityOffset::*PPLoc>
4919struct PPEntityComp {
4920 const ASTReader &Reader;
4921 ModuleFile &M;
4922
4923 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4924
4925 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4926 SourceLocation LHS = getLoc(L);
4927 SourceLocation RHS = getLoc(R);
4928 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4929 }
4930
4931 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4932 SourceLocation LHS = getLoc(L);
4933 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4934 }
4935
4936 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4937 SourceLocation RHS = getLoc(R);
4938 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4939 }
4940
4941 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4942 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4943 }
4944};
4945
4946}
4947
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004948PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4949 bool EndsAfter) const {
4950 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004951 return getTotalNumPreprocessedEntities();
4952
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004953 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4954 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004955 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4956 "Corrupted global sloc offset map");
4957
4958 if (SLocMapI->second->NumPreprocessedEntities == 0)
4959 return findNextPreprocessedEntity(SLocMapI);
4960
4961 ModuleFile &M = *SLocMapI->second;
4962 typedef const PPEntityOffset *pp_iterator;
4963 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4964 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4965
4966 size_t Count = M.NumPreprocessedEntities;
4967 size_t Half;
4968 pp_iterator First = pp_begin;
4969 pp_iterator PPI;
4970
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004971 if (EndsAfter) {
4972 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4973 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4974 } else {
4975 // Do a binary search manually instead of using std::lower_bound because
4976 // The end locations of entities may be unordered (when a macro expansion
4977 // is inside another macro argument), but for this case it is not important
4978 // whether we get the first macro expansion or its containing macro.
4979 while (Count > 0) {
4980 Half = Count / 2;
4981 PPI = First;
4982 std::advance(PPI, Half);
4983 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4984 Loc)) {
4985 First = PPI;
4986 ++First;
4987 Count = Count - Half - 1;
4988 } else
4989 Count = Half;
4990 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004991 }
4992
4993 if (PPI == pp_end)
4994 return findNextPreprocessedEntity(SLocMapI);
4995
4996 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4997}
4998
Guy Benyei11169dd2012-12-18 14:30:41 +00004999/// \brief Returns a pair of [Begin, End) indices of preallocated
5000/// preprocessed entities that \arg Range encompasses.
5001std::pair<unsigned, unsigned>
5002 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5003 if (Range.isInvalid())
5004 return std::make_pair(0,0);
5005 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5006
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005007 PreprocessedEntityID BeginID =
5008 findPreprocessedEntity(Range.getBegin(), false);
5009 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005010 return std::make_pair(BeginID, EndID);
5011}
5012
5013/// \brief Optionally returns true or false if the preallocated preprocessed
5014/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005015Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005016 FileID FID) {
5017 if (FID.isInvalid())
5018 return false;
5019
5020 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5021 ModuleFile &M = *PPInfo.first;
5022 unsigned LocalIndex = PPInfo.second;
5023 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5024
5025 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
5026 if (Loc.isInvalid())
5027 return false;
5028
5029 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5030 return true;
5031 else
5032 return false;
5033}
5034
5035namespace {
5036 /// \brief Visitor used to search for information about a header file.
5037 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005038 const FileEntry *FE;
5039
David Blaikie05785d12013-02-20 22:23:23 +00005040 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005041
5042 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005043 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5044 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00005045
5046 static bool visit(ModuleFile &M, void *UserData) {
5047 HeaderFileInfoVisitor *This
5048 = static_cast<HeaderFileInfoVisitor *>(UserData);
5049
Guy Benyei11169dd2012-12-18 14:30:41 +00005050 HeaderFileInfoLookupTable *Table
5051 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5052 if (!Table)
5053 return false;
5054
5055 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00005056 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005057 if (Pos == Table->end())
5058 return false;
5059
5060 This->HFI = *Pos;
5061 return true;
5062 }
5063
David Blaikie05785d12013-02-20 22:23:23 +00005064 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005065 };
5066}
5067
5068HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005069 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005070 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005071 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005072 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005073
5074 return HeaderFileInfo();
5075}
5076
5077void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5078 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005079 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005080 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5081 ModuleFile &F = *(*I);
5082 unsigned Idx = 0;
5083 DiagStates.clear();
5084 assert(!Diag.DiagStates.empty());
5085 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5086 while (Idx < F.PragmaDiagMappings.size()) {
5087 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5088 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5089 if (DiagStateID != 0) {
5090 Diag.DiagStatePoints.push_back(
5091 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5092 FullSourceLoc(Loc, SourceMgr)));
5093 continue;
5094 }
5095
5096 assert(DiagStateID == 0);
5097 // A new DiagState was created here.
5098 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5099 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5100 DiagStates.push_back(NewState);
5101 Diag.DiagStatePoints.push_back(
5102 DiagnosticsEngine::DiagStatePoint(NewState,
5103 FullSourceLoc(Loc, SourceMgr)));
5104 while (1) {
5105 assert(Idx < F.PragmaDiagMappings.size() &&
5106 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5107 if (Idx >= F.PragmaDiagMappings.size()) {
5108 break; // Something is messed up but at least avoid infinite loop in
5109 // release build.
5110 }
5111 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5112 if (DiagID == (unsigned)-1) {
5113 break; // no more diag/map pairs for this location.
5114 }
Alp Tokerc726c362014-06-10 09:31:37 +00005115 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5116 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5117 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005118 }
5119 }
5120 }
5121}
5122
5123/// \brief Get the correct cursor and offset for loading a type.
5124ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5125 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5126 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5127 ModuleFile *M = I->second;
5128 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5129}
5130
5131/// \brief Read and return the type with the given index..
5132///
5133/// The index is the type ID, shifted and minus the number of predefs. This
5134/// routine actually reads the record corresponding to the type at the given
5135/// location. It is a helper routine for GetType, which deals with reading type
5136/// IDs.
5137QualType ASTReader::readTypeRecord(unsigned Index) {
5138 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005139 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005140
5141 // Keep track of where we are in the stream, then jump back there
5142 // after reading this type.
5143 SavedStreamPosition SavedPosition(DeclsCursor);
5144
5145 ReadingKindTracker ReadingKind(Read_Type, *this);
5146
5147 // Note that we are loading a type record.
5148 Deserializing AType(this);
5149
5150 unsigned Idx = 0;
5151 DeclsCursor.JumpToBit(Loc.Offset);
5152 RecordData Record;
5153 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005154 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005155 case TYPE_EXT_QUAL: {
5156 if (Record.size() != 2) {
5157 Error("Incorrect encoding of extended qualifier type");
5158 return QualType();
5159 }
5160 QualType Base = readType(*Loc.F, Record, Idx);
5161 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5162 return Context.getQualifiedType(Base, Quals);
5163 }
5164
5165 case TYPE_COMPLEX: {
5166 if (Record.size() != 1) {
5167 Error("Incorrect encoding of complex type");
5168 return QualType();
5169 }
5170 QualType ElemType = readType(*Loc.F, Record, Idx);
5171 return Context.getComplexType(ElemType);
5172 }
5173
5174 case TYPE_POINTER: {
5175 if (Record.size() != 1) {
5176 Error("Incorrect encoding of pointer type");
5177 return QualType();
5178 }
5179 QualType PointeeType = readType(*Loc.F, Record, Idx);
5180 return Context.getPointerType(PointeeType);
5181 }
5182
Reid Kleckner8a365022013-06-24 17:51:48 +00005183 case TYPE_DECAYED: {
5184 if (Record.size() != 1) {
5185 Error("Incorrect encoding of decayed type");
5186 return QualType();
5187 }
5188 QualType OriginalType = readType(*Loc.F, Record, Idx);
5189 QualType DT = Context.getAdjustedParameterType(OriginalType);
5190 if (!isa<DecayedType>(DT))
5191 Error("Decayed type does not decay");
5192 return DT;
5193 }
5194
Reid Kleckner0503a872013-12-05 01:23:43 +00005195 case TYPE_ADJUSTED: {
5196 if (Record.size() != 2) {
5197 Error("Incorrect encoding of adjusted type");
5198 return QualType();
5199 }
5200 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5201 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5202 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5203 }
5204
Guy Benyei11169dd2012-12-18 14:30:41 +00005205 case TYPE_BLOCK_POINTER: {
5206 if (Record.size() != 1) {
5207 Error("Incorrect encoding of block pointer type");
5208 return QualType();
5209 }
5210 QualType PointeeType = readType(*Loc.F, Record, Idx);
5211 return Context.getBlockPointerType(PointeeType);
5212 }
5213
5214 case TYPE_LVALUE_REFERENCE: {
5215 if (Record.size() != 2) {
5216 Error("Incorrect encoding of lvalue reference type");
5217 return QualType();
5218 }
5219 QualType PointeeType = readType(*Loc.F, Record, Idx);
5220 return Context.getLValueReferenceType(PointeeType, Record[1]);
5221 }
5222
5223 case TYPE_RVALUE_REFERENCE: {
5224 if (Record.size() != 1) {
5225 Error("Incorrect encoding of rvalue reference type");
5226 return QualType();
5227 }
5228 QualType PointeeType = readType(*Loc.F, Record, Idx);
5229 return Context.getRValueReferenceType(PointeeType);
5230 }
5231
5232 case TYPE_MEMBER_POINTER: {
5233 if (Record.size() != 2) {
5234 Error("Incorrect encoding of member pointer type");
5235 return QualType();
5236 }
5237 QualType PointeeType = readType(*Loc.F, Record, Idx);
5238 QualType ClassType = readType(*Loc.F, Record, Idx);
5239 if (PointeeType.isNull() || ClassType.isNull())
5240 return QualType();
5241
5242 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5243 }
5244
5245 case TYPE_CONSTANT_ARRAY: {
5246 QualType ElementType = readType(*Loc.F, Record, Idx);
5247 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5248 unsigned IndexTypeQuals = Record[2];
5249 unsigned Idx = 3;
5250 llvm::APInt Size = ReadAPInt(Record, Idx);
5251 return Context.getConstantArrayType(ElementType, Size,
5252 ASM, IndexTypeQuals);
5253 }
5254
5255 case TYPE_INCOMPLETE_ARRAY: {
5256 QualType ElementType = readType(*Loc.F, Record, Idx);
5257 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5258 unsigned IndexTypeQuals = Record[2];
5259 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5260 }
5261
5262 case TYPE_VARIABLE_ARRAY: {
5263 QualType ElementType = readType(*Loc.F, Record, Idx);
5264 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5265 unsigned IndexTypeQuals = Record[2];
5266 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5267 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5268 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5269 ASM, IndexTypeQuals,
5270 SourceRange(LBLoc, RBLoc));
5271 }
5272
5273 case TYPE_VECTOR: {
5274 if (Record.size() != 3) {
5275 Error("incorrect encoding of vector type in AST file");
5276 return QualType();
5277 }
5278
5279 QualType ElementType = readType(*Loc.F, Record, Idx);
5280 unsigned NumElements = Record[1];
5281 unsigned VecKind = Record[2];
5282 return Context.getVectorType(ElementType, NumElements,
5283 (VectorType::VectorKind)VecKind);
5284 }
5285
5286 case TYPE_EXT_VECTOR: {
5287 if (Record.size() != 3) {
5288 Error("incorrect encoding of extended vector type in AST file");
5289 return QualType();
5290 }
5291
5292 QualType ElementType = readType(*Loc.F, Record, Idx);
5293 unsigned NumElements = Record[1];
5294 return Context.getExtVectorType(ElementType, NumElements);
5295 }
5296
5297 case TYPE_FUNCTION_NO_PROTO: {
5298 if (Record.size() != 6) {
5299 Error("incorrect encoding of no-proto function type");
5300 return QualType();
5301 }
5302 QualType ResultType = readType(*Loc.F, Record, Idx);
5303 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5304 (CallingConv)Record[4], Record[5]);
5305 return Context.getFunctionNoProtoType(ResultType, Info);
5306 }
5307
5308 case TYPE_FUNCTION_PROTO: {
5309 QualType ResultType = readType(*Loc.F, Record, Idx);
5310
5311 FunctionProtoType::ExtProtoInfo EPI;
5312 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5313 /*hasregparm*/ Record[2],
5314 /*regparm*/ Record[3],
5315 static_cast<CallingConv>(Record[4]),
5316 /*produces*/ Record[5]);
5317
5318 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005319
5320 EPI.Variadic = Record[Idx++];
5321 EPI.HasTrailingReturn = Record[Idx++];
5322 EPI.TypeQuals = Record[Idx++];
5323 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005324 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005325 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005326
5327 unsigned NumParams = Record[Idx++];
5328 SmallVector<QualType, 16> ParamTypes;
5329 for (unsigned I = 0; I != NumParams; ++I)
5330 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5331
Jordan Rose5c382722013-03-08 21:51:21 +00005332 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005333 }
5334
5335 case TYPE_UNRESOLVED_USING: {
5336 unsigned Idx = 0;
5337 return Context.getTypeDeclType(
5338 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5339 }
5340
5341 case TYPE_TYPEDEF: {
5342 if (Record.size() != 2) {
5343 Error("incorrect encoding of typedef type");
5344 return QualType();
5345 }
5346 unsigned Idx = 0;
5347 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5348 QualType Canonical = readType(*Loc.F, Record, Idx);
5349 if (!Canonical.isNull())
5350 Canonical = Context.getCanonicalType(Canonical);
5351 return Context.getTypedefType(Decl, Canonical);
5352 }
5353
5354 case TYPE_TYPEOF_EXPR:
5355 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5356
5357 case TYPE_TYPEOF: {
5358 if (Record.size() != 1) {
5359 Error("incorrect encoding of typeof(type) in AST file");
5360 return QualType();
5361 }
5362 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5363 return Context.getTypeOfType(UnderlyingType);
5364 }
5365
5366 case TYPE_DECLTYPE: {
5367 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5368 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5369 }
5370
5371 case TYPE_UNARY_TRANSFORM: {
5372 QualType BaseType = readType(*Loc.F, Record, Idx);
5373 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5374 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5375 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5376 }
5377
Richard Smith74aeef52013-04-26 16:15:35 +00005378 case TYPE_AUTO: {
5379 QualType Deduced = readType(*Loc.F, Record, Idx);
5380 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005381 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005382 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005383 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005384
5385 case TYPE_RECORD: {
5386 if (Record.size() != 2) {
5387 Error("incorrect encoding of record type");
5388 return QualType();
5389 }
5390 unsigned Idx = 0;
5391 bool IsDependent = Record[Idx++];
5392 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5393 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5394 QualType T = Context.getRecordType(RD);
5395 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5396 return T;
5397 }
5398
5399 case TYPE_ENUM: {
5400 if (Record.size() != 2) {
5401 Error("incorrect encoding of enum type");
5402 return QualType();
5403 }
5404 unsigned Idx = 0;
5405 bool IsDependent = Record[Idx++];
5406 QualType T
5407 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5408 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5409 return T;
5410 }
5411
5412 case TYPE_ATTRIBUTED: {
5413 if (Record.size() != 3) {
5414 Error("incorrect encoding of attributed type");
5415 return QualType();
5416 }
5417 QualType modifiedType = readType(*Loc.F, Record, Idx);
5418 QualType equivalentType = readType(*Loc.F, Record, Idx);
5419 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5420 return Context.getAttributedType(kind, modifiedType, equivalentType);
5421 }
5422
5423 case TYPE_PAREN: {
5424 if (Record.size() != 1) {
5425 Error("incorrect encoding of paren type");
5426 return QualType();
5427 }
5428 QualType InnerType = readType(*Loc.F, Record, Idx);
5429 return Context.getParenType(InnerType);
5430 }
5431
5432 case TYPE_PACK_EXPANSION: {
5433 if (Record.size() != 2) {
5434 Error("incorrect encoding of pack expansion type");
5435 return QualType();
5436 }
5437 QualType Pattern = readType(*Loc.F, Record, Idx);
5438 if (Pattern.isNull())
5439 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005440 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005441 if (Record[1])
5442 NumExpansions = Record[1] - 1;
5443 return Context.getPackExpansionType(Pattern, NumExpansions);
5444 }
5445
5446 case TYPE_ELABORATED: {
5447 unsigned Idx = 0;
5448 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5449 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5450 QualType NamedType = readType(*Loc.F, Record, Idx);
5451 return Context.getElaboratedType(Keyword, NNS, NamedType);
5452 }
5453
5454 case TYPE_OBJC_INTERFACE: {
5455 unsigned Idx = 0;
5456 ObjCInterfaceDecl *ItfD
5457 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5458 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5459 }
5460
5461 case TYPE_OBJC_OBJECT: {
5462 unsigned Idx = 0;
5463 QualType Base = readType(*Loc.F, Record, Idx);
5464 unsigned NumProtos = Record[Idx++];
5465 SmallVector<ObjCProtocolDecl*, 4> Protos;
5466 for (unsigned I = 0; I != NumProtos; ++I)
5467 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5468 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5469 }
5470
5471 case TYPE_OBJC_OBJECT_POINTER: {
5472 unsigned Idx = 0;
5473 QualType Pointee = readType(*Loc.F, Record, Idx);
5474 return Context.getObjCObjectPointerType(Pointee);
5475 }
5476
5477 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5478 unsigned Idx = 0;
5479 QualType Parm = readType(*Loc.F, Record, Idx);
5480 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005481 return Context.getSubstTemplateTypeParmType(
5482 cast<TemplateTypeParmType>(Parm),
5483 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005484 }
5485
5486 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5487 unsigned Idx = 0;
5488 QualType Parm = readType(*Loc.F, Record, Idx);
5489 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5490 return Context.getSubstTemplateTypeParmPackType(
5491 cast<TemplateTypeParmType>(Parm),
5492 ArgPack);
5493 }
5494
5495 case TYPE_INJECTED_CLASS_NAME: {
5496 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5497 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5498 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5499 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005500 const Type *T = nullptr;
5501 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5502 if (const Type *Existing = DI->getTypeForDecl()) {
5503 T = Existing;
5504 break;
5505 }
5506 }
5507 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005508 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005509 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5510 DI->setTypeForDecl(T);
5511 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005512 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005513 }
5514
5515 case TYPE_TEMPLATE_TYPE_PARM: {
5516 unsigned Idx = 0;
5517 unsigned Depth = Record[Idx++];
5518 unsigned Index = Record[Idx++];
5519 bool Pack = Record[Idx++];
5520 TemplateTypeParmDecl *D
5521 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5522 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5523 }
5524
5525 case TYPE_DEPENDENT_NAME: {
5526 unsigned Idx = 0;
5527 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5528 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5529 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5530 QualType Canon = readType(*Loc.F, Record, Idx);
5531 if (!Canon.isNull())
5532 Canon = Context.getCanonicalType(Canon);
5533 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5534 }
5535
5536 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5537 unsigned Idx = 0;
5538 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5539 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5540 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5541 unsigned NumArgs = Record[Idx++];
5542 SmallVector<TemplateArgument, 8> Args;
5543 Args.reserve(NumArgs);
5544 while (NumArgs--)
5545 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5546 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5547 Args.size(), Args.data());
5548 }
5549
5550 case TYPE_DEPENDENT_SIZED_ARRAY: {
5551 unsigned Idx = 0;
5552
5553 // ArrayType
5554 QualType ElementType = readType(*Loc.F, Record, Idx);
5555 ArrayType::ArraySizeModifier ASM
5556 = (ArrayType::ArraySizeModifier)Record[Idx++];
5557 unsigned IndexTypeQuals = Record[Idx++];
5558
5559 // DependentSizedArrayType
5560 Expr *NumElts = ReadExpr(*Loc.F);
5561 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5562
5563 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5564 IndexTypeQuals, Brackets);
5565 }
5566
5567 case TYPE_TEMPLATE_SPECIALIZATION: {
5568 unsigned Idx = 0;
5569 bool IsDependent = Record[Idx++];
5570 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5571 SmallVector<TemplateArgument, 8> Args;
5572 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5573 QualType Underlying = readType(*Loc.F, Record, Idx);
5574 QualType T;
5575 if (Underlying.isNull())
5576 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5577 Args.size());
5578 else
5579 T = Context.getTemplateSpecializationType(Name, Args.data(),
5580 Args.size(), Underlying);
5581 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5582 return T;
5583 }
5584
5585 case TYPE_ATOMIC: {
5586 if (Record.size() != 1) {
5587 Error("Incorrect encoding of atomic type");
5588 return QualType();
5589 }
5590 QualType ValueType = readType(*Loc.F, Record, Idx);
5591 return Context.getAtomicType(ValueType);
5592 }
5593 }
5594 llvm_unreachable("Invalid TypeCode!");
5595}
5596
Richard Smith564417a2014-03-20 21:47:22 +00005597void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5598 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005599 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005600 const RecordData &Record, unsigned &Idx) {
5601 ExceptionSpecificationType EST =
5602 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005603 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005604 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005605 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005606 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005607 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005608 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005609 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005610 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005611 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5612 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005613 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005614 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005615 }
5616}
5617
Guy Benyei11169dd2012-12-18 14:30:41 +00005618class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5619 ASTReader &Reader;
5620 ModuleFile &F;
5621 const ASTReader::RecordData &Record;
5622 unsigned &Idx;
5623
5624 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5625 unsigned &I) {
5626 return Reader.ReadSourceLocation(F, R, I);
5627 }
5628
5629 template<typename T>
5630 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5631 return Reader.ReadDeclAs<T>(F, Record, Idx);
5632 }
5633
5634public:
5635 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5636 const ASTReader::RecordData &Record, unsigned &Idx)
5637 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5638 { }
5639
5640 // We want compile-time assurance that we've enumerated all of
5641 // these, so unfortunately we have to declare them first, then
5642 // define them out-of-line.
5643#define ABSTRACT_TYPELOC(CLASS, PARENT)
5644#define TYPELOC(CLASS, PARENT) \
5645 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5646#include "clang/AST/TypeLocNodes.def"
5647
5648 void VisitFunctionTypeLoc(FunctionTypeLoc);
5649 void VisitArrayTypeLoc(ArrayTypeLoc);
5650};
5651
5652void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5653 // nothing to do
5654}
5655void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5656 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5657 if (TL.needsExtraLocalData()) {
5658 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5659 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5660 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5661 TL.setModeAttr(Record[Idx++]);
5662 }
5663}
5664void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5665 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5666}
5667void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5668 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5669}
Reid Kleckner8a365022013-06-24 17:51:48 +00005670void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5671 // nothing to do
5672}
Reid Kleckner0503a872013-12-05 01:23:43 +00005673void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5674 // nothing to do
5675}
Guy Benyei11169dd2012-12-18 14:30:41 +00005676void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5677 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5678}
5679void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5680 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5681}
5682void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5683 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5684}
5685void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5686 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5687 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5688}
5689void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5690 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5691 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5692 if (Record[Idx++])
5693 TL.setSizeExpr(Reader.ReadExpr(F));
5694 else
Craig Toppera13603a2014-05-22 05:54:18 +00005695 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005696}
5697void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5698 VisitArrayTypeLoc(TL);
5699}
5700void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5701 VisitArrayTypeLoc(TL);
5702}
5703void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5704 VisitArrayTypeLoc(TL);
5705}
5706void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5707 DependentSizedArrayTypeLoc TL) {
5708 VisitArrayTypeLoc(TL);
5709}
5710void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5711 DependentSizedExtVectorTypeLoc TL) {
5712 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5713}
5714void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5715 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5716}
5717void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5718 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5719}
5720void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5721 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5722 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5723 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5724 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005725 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5726 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005727 }
5728}
5729void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5730 VisitFunctionTypeLoc(TL);
5731}
5732void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5733 VisitFunctionTypeLoc(TL);
5734}
5735void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5736 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5737}
5738void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5739 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5740}
5741void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5742 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5743 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5744 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5745}
5746void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5747 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5748 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5749 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5750 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5751}
5752void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5753 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5754}
5755void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5756 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5757 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5758 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5759 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5760}
5761void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5762 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5763}
5764void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5765 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5766}
5767void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5768 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5769}
5770void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5771 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5772 if (TL.hasAttrOperand()) {
5773 SourceRange range;
5774 range.setBegin(ReadSourceLocation(Record, Idx));
5775 range.setEnd(ReadSourceLocation(Record, Idx));
5776 TL.setAttrOperandParensRange(range);
5777 }
5778 if (TL.hasAttrExprOperand()) {
5779 if (Record[Idx++])
5780 TL.setAttrExprOperand(Reader.ReadExpr(F));
5781 else
Craig Toppera13603a2014-05-22 05:54:18 +00005782 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005783 } else if (TL.hasAttrEnumOperand())
5784 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5785}
5786void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5787 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5788}
5789void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5790 SubstTemplateTypeParmTypeLoc TL) {
5791 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5792}
5793void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5794 SubstTemplateTypeParmPackTypeLoc TL) {
5795 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5796}
5797void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5798 TemplateSpecializationTypeLoc TL) {
5799 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5800 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5801 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5802 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5803 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5804 TL.setArgLocInfo(i,
5805 Reader.GetTemplateArgumentLocInfo(F,
5806 TL.getTypePtr()->getArg(i).getKind(),
5807 Record, Idx));
5808}
5809void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5810 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5811 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5812}
5813void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5814 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5815 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5816}
5817void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5818 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5819}
5820void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5821 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5822 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5823 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5824}
5825void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5826 DependentTemplateSpecializationTypeLoc TL) {
5827 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5828 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5829 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5830 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5831 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5832 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5833 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5834 TL.setArgLocInfo(I,
5835 Reader.GetTemplateArgumentLocInfo(F,
5836 TL.getTypePtr()->getArg(I).getKind(),
5837 Record, Idx));
5838}
5839void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5840 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5841}
5842void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5843 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5844}
5845void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5846 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5847 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5848 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5849 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5850 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5851}
5852void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5853 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5854}
5855void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5856 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5857 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5858 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5859}
5860
5861TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5862 const RecordData &Record,
5863 unsigned &Idx) {
5864 QualType InfoTy = readType(F, Record, Idx);
5865 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005866 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005867
5868 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5869 TypeLocReader TLR(*this, F, Record, Idx);
5870 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5871 TLR.Visit(TL);
5872 return TInfo;
5873}
5874
5875QualType ASTReader::GetType(TypeID ID) {
5876 unsigned FastQuals = ID & Qualifiers::FastMask;
5877 unsigned Index = ID >> Qualifiers::FastWidth;
5878
5879 if (Index < NUM_PREDEF_TYPE_IDS) {
5880 QualType T;
5881 switch ((PredefinedTypeIDs)Index) {
5882 case PREDEF_TYPE_NULL_ID: return QualType();
5883 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5884 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5885
5886 case PREDEF_TYPE_CHAR_U_ID:
5887 case PREDEF_TYPE_CHAR_S_ID:
5888 // FIXME: Check that the signedness of CharTy is correct!
5889 T = Context.CharTy;
5890 break;
5891
5892 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5893 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5894 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5895 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5896 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5897 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5898 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5899 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5900 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5901 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5902 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5903 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5904 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5905 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5906 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5907 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5908 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5909 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5910 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5911 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5912 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5913 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5914 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5915 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5916 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5917 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5918 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5919 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005920 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5921 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5922 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5923 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5924 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5925 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005926 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005927 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005928 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5929
5930 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5931 T = Context.getAutoRRefDeductType();
5932 break;
5933
5934 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5935 T = Context.ARCUnbridgedCastTy;
5936 break;
5937
5938 case PREDEF_TYPE_VA_LIST_TAG:
5939 T = Context.getVaListTagType();
5940 break;
5941
5942 case PREDEF_TYPE_BUILTIN_FN:
5943 T = Context.BuiltinFnTy;
5944 break;
5945 }
5946
5947 assert(!T.isNull() && "Unknown predefined type");
5948 return T.withFastQualifiers(FastQuals);
5949 }
5950
5951 Index -= NUM_PREDEF_TYPE_IDS;
5952 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5953 if (TypesLoaded[Index].isNull()) {
5954 TypesLoaded[Index] = readTypeRecord(Index);
5955 if (TypesLoaded[Index].isNull())
5956 return QualType();
5957
5958 TypesLoaded[Index]->setFromAST();
5959 if (DeserializationListener)
5960 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5961 TypesLoaded[Index]);
5962 }
5963
5964 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5965}
5966
5967QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5968 return GetType(getGlobalTypeID(F, LocalID));
5969}
5970
5971serialization::TypeID
5972ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5973 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5974 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5975
5976 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5977 return LocalID;
5978
5979 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5980 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5981 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5982
5983 unsigned GlobalIndex = LocalIndex + I->second;
5984 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5985}
5986
5987TemplateArgumentLocInfo
5988ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5989 TemplateArgument::ArgKind Kind,
5990 const RecordData &Record,
5991 unsigned &Index) {
5992 switch (Kind) {
5993 case TemplateArgument::Expression:
5994 return ReadExpr(F);
5995 case TemplateArgument::Type:
5996 return GetTypeSourceInfo(F, Record, Index);
5997 case TemplateArgument::Template: {
5998 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5999 Index);
6000 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6001 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6002 SourceLocation());
6003 }
6004 case TemplateArgument::TemplateExpansion: {
6005 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6006 Index);
6007 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6008 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6009 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6010 EllipsisLoc);
6011 }
6012 case TemplateArgument::Null:
6013 case TemplateArgument::Integral:
6014 case TemplateArgument::Declaration:
6015 case TemplateArgument::NullPtr:
6016 case TemplateArgument::Pack:
6017 // FIXME: Is this right?
6018 return TemplateArgumentLocInfo();
6019 }
6020 llvm_unreachable("unexpected template argument loc");
6021}
6022
6023TemplateArgumentLoc
6024ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6025 const RecordData &Record, unsigned &Index) {
6026 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6027
6028 if (Arg.getKind() == TemplateArgument::Expression) {
6029 if (Record[Index++]) // bool InfoHasSameExpr.
6030 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6031 }
6032 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6033 Record, Index));
6034}
6035
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006036const ASTTemplateArgumentListInfo*
6037ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6038 const RecordData &Record,
6039 unsigned &Index) {
6040 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6041 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6042 unsigned NumArgsAsWritten = Record[Index++];
6043 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6044 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6045 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6046 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6047}
6048
Guy Benyei11169dd2012-12-18 14:30:41 +00006049Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6050 return GetDecl(ID);
6051}
6052
Richard Smith50895422015-01-31 03:04:55 +00006053template<typename TemplateSpecializationDecl>
6054static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6055 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6056 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6057}
6058
Richard Smith053f6c62014-05-16 23:01:30 +00006059void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006060 if (NumCurrentElementsDeserializing) {
6061 // We arrange to not care about the complete redeclaration chain while we're
6062 // deserializing. Just remember that the AST has marked this one as complete
6063 // but that it's not actually complete yet, so we know we still need to
6064 // complete it later.
6065 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6066 return;
6067 }
6068
Richard Smith053f6c62014-05-16 23:01:30 +00006069 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6070
Richard Smith053f6c62014-05-16 23:01:30 +00006071 // If this is a named declaration, complete it by looking it up
6072 // within its context.
6073 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006074 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006075 // all mergeable entities within it.
6076 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6077 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6078 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
6079 auto *II = Name.getAsIdentifierInfo();
6080 if (isa<TranslationUnitDecl>(DC) && II) {
6081 // Outside of C++, we don't have a lookup table for the TU, so update
6082 // the identifier instead. In C++, either way should work fine.
6083 if (II->isOutOfDate())
6084 updateOutOfDateIdentifier(*II);
6085 } else
6086 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006087 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
6088 // FIXME: It'd be nice to do something a bit more targeted here.
6089 D->getDeclContext()->decls_begin();
Richard Smith053f6c62014-05-16 23:01:30 +00006090 }
6091 }
Richard Smith50895422015-01-31 03:04:55 +00006092
6093 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6094 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6095 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6096 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6097 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6098 if (auto *Template = FD->getPrimaryTemplate())
6099 Template->LoadLazySpecializations();
6100 }
Richard Smith053f6c62014-05-16 23:01:30 +00006101}
6102
Richard Smithc2bb8182015-03-24 06:36:48 +00006103uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
6104 const RecordData &Record,
6105 unsigned &Idx) {
6106 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
6107 Error("malformed AST file: missing C++ ctor initializers");
6108 return 0;
6109 }
6110
6111 unsigned LocalID = Record[Idx++];
6112 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
6113}
6114
6115CXXCtorInitializer **
6116ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6117 RecordLocation Loc = getLocalBitOffset(Offset);
6118 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6119 SavedStreamPosition SavedPosition(Cursor);
6120 Cursor.JumpToBit(Loc.Offset);
6121 ReadingKindTracker ReadingKind(Read_Decl, *this);
6122
6123 RecordData Record;
6124 unsigned Code = Cursor.ReadCode();
6125 unsigned RecCode = Cursor.readRecord(Code, Record);
6126 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6127 Error("malformed AST file: missing C++ ctor initializers");
6128 return nullptr;
6129 }
6130
6131 unsigned Idx = 0;
6132 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6133}
6134
Richard Smithcd45dbc2014-04-19 03:48:30 +00006135uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6136 const RecordData &Record,
6137 unsigned &Idx) {
6138 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6139 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006140 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006141 }
6142
Guy Benyei11169dd2012-12-18 14:30:41 +00006143 unsigned LocalID = Record[Idx++];
6144 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6145}
6146
6147CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6148 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006149 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006150 SavedStreamPosition SavedPosition(Cursor);
6151 Cursor.JumpToBit(Loc.Offset);
6152 ReadingKindTracker ReadingKind(Read_Decl, *this);
6153 RecordData Record;
6154 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006155 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006156 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006157 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006158 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006159 }
6160
6161 unsigned Idx = 0;
6162 unsigned NumBases = Record[Idx++];
6163 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6164 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6165 for (unsigned I = 0; I != NumBases; ++I)
6166 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6167 return Bases;
6168}
6169
6170serialization::DeclID
6171ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6172 if (LocalID < NUM_PREDEF_DECL_IDS)
6173 return LocalID;
6174
6175 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6176 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6177 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6178
6179 return LocalID + I->second;
6180}
6181
6182bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6183 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006184 // Predefined decls aren't from any module.
6185 if (ID < NUM_PREDEF_DECL_IDS)
6186 return false;
6187
Guy Benyei11169dd2012-12-18 14:30:41 +00006188 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6189 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6190 return &M == I->second;
6191}
6192
Douglas Gregor9f782892013-01-21 15:25:38 +00006193ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006194 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006195 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006196 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6197 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6198 return I->second;
6199}
6200
6201SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6202 if (ID < NUM_PREDEF_DECL_IDS)
6203 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006204
Guy Benyei11169dd2012-12-18 14:30:41 +00006205 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6206
6207 if (Index > DeclsLoaded.size()) {
6208 Error("declaration ID out-of-range for AST file");
6209 return SourceLocation();
6210 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006211
Guy Benyei11169dd2012-12-18 14:30:41 +00006212 if (Decl *D = DeclsLoaded[Index])
6213 return D->getLocation();
6214
6215 unsigned RawLocation = 0;
6216 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6217 return ReadSourceLocation(*Rec.F, RawLocation);
6218}
6219
Richard Smithfe620d22015-03-05 23:24:12 +00006220static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6221 switch (ID) {
6222 case PREDEF_DECL_NULL_ID:
6223 return nullptr;
6224
6225 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6226 return Context.getTranslationUnitDecl();
6227
6228 case PREDEF_DECL_OBJC_ID_ID:
6229 return Context.getObjCIdDecl();
6230
6231 case PREDEF_DECL_OBJC_SEL_ID:
6232 return Context.getObjCSelDecl();
6233
6234 case PREDEF_DECL_OBJC_CLASS_ID:
6235 return Context.getObjCClassDecl();
6236
6237 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6238 return Context.getObjCProtocolDecl();
6239
6240 case PREDEF_DECL_INT_128_ID:
6241 return Context.getInt128Decl();
6242
6243 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6244 return Context.getUInt128Decl();
6245
6246 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6247 return Context.getObjCInstanceTypeDecl();
6248
6249 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6250 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006251
6252 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6253 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006254 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006255 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006256}
6257
Richard Smithcd45dbc2014-04-19 03:48:30 +00006258Decl *ASTReader::GetExistingDecl(DeclID ID) {
6259 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006260 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6261 if (D) {
6262 // Track that we have merged the declaration with ID \p ID into the
6263 // pre-existing predefined declaration \p D.
6264 auto &Merged = MergedDecls[D->getCanonicalDecl()];
6265 if (Merged.empty())
6266 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006267 }
Richard Smithfe620d22015-03-05 23:24:12 +00006268 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006269 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006270
Guy Benyei11169dd2012-12-18 14:30:41 +00006271 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6272
6273 if (Index >= DeclsLoaded.size()) {
6274 assert(0 && "declaration ID out-of-range for AST file");
6275 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006276 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006277 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006278
6279 return DeclsLoaded[Index];
6280}
6281
6282Decl *ASTReader::GetDecl(DeclID ID) {
6283 if (ID < NUM_PREDEF_DECL_IDS)
6284 return GetExistingDecl(ID);
6285
6286 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6287
6288 if (Index >= DeclsLoaded.size()) {
6289 assert(0 && "declaration ID out-of-range for AST file");
6290 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006291 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006292 }
6293
Guy Benyei11169dd2012-12-18 14:30:41 +00006294 if (!DeclsLoaded[Index]) {
6295 ReadDeclRecord(ID);
6296 if (DeserializationListener)
6297 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6298 }
6299
6300 return DeclsLoaded[Index];
6301}
6302
6303DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6304 DeclID GlobalID) {
6305 if (GlobalID < NUM_PREDEF_DECL_IDS)
6306 return GlobalID;
6307
6308 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6309 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6310 ModuleFile *Owner = I->second;
6311
6312 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6313 = M.GlobalToLocalDeclIDs.find(Owner);
6314 if (Pos == M.GlobalToLocalDeclIDs.end())
6315 return 0;
6316
6317 return GlobalID - Owner->BaseDeclID + Pos->second;
6318}
6319
6320serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6321 const RecordData &Record,
6322 unsigned &Idx) {
6323 if (Idx >= Record.size()) {
6324 Error("Corrupted AST file");
6325 return 0;
6326 }
6327
6328 return getGlobalDeclID(F, Record[Idx++]);
6329}
6330
6331/// \brief Resolve the offset of a statement into a statement.
6332///
6333/// This operation will read a new statement from the external
6334/// source each time it is called, and is meant to be used via a
6335/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6336Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6337 // Switch case IDs are per Decl.
6338 ClearSwitchCaseIDs();
6339
6340 // Offset here is a global offset across the entire chain.
6341 RecordLocation Loc = getLocalBitOffset(Offset);
6342 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6343 return ReadStmtFromStream(*Loc.F);
6344}
6345
6346namespace {
6347 class FindExternalLexicalDeclsVisitor {
6348 ASTReader &Reader;
6349 const DeclContext *DC;
6350 bool (*isKindWeWant)(Decl::Kind);
6351
6352 SmallVectorImpl<Decl*> &Decls;
6353 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6354
6355 public:
6356 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6357 bool (*isKindWeWant)(Decl::Kind),
6358 SmallVectorImpl<Decl*> &Decls)
6359 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6360 {
6361 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6362 PredefsVisited[I] = false;
6363 }
6364
6365 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6366 if (Preorder)
6367 return false;
6368
6369 FindExternalLexicalDeclsVisitor *This
6370 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6371
6372 ModuleFile::DeclContextInfosMap::iterator Info
6373 = M.DeclContextInfos.find(This->DC);
6374 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6375 return false;
6376
6377 // Load all of the declaration IDs
6378 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6379 *IDE = ID + Info->second.NumLexicalDecls;
6380 ID != IDE; ++ID) {
6381 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6382 continue;
6383
6384 // Don't add predefined declarations to the lexical context more
6385 // than once.
6386 if (ID->second < NUM_PREDEF_DECL_IDS) {
6387 if (This->PredefsVisited[ID->second])
6388 continue;
6389
6390 This->PredefsVisited[ID->second] = true;
6391 }
6392
6393 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6394 if (!This->DC->isDeclInLexicalTraversal(D))
6395 This->Decls.push_back(D);
6396 }
6397 }
6398
6399 return false;
6400 }
6401 };
6402}
6403
6404ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6405 bool (*isKindWeWant)(Decl::Kind),
6406 SmallVectorImpl<Decl*> &Decls) {
6407 // There might be lexical decls in multiple modules, for the TU at
6408 // least. Walk all of the modules in the order they were loaded.
6409 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6410 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6411 ++NumLexicalDeclContextsRead;
6412 return ELR_Success;
6413}
6414
6415namespace {
6416
6417class DeclIDComp {
6418 ASTReader &Reader;
6419 ModuleFile &Mod;
6420
6421public:
6422 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6423
6424 bool operator()(LocalDeclID L, LocalDeclID R) const {
6425 SourceLocation LHS = getLocation(L);
6426 SourceLocation RHS = getLocation(R);
6427 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6428 }
6429
6430 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6431 SourceLocation RHS = getLocation(R);
6432 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6433 }
6434
6435 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6436 SourceLocation LHS = getLocation(L);
6437 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6438 }
6439
6440 SourceLocation getLocation(LocalDeclID ID) const {
6441 return Reader.getSourceManager().getFileLoc(
6442 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6443 }
6444};
6445
6446}
6447
6448void ASTReader::FindFileRegionDecls(FileID File,
6449 unsigned Offset, unsigned Length,
6450 SmallVectorImpl<Decl *> &Decls) {
6451 SourceManager &SM = getSourceManager();
6452
6453 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6454 if (I == FileDeclIDs.end())
6455 return;
6456
6457 FileDeclsInfo &DInfo = I->second;
6458 if (DInfo.Decls.empty())
6459 return;
6460
6461 SourceLocation
6462 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6463 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6464
6465 DeclIDComp DIDComp(*this, *DInfo.Mod);
6466 ArrayRef<serialization::LocalDeclID>::iterator
6467 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6468 BeginLoc, DIDComp);
6469 if (BeginIt != DInfo.Decls.begin())
6470 --BeginIt;
6471
6472 // If we are pointing at a top-level decl inside an objc container, we need
6473 // to backtrack until we find it otherwise we will fail to report that the
6474 // region overlaps with an objc container.
6475 while (BeginIt != DInfo.Decls.begin() &&
6476 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6477 ->isTopLevelDeclInObjCContainer())
6478 --BeginIt;
6479
6480 ArrayRef<serialization::LocalDeclID>::iterator
6481 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6482 EndLoc, DIDComp);
6483 if (EndIt != DInfo.Decls.end())
6484 ++EndIt;
6485
6486 for (ArrayRef<serialization::LocalDeclID>::iterator
6487 DIt = BeginIt; DIt != EndIt; ++DIt)
6488 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6489}
6490
6491namespace {
6492 /// \brief ModuleFile visitor used to perform name lookup into a
6493 /// declaration context.
6494 class DeclContextNameLookupVisitor {
6495 ASTReader &Reader;
Richard Smith8c913ec2014-08-14 02:21:01 +00006496 ArrayRef<const DeclContext *> Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006497 DeclarationName Name;
6498 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006499 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006500
6501 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006502 DeclContextNameLookupVisitor(ASTReader &Reader,
6503 ArrayRef<const DeclContext *> Contexts,
Guy Benyei11169dd2012-12-18 14:30:41 +00006504 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006505 SmallVectorImpl<NamedDecl *> &Decls,
6506 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
6507 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls),
6508 DeclSet(DeclSet) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006509
6510 static bool visit(ModuleFile &M, void *UserData) {
6511 DeclContextNameLookupVisitor *This
6512 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6513
6514 // Check whether we have any visible declaration information for
6515 // this context in this module.
6516 ModuleFile::DeclContextInfosMap::iterator Info;
6517 bool FoundInfo = false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006518 for (auto *DC : This->Contexts) {
6519 Info = M.DeclContextInfos.find(DC);
6520 if (Info != M.DeclContextInfos.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006521 Info->second.NameLookupTableData) {
6522 FoundInfo = true;
6523 break;
6524 }
6525 }
6526
6527 if (!FoundInfo)
6528 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006529
Guy Benyei11169dd2012-12-18 14:30:41 +00006530 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006531 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006532 Info->second.NameLookupTableData;
6533 ASTDeclContextNameLookupTable::iterator Pos
6534 = LookupTable->find(This->Name);
6535 if (Pos == LookupTable->end())
6536 return false;
6537
6538 bool FoundAnything = false;
6539 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6540 for (; Data.first != Data.second; ++Data.first) {
6541 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6542 if (!ND)
6543 continue;
6544
6545 if (ND->getDeclName() != This->Name) {
6546 // A name might be null because the decl's redeclarable part is
6547 // currently read before reading its name. The lookup is triggered by
6548 // building that decl (likely indirectly), and so it is later in the
6549 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006550 // FIXME: This should not happen; deserializing declarations should
6551 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006552 continue;
6553 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006554
Guy Benyei11169dd2012-12-18 14:30:41 +00006555 // Record this declaration.
6556 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006557 if (This->DeclSet.insert(ND).second)
6558 This->Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006559 }
6560
6561 return FoundAnything;
6562 }
6563 };
6564}
6565
Douglas Gregor9f782892013-01-21 15:25:38 +00006566/// \brief Retrieve the "definitive" module file for the definition of the
6567/// given declaration context, if there is one.
6568///
6569/// The "definitive" module file is the only place where we need to look to
6570/// find information about the declarations within the given declaration
6571/// context. For example, C++ and Objective-C classes, C structs/unions, and
6572/// Objective-C protocols, categories, and extensions are all defined in a
6573/// single place in the source code, so they have definitive module files
6574/// associated with them. C++ namespaces, on the other hand, can have
6575/// definitions in multiple different module files.
6576///
6577/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6578/// NDEBUG checking.
6579static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6580 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006581 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6582 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006583
Craig Toppera13603a2014-05-22 05:54:18 +00006584 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006585}
6586
Richard Smith9ce12e32013-02-07 03:30:24 +00006587bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006588ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6589 DeclarationName Name) {
6590 assert(DC->hasExternalVisibleStorage() &&
6591 "DeclContext has no visible decls in storage");
6592 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006593 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006594
Richard Smith8c913ec2014-08-14 02:21:01 +00006595 Deserializing LookupResults(this);
6596
Guy Benyei11169dd2012-12-18 14:30:41 +00006597 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006598 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006599
Guy Benyei11169dd2012-12-18 14:30:41 +00006600 // Compute the declaration contexts we need to look into. Multiple such
6601 // declaration contexts occur when two declaration contexts from disjoint
6602 // modules get merged, e.g., when two namespaces with the same name are
6603 // independently defined in separate modules.
6604 SmallVector<const DeclContext *, 2> Contexts;
6605 Contexts.push_back(DC);
Richard Smith8c913ec2014-08-14 02:21:01 +00006606
Guy Benyei11169dd2012-12-18 14:30:41 +00006607 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006608 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006609 if (Merged != MergedDecls.end()) {
6610 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6611 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6612 }
6613 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006614
6615 auto LookUpInContexts = [&](ArrayRef<const DeclContext*> Contexts) {
Richard Smith52874ec2015-02-13 20:17:14 +00006616 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls, DeclSet);
Richard Smith8c913ec2014-08-14 02:21:01 +00006617
6618 // If we can definitively determine which module file to look into,
6619 // only look there. Otherwise, look in all module files.
6620 ModuleFile *Definitive;
6621 if (Contexts.size() == 1 &&
6622 (Definitive = getDefinitiveModuleFileFor(Contexts[0], *this))) {
6623 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6624 } else {
6625 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6626 }
6627 };
6628
6629 LookUpInContexts(Contexts);
6630
6631 // If this might be an implicit special member function, then also search
6632 // all merged definitions of the surrounding class. We need to search them
6633 // individually, because finding an entity in one of them doesn't imply that
6634 // we can't find a different entity in another one.
Richard Smithcd45dbc2014-04-19 03:48:30 +00006635 if (isa<CXXRecordDecl>(DC)) {
Richard Smith02793752015-03-27 21:16:39 +00006636 auto Merged = MergedLookups.find(DC);
6637 if (Merged != MergedLookups.end()) {
6638 for (unsigned I = 0; I != Merged->second.size(); ++I) {
6639 const DeclContext *Context = Merged->second[I];
6640 LookUpInContexts(Context);
6641 // We might have just added some more merged lookups. If so, our
6642 // iterator is now invalid, so grab a fresh one before continuing.
6643 Merged = MergedLookups.find(DC);
Richard Smithe0612472014-11-21 05:16:13 +00006644 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006645 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006646 }
6647
Guy Benyei11169dd2012-12-18 14:30:41 +00006648 ++NumVisibleDeclContextsRead;
6649 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006650 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006651}
6652
6653namespace {
6654 /// \brief ModuleFile visitor used to retrieve all visible names in a
6655 /// declaration context.
6656 class DeclContextAllNamesVisitor {
6657 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006658 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006659 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006660 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006661 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006662
6663 public:
6664 DeclContextAllNamesVisitor(ASTReader &Reader,
6665 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006666 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006667 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006668
6669 static bool visit(ModuleFile &M, void *UserData) {
6670 DeclContextAllNamesVisitor *This
6671 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6672
6673 // Check whether we have any visible declaration information for
6674 // this context in this module.
6675 ModuleFile::DeclContextInfosMap::iterator Info;
6676 bool FoundInfo = false;
6677 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6678 Info = M.DeclContextInfos.find(This->Contexts[I]);
6679 if (Info != M.DeclContextInfos.end() &&
6680 Info->second.NameLookupTableData) {
6681 FoundInfo = true;
6682 break;
6683 }
6684 }
6685
6686 if (!FoundInfo)
6687 return false;
6688
Richard Smith52e3fba2014-03-11 07:17:35 +00006689 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006690 Info->second.NameLookupTableData;
6691 bool FoundAnything = false;
6692 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006693 I = LookupTable->data_begin(), E = LookupTable->data_end();
6694 I != E;
6695 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006696 ASTDeclContextNameLookupTrait::data_type Data = *I;
6697 for (; Data.first != Data.second; ++Data.first) {
6698 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6699 *Data.first);
6700 if (!ND)
6701 continue;
6702
6703 // Record this declaration.
6704 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006705 if (This->DeclSet.insert(ND).second)
6706 This->Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006707 }
6708 }
6709
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006710 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006711 }
6712 };
6713}
6714
6715void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6716 if (!DC->hasExternalVisibleStorage())
6717 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006718 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006719
6720 // Compute the declaration contexts we need to look into. Multiple such
6721 // declaration contexts occur when two declaration contexts from disjoint
6722 // modules get merged, e.g., when two namespaces with the same name are
6723 // independently defined in separate modules.
6724 SmallVector<const DeclContext *, 2> Contexts;
6725 Contexts.push_back(DC);
6726
6727 if (DC->isNamespace()) {
6728 MergedDeclsMap::iterator Merged
6729 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6730 if (Merged != MergedDecls.end()) {
6731 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6732 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6733 }
6734 }
6735
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006736 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6737 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006738 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6739 ++NumVisibleDeclContextsRead;
6740
Craig Topper79be4cd2013-07-05 04:33:53 +00006741 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006742 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6743 }
6744 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6745}
6746
6747/// \brief Under non-PCH compilation the consumer receives the objc methods
6748/// before receiving the implementation, and codegen depends on this.
6749/// We simulate this by deserializing and passing to consumer the methods of the
6750/// implementation before passing the deserialized implementation decl.
6751static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6752 ASTConsumer *Consumer) {
6753 assert(ImplD && Consumer);
6754
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006755 for (auto *I : ImplD->methods())
6756 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006757
6758 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6759}
6760
6761void ASTReader::PassInterestingDeclsToConsumer() {
6762 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006763
6764 if (PassingDeclsToConsumer)
6765 return;
6766
6767 // Guard variable to avoid recursively redoing the process of passing
6768 // decls to consumer.
6769 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6770 true);
6771
Richard Smith9e2341d2015-03-23 03:25:59 +00006772 // Ensure that we've loaded all potentially-interesting declarations
6773 // that need to be eagerly loaded.
6774 for (auto ID : EagerlyDeserializedDecls)
6775 GetDecl(ID);
6776 EagerlyDeserializedDecls.clear();
6777
Guy Benyei11169dd2012-12-18 14:30:41 +00006778 while (!InterestingDecls.empty()) {
6779 Decl *D = InterestingDecls.front();
6780 InterestingDecls.pop_front();
6781
6782 PassInterestingDeclToConsumer(D);
6783 }
6784}
6785
6786void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6787 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6788 PassObjCImplDeclToConsumer(ImplD, Consumer);
6789 else
6790 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6791}
6792
6793void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6794 this->Consumer = Consumer;
6795
Richard Smith9e2341d2015-03-23 03:25:59 +00006796 if (Consumer)
6797 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006798
6799 if (DeserializationListener)
6800 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006801}
6802
6803void ASTReader::PrintStats() {
6804 std::fprintf(stderr, "*** AST File Statistics:\n");
6805
6806 unsigned NumTypesLoaded
6807 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6808 QualType());
6809 unsigned NumDeclsLoaded
6810 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006811 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006812 unsigned NumIdentifiersLoaded
6813 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6814 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006815 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006816 unsigned NumMacrosLoaded
6817 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6818 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006819 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006820 unsigned NumSelectorsLoaded
6821 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6822 SelectorsLoaded.end(),
6823 Selector());
6824
6825 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6826 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6827 NumSLocEntriesRead, TotalNumSLocEntries,
6828 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6829 if (!TypesLoaded.empty())
6830 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6831 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6832 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6833 if (!DeclsLoaded.empty())
6834 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6835 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6836 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6837 if (!IdentifiersLoaded.empty())
6838 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6839 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6840 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6841 if (!MacrosLoaded.empty())
6842 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6843 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6844 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6845 if (!SelectorsLoaded.empty())
6846 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6847 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6848 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6849 if (TotalNumStatements)
6850 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6851 NumStatementsRead, TotalNumStatements,
6852 ((float)NumStatementsRead/TotalNumStatements * 100));
6853 if (TotalNumMacros)
6854 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6855 NumMacrosRead, TotalNumMacros,
6856 ((float)NumMacrosRead/TotalNumMacros * 100));
6857 if (TotalLexicalDeclContexts)
6858 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6859 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6860 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6861 * 100));
6862 if (TotalVisibleDeclContexts)
6863 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6864 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6865 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6866 * 100));
6867 if (TotalNumMethodPoolEntries) {
6868 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6869 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6870 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6871 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006872 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006873 if (NumMethodPoolLookups) {
6874 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6875 NumMethodPoolHits, NumMethodPoolLookups,
6876 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6877 }
6878 if (NumMethodPoolTableLookups) {
6879 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6880 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6881 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6882 * 100.0));
6883 }
6884
Douglas Gregor00a50f72013-01-25 00:38:33 +00006885 if (NumIdentifierLookupHits) {
6886 std::fprintf(stderr,
6887 " %u / %u identifier table lookups succeeded (%f%%)\n",
6888 NumIdentifierLookupHits, NumIdentifierLookups,
6889 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6890 }
6891
Douglas Gregore060e572013-01-25 01:03:03 +00006892 if (GlobalIndex) {
6893 std::fprintf(stderr, "\n");
6894 GlobalIndex->printStats();
6895 }
6896
Guy Benyei11169dd2012-12-18 14:30:41 +00006897 std::fprintf(stderr, "\n");
6898 dump();
6899 std::fprintf(stderr, "\n");
6900}
6901
6902template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6903static void
6904dumpModuleIDMap(StringRef Name,
6905 const ContinuousRangeMap<Key, ModuleFile *,
6906 InitialCapacity> &Map) {
6907 if (Map.begin() == Map.end())
6908 return;
6909
6910 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6911 llvm::errs() << Name << ":\n";
6912 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6913 I != IEnd; ++I) {
6914 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6915 << "\n";
6916 }
6917}
6918
6919void ASTReader::dump() {
6920 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6921 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6922 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6923 dumpModuleIDMap("Global type map", GlobalTypeMap);
6924 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6925 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6926 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6927 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6928 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6929 dumpModuleIDMap("Global preprocessed entity map",
6930 GlobalPreprocessedEntityMap);
6931
6932 llvm::errs() << "\n*** PCH/Modules Loaded:";
6933 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6934 MEnd = ModuleMgr.end();
6935 M != MEnd; ++M)
6936 (*M)->dump();
6937}
6938
6939/// Return the amount of memory used by memory buffers, breaking down
6940/// by heap-backed versus mmap'ed memory.
6941void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6942 for (ModuleConstIterator I = ModuleMgr.begin(),
6943 E = ModuleMgr.end(); I != E; ++I) {
6944 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6945 size_t bytes = buf->getBufferSize();
6946 switch (buf->getBufferKind()) {
6947 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6948 sizes.malloc_bytes += bytes;
6949 break;
6950 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6951 sizes.mmap_bytes += bytes;
6952 break;
6953 }
6954 }
6955 }
6956}
6957
6958void ASTReader::InitializeSema(Sema &S) {
6959 SemaObj = &S;
6960 S.addExternalSource(this);
6961
6962 // Makes sure any declarations that were deserialized "too early"
6963 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006964 for (uint64_t ID : PreloadedDeclIDs) {
6965 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6966 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006967 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006968 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006969
Richard Smith3d8e97e2013-10-18 06:54:39 +00006970 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006971 if (!FPPragmaOptions.empty()) {
6972 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6973 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6974 }
6975
Richard Smith3d8e97e2013-10-18 06:54:39 +00006976 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006977 if (!OpenCLExtensions.empty()) {
6978 unsigned I = 0;
6979#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6980#include "clang/Basic/OpenCLExtensions.def"
6981
6982 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6983 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006984
6985 UpdateSema();
6986}
6987
6988void ASTReader::UpdateSema() {
6989 assert(SemaObj && "no Sema to update");
6990
6991 // Load the offsets of the declarations that Sema references.
6992 // They will be lazily deserialized when needed.
6993 if (!SemaDeclRefs.empty()) {
6994 assert(SemaDeclRefs.size() % 2 == 0);
6995 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6996 if (!SemaObj->StdNamespace)
6997 SemaObj->StdNamespace = SemaDeclRefs[I];
6998 if (!SemaObj->StdBadAlloc)
6999 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
7000 }
7001 SemaDeclRefs.clear();
7002 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007003
7004 // Update the state of 'pragma clang optimize'. Use the same API as if we had
7005 // encountered the pragma in the source.
7006 if(OptimizeOffPragmaLocation.isValid())
7007 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00007008}
7009
7010IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
7011 // Note that we are loading an identifier.
7012 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007013 StringRef Name(NameStart, NameEnd - NameStart);
7014
7015 // If there is a global index, look there first to determine which modules
7016 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00007017 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00007018 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00007019 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00007020 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7021 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00007022 }
7023 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00007024 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007025 NumIdentifierLookups,
7026 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00007027 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007028 IdentifierInfo *II = Visitor.getIdentifierInfo();
7029 markIdentifierUpToDate(II);
7030 return II;
7031}
7032
7033namespace clang {
7034 /// \brief An identifier-lookup iterator that enumerates all of the
7035 /// identifiers stored within a set of AST files.
7036 class ASTIdentifierIterator : public IdentifierIterator {
7037 /// \brief The AST reader whose identifiers are being enumerated.
7038 const ASTReader &Reader;
7039
7040 /// \brief The current index into the chain of AST files stored in
7041 /// the AST reader.
7042 unsigned Index;
7043
7044 /// \brief The current position within the identifier lookup table
7045 /// of the current AST file.
7046 ASTIdentifierLookupTable::key_iterator Current;
7047
7048 /// \brief The end position within the identifier lookup table of
7049 /// the current AST file.
7050 ASTIdentifierLookupTable::key_iterator End;
7051
7052 public:
7053 explicit ASTIdentifierIterator(const ASTReader &Reader);
7054
Craig Topper3e89dfe2014-03-13 02:13:41 +00007055 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007056 };
7057}
7058
7059ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
7060 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
7061 ASTIdentifierLookupTable *IdTable
7062 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
7063 Current = IdTable->key_begin();
7064 End = IdTable->key_end();
7065}
7066
7067StringRef ASTIdentifierIterator::Next() {
7068 while (Current == End) {
7069 // If we have exhausted all of our AST files, we're done.
7070 if (Index == 0)
7071 return StringRef();
7072
7073 --Index;
7074 ASTIdentifierLookupTable *IdTable
7075 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
7076 IdentifierLookupTable;
7077 Current = IdTable->key_begin();
7078 End = IdTable->key_end();
7079 }
7080
7081 // We have any identifiers remaining in the current AST file; return
7082 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007083 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007084 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007085 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007086}
7087
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007088IdentifierIterator *ASTReader::getIdentifiers() {
7089 if (!loadGlobalIndex())
7090 return GlobalIndex->createIdentifierIterator();
7091
Guy Benyei11169dd2012-12-18 14:30:41 +00007092 return new ASTIdentifierIterator(*this);
7093}
7094
7095namespace clang { namespace serialization {
7096 class ReadMethodPoolVisitor {
7097 ASTReader &Reader;
7098 Selector Sel;
7099 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007100 unsigned InstanceBits;
7101 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007102 bool InstanceHasMoreThanOneDecl;
7103 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007104 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7105 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007106
7107 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007108 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007109 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007110 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007111 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7112 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007113
Guy Benyei11169dd2012-12-18 14:30:41 +00007114 static bool visit(ModuleFile &M, void *UserData) {
7115 ReadMethodPoolVisitor *This
7116 = static_cast<ReadMethodPoolVisitor *>(UserData);
7117
7118 if (!M.SelectorLookupTable)
7119 return false;
7120
7121 // If we've already searched this module file, skip it now.
7122 if (M.Generation <= This->PriorGeneration)
7123 return true;
7124
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007125 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007126 ASTSelectorLookupTable *PoolTable
7127 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
7128 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
7129 if (Pos == PoolTable->end())
7130 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007131
7132 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00007133 ++This->Reader.NumSelectorsRead;
7134 // FIXME: Not quite happy with the statistics here. We probably should
7135 // disable this tracking when called via LoadSelector.
7136 // Also, should entries without methods count as misses?
7137 ++This->Reader.NumMethodPoolEntriesRead;
7138 ASTSelectorLookupTrait::data_type Data = *Pos;
7139 if (This->Reader.DeserializationListener)
7140 This->Reader.DeserializationListener->SelectorRead(Data.ID,
7141 This->Sel);
7142
7143 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7144 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007145 This->InstanceBits = Data.InstanceBits;
7146 This->FactoryBits = Data.FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007147 This->InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7148 This->FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007149 return true;
7150 }
7151
7152 /// \brief Retrieve the instance methods found by this visitor.
7153 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7154 return InstanceMethods;
7155 }
7156
7157 /// \brief Retrieve the instance methods found by this visitor.
7158 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7159 return FactoryMethods;
7160 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007161
7162 unsigned getInstanceBits() const { return InstanceBits; }
7163 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007164 bool instanceHasMoreThanOneDecl() const {
7165 return InstanceHasMoreThanOneDecl;
7166 }
7167 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007168 };
7169} } // end namespace clang::serialization
7170
7171/// \brief Add the given set of methods to the method list.
7172static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7173 ObjCMethodList &List) {
7174 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7175 S.addMethodToGlobalList(&List, Methods[I]);
7176 }
7177}
7178
7179void ASTReader::ReadMethodPool(Selector Sel) {
7180 // Get the selector generation and update it to the current generation.
7181 unsigned &Generation = SelectorGeneration[Sel];
7182 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007183 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007184
7185 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007186 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007187 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7188 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
7189
7190 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007191 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007192 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007193
7194 ++NumMethodPoolHits;
7195
Guy Benyei11169dd2012-12-18 14:30:41 +00007196 if (!getSema())
7197 return;
7198
7199 Sema &S = *getSema();
7200 Sema::GlobalMethodPool::iterator Pos
7201 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007202
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007203 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007204 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007205 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007206 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007207
7208 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7209 // when building a module we keep every method individually and may need to
7210 // update hasMoreThanOneDecl as we add the methods.
7211 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7212 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007213}
7214
7215void ASTReader::ReadKnownNamespaces(
7216 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7217 Namespaces.clear();
7218
7219 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7220 if (NamespaceDecl *Namespace
7221 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7222 Namespaces.push_back(Namespace);
7223 }
7224}
7225
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007226void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007227 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007228 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7229 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007230 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007231 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007232 Undefined.insert(std::make_pair(D, Loc));
7233 }
7234}
Nick Lewycky8334af82013-01-26 00:35:08 +00007235
Guy Benyei11169dd2012-12-18 14:30:41 +00007236void ASTReader::ReadTentativeDefinitions(
7237 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7238 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7239 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7240 if (Var)
7241 TentativeDefs.push_back(Var);
7242 }
7243 TentativeDefinitions.clear();
7244}
7245
7246void ASTReader::ReadUnusedFileScopedDecls(
7247 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7248 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7249 DeclaratorDecl *D
7250 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7251 if (D)
7252 Decls.push_back(D);
7253 }
7254 UnusedFileScopedDecls.clear();
7255}
7256
7257void ASTReader::ReadDelegatingConstructors(
7258 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7259 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7260 CXXConstructorDecl *D
7261 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7262 if (D)
7263 Decls.push_back(D);
7264 }
7265 DelegatingCtorDecls.clear();
7266}
7267
7268void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7269 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7270 TypedefNameDecl *D
7271 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7272 if (D)
7273 Decls.push_back(D);
7274 }
7275 ExtVectorDecls.clear();
7276}
7277
Nico Weber72889432014-09-06 01:25:55 +00007278void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7279 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7280 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7281 ++I) {
7282 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7283 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7284 if (D)
7285 Decls.insert(D);
7286 }
7287 UnusedLocalTypedefNameCandidates.clear();
7288}
7289
Guy Benyei11169dd2012-12-18 14:30:41 +00007290void ASTReader::ReadReferencedSelectors(
7291 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7292 if (ReferencedSelectorsData.empty())
7293 return;
7294
7295 // If there are @selector references added them to its pool. This is for
7296 // implementation of -Wselector.
7297 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7298 unsigned I = 0;
7299 while (I < DataSize) {
7300 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7301 SourceLocation SelLoc
7302 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7303 Sels.push_back(std::make_pair(Sel, SelLoc));
7304 }
7305 ReferencedSelectorsData.clear();
7306}
7307
7308void ASTReader::ReadWeakUndeclaredIdentifiers(
7309 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7310 if (WeakUndeclaredIdentifiers.empty())
7311 return;
7312
7313 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7314 IdentifierInfo *WeakId
7315 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7316 IdentifierInfo *AliasId
7317 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7318 SourceLocation Loc
7319 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7320 bool Used = WeakUndeclaredIdentifiers[I++];
7321 WeakInfo WI(AliasId, Loc);
7322 WI.setUsed(Used);
7323 WeakIDs.push_back(std::make_pair(WeakId, WI));
7324 }
7325 WeakUndeclaredIdentifiers.clear();
7326}
7327
7328void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7329 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7330 ExternalVTableUse VT;
7331 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7332 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7333 VT.DefinitionRequired = VTableUses[Idx++];
7334 VTables.push_back(VT);
7335 }
7336
7337 VTableUses.clear();
7338}
7339
7340void ASTReader::ReadPendingInstantiations(
7341 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7342 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7343 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7344 SourceLocation Loc
7345 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7346
7347 Pending.push_back(std::make_pair(D, Loc));
7348 }
7349 PendingInstantiations.clear();
7350}
7351
Richard Smithe40f2ba2013-08-07 21:41:30 +00007352void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007353 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007354 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7355 /* In loop */) {
7356 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7357
7358 LateParsedTemplate *LT = new LateParsedTemplate;
7359 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7360
7361 ModuleFile *F = getOwningModuleFile(LT->D);
7362 assert(F && "No module");
7363
7364 unsigned TokN = LateParsedTemplates[Idx++];
7365 LT->Toks.reserve(TokN);
7366 for (unsigned T = 0; T < TokN; ++T)
7367 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7368
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007369 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007370 }
7371
7372 LateParsedTemplates.clear();
7373}
7374
Guy Benyei11169dd2012-12-18 14:30:41 +00007375void ASTReader::LoadSelector(Selector Sel) {
7376 // It would be complicated to avoid reading the methods anyway. So don't.
7377 ReadMethodPool(Sel);
7378}
7379
7380void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7381 assert(ID && "Non-zero identifier ID required");
7382 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7383 IdentifiersLoaded[ID - 1] = II;
7384 if (DeserializationListener)
7385 DeserializationListener->IdentifierRead(ID, II);
7386}
7387
7388/// \brief Set the globally-visible declarations associated with the given
7389/// identifier.
7390///
7391/// If the AST reader is currently in a state where the given declaration IDs
7392/// cannot safely be resolved, they are queued until it is safe to resolve
7393/// them.
7394///
7395/// \param II an IdentifierInfo that refers to one or more globally-visible
7396/// declarations.
7397///
7398/// \param DeclIDs the set of declaration IDs with the name @p II that are
7399/// visible at global scope.
7400///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007401/// \param Decls if non-null, this vector will be populated with the set of
7402/// deserialized declarations. These declarations will not be pushed into
7403/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007404void
7405ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7406 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007407 SmallVectorImpl<Decl *> *Decls) {
7408 if (NumCurrentElementsDeserializing && !Decls) {
7409 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007410 return;
7411 }
7412
7413 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007414 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007415 // Queue this declaration so that it will be added to the
7416 // translation unit scope and identifier's declaration chain
7417 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007418 PreloadedDeclIDs.push_back(DeclIDs[I]);
7419 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007420 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007421
7422 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7423
7424 // If we're simply supposed to record the declarations, do so now.
7425 if (Decls) {
7426 Decls->push_back(D);
7427 continue;
7428 }
7429
7430 // Introduce this declaration into the translation-unit scope
7431 // and add it to the declaration chain for this identifier, so
7432 // that (unqualified) name lookup will find it.
7433 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007434 }
7435}
7436
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007437IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007438 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007439 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007440
7441 if (IdentifiersLoaded.empty()) {
7442 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007443 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007444 }
7445
7446 ID -= 1;
7447 if (!IdentifiersLoaded[ID]) {
7448 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7449 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7450 ModuleFile *M = I->second;
7451 unsigned Index = ID - M->BaseIdentifierID;
7452 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7453
7454 // All of the strings in the AST file are preceded by a 16-bit length.
7455 // Extract that 16-bit length to avoid having to execute strlen().
7456 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7457 // unsigned integers. This is important to avoid integer overflow when
7458 // we cast them to 'unsigned'.
7459 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7460 unsigned StrLen = (((unsigned) StrLenPtr[0])
7461 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007462 IdentifiersLoaded[ID]
7463 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007464 if (DeserializationListener)
7465 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7466 }
7467
7468 return IdentifiersLoaded[ID];
7469}
7470
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007471IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7472 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007473}
7474
7475IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7476 if (LocalID < NUM_PREDEF_IDENT_IDS)
7477 return LocalID;
7478
7479 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7480 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7481 assert(I != M.IdentifierRemap.end()
7482 && "Invalid index into identifier index remap");
7483
7484 return LocalID + I->second;
7485}
7486
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007487MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007488 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007489 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007490
7491 if (MacrosLoaded.empty()) {
7492 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007493 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007494 }
7495
7496 ID -= NUM_PREDEF_MACRO_IDS;
7497 if (!MacrosLoaded[ID]) {
7498 GlobalMacroMapType::iterator I
7499 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7500 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7501 ModuleFile *M = I->second;
7502 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007503 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7504
7505 if (DeserializationListener)
7506 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7507 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007508 }
7509
7510 return MacrosLoaded[ID];
7511}
7512
7513MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7514 if (LocalID < NUM_PREDEF_MACRO_IDS)
7515 return LocalID;
7516
7517 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7518 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7519 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7520
7521 return LocalID + I->second;
7522}
7523
7524serialization::SubmoduleID
7525ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7526 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7527 return LocalID;
7528
7529 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7530 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7531 assert(I != M.SubmoduleRemap.end()
7532 && "Invalid index into submodule index remap");
7533
7534 return LocalID + I->second;
7535}
7536
7537Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7538 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7539 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007540 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007541 }
7542
7543 if (GlobalID > SubmodulesLoaded.size()) {
7544 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007545 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007546 }
7547
7548 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7549}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007550
7551Module *ASTReader::getModule(unsigned ID) {
7552 return getSubmodule(ID);
7553}
7554
Guy Benyei11169dd2012-12-18 14:30:41 +00007555Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7556 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7557}
7558
7559Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7560 if (ID == 0)
7561 return Selector();
7562
7563 if (ID > SelectorsLoaded.size()) {
7564 Error("selector ID out of range in AST file");
7565 return Selector();
7566 }
7567
Craig Toppera13603a2014-05-22 05:54:18 +00007568 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007569 // Load this selector from the selector table.
7570 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7571 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7572 ModuleFile &M = *I->second;
7573 ASTSelectorLookupTrait Trait(*this, M);
7574 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7575 SelectorsLoaded[ID - 1] =
7576 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7577 if (DeserializationListener)
7578 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7579 }
7580
7581 return SelectorsLoaded[ID - 1];
7582}
7583
7584Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7585 return DecodeSelector(ID);
7586}
7587
7588uint32_t ASTReader::GetNumExternalSelectors() {
7589 // ID 0 (the null selector) is considered an external selector.
7590 return getTotalNumSelectors() + 1;
7591}
7592
7593serialization::SelectorID
7594ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7595 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7596 return LocalID;
7597
7598 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7599 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7600 assert(I != M.SelectorRemap.end()
7601 && "Invalid index into selector index remap");
7602
7603 return LocalID + I->second;
7604}
7605
7606DeclarationName
7607ASTReader::ReadDeclarationName(ModuleFile &F,
7608 const RecordData &Record, unsigned &Idx) {
7609 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7610 switch (Kind) {
7611 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007612 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007613
7614 case DeclarationName::ObjCZeroArgSelector:
7615 case DeclarationName::ObjCOneArgSelector:
7616 case DeclarationName::ObjCMultiArgSelector:
7617 return DeclarationName(ReadSelector(F, Record, Idx));
7618
7619 case DeclarationName::CXXConstructorName:
7620 return Context.DeclarationNames.getCXXConstructorName(
7621 Context.getCanonicalType(readType(F, Record, Idx)));
7622
7623 case DeclarationName::CXXDestructorName:
7624 return Context.DeclarationNames.getCXXDestructorName(
7625 Context.getCanonicalType(readType(F, Record, Idx)));
7626
7627 case DeclarationName::CXXConversionFunctionName:
7628 return Context.DeclarationNames.getCXXConversionFunctionName(
7629 Context.getCanonicalType(readType(F, Record, Idx)));
7630
7631 case DeclarationName::CXXOperatorName:
7632 return Context.DeclarationNames.getCXXOperatorName(
7633 (OverloadedOperatorKind)Record[Idx++]);
7634
7635 case DeclarationName::CXXLiteralOperatorName:
7636 return Context.DeclarationNames.getCXXLiteralOperatorName(
7637 GetIdentifierInfo(F, Record, Idx));
7638
7639 case DeclarationName::CXXUsingDirective:
7640 return DeclarationName::getUsingDirectiveName();
7641 }
7642
7643 llvm_unreachable("Invalid NameKind!");
7644}
7645
7646void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7647 DeclarationNameLoc &DNLoc,
7648 DeclarationName Name,
7649 const RecordData &Record, unsigned &Idx) {
7650 switch (Name.getNameKind()) {
7651 case DeclarationName::CXXConstructorName:
7652 case DeclarationName::CXXDestructorName:
7653 case DeclarationName::CXXConversionFunctionName:
7654 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7655 break;
7656
7657 case DeclarationName::CXXOperatorName:
7658 DNLoc.CXXOperatorName.BeginOpNameLoc
7659 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7660 DNLoc.CXXOperatorName.EndOpNameLoc
7661 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7662 break;
7663
7664 case DeclarationName::CXXLiteralOperatorName:
7665 DNLoc.CXXLiteralOperatorName.OpNameLoc
7666 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7667 break;
7668
7669 case DeclarationName::Identifier:
7670 case DeclarationName::ObjCZeroArgSelector:
7671 case DeclarationName::ObjCOneArgSelector:
7672 case DeclarationName::ObjCMultiArgSelector:
7673 case DeclarationName::CXXUsingDirective:
7674 break;
7675 }
7676}
7677
7678void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7679 DeclarationNameInfo &NameInfo,
7680 const RecordData &Record, unsigned &Idx) {
7681 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7682 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7683 DeclarationNameLoc DNLoc;
7684 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7685 NameInfo.setInfo(DNLoc);
7686}
7687
7688void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7689 const RecordData &Record, unsigned &Idx) {
7690 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7691 unsigned NumTPLists = Record[Idx++];
7692 Info.NumTemplParamLists = NumTPLists;
7693 if (NumTPLists) {
7694 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7695 for (unsigned i=0; i != NumTPLists; ++i)
7696 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7697 }
7698}
7699
7700TemplateName
7701ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7702 unsigned &Idx) {
7703 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7704 switch (Kind) {
7705 case TemplateName::Template:
7706 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7707
7708 case TemplateName::OverloadedTemplate: {
7709 unsigned size = Record[Idx++];
7710 UnresolvedSet<8> Decls;
7711 while (size--)
7712 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7713
7714 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7715 }
7716
7717 case TemplateName::QualifiedTemplate: {
7718 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7719 bool hasTemplKeyword = Record[Idx++];
7720 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7721 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7722 }
7723
7724 case TemplateName::DependentTemplate: {
7725 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7726 if (Record[Idx++]) // isIdentifier
7727 return Context.getDependentTemplateName(NNS,
7728 GetIdentifierInfo(F, Record,
7729 Idx));
7730 return Context.getDependentTemplateName(NNS,
7731 (OverloadedOperatorKind)Record[Idx++]);
7732 }
7733
7734 case TemplateName::SubstTemplateTemplateParm: {
7735 TemplateTemplateParmDecl *param
7736 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7737 if (!param) return TemplateName();
7738 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7739 return Context.getSubstTemplateTemplateParm(param, replacement);
7740 }
7741
7742 case TemplateName::SubstTemplateTemplateParmPack: {
7743 TemplateTemplateParmDecl *Param
7744 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7745 if (!Param)
7746 return TemplateName();
7747
7748 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7749 if (ArgPack.getKind() != TemplateArgument::Pack)
7750 return TemplateName();
7751
7752 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7753 }
7754 }
7755
7756 llvm_unreachable("Unhandled template name kind!");
7757}
7758
7759TemplateArgument
7760ASTReader::ReadTemplateArgument(ModuleFile &F,
7761 const RecordData &Record, unsigned &Idx) {
7762 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7763 switch (Kind) {
7764 case TemplateArgument::Null:
7765 return TemplateArgument();
7766 case TemplateArgument::Type:
7767 return TemplateArgument(readType(F, Record, Idx));
7768 case TemplateArgument::Declaration: {
7769 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007770 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007771 }
7772 case TemplateArgument::NullPtr:
7773 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7774 case TemplateArgument::Integral: {
7775 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7776 QualType T = readType(F, Record, Idx);
7777 return TemplateArgument(Context, Value, T);
7778 }
7779 case TemplateArgument::Template:
7780 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7781 case TemplateArgument::TemplateExpansion: {
7782 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007783 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007784 if (unsigned NumExpansions = Record[Idx++])
7785 NumTemplateExpansions = NumExpansions - 1;
7786 return TemplateArgument(Name, NumTemplateExpansions);
7787 }
7788 case TemplateArgument::Expression:
7789 return TemplateArgument(ReadExpr(F));
7790 case TemplateArgument::Pack: {
7791 unsigned NumArgs = Record[Idx++];
7792 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7793 for (unsigned I = 0; I != NumArgs; ++I)
7794 Args[I] = ReadTemplateArgument(F, Record, Idx);
7795 return TemplateArgument(Args, NumArgs);
7796 }
7797 }
7798
7799 llvm_unreachable("Unhandled template argument kind!");
7800}
7801
7802TemplateParameterList *
7803ASTReader::ReadTemplateParameterList(ModuleFile &F,
7804 const RecordData &Record, unsigned &Idx) {
7805 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7806 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7807 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7808
7809 unsigned NumParams = Record[Idx++];
7810 SmallVector<NamedDecl *, 16> Params;
7811 Params.reserve(NumParams);
7812 while (NumParams--)
7813 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7814
7815 TemplateParameterList* TemplateParams =
7816 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7817 Params.data(), Params.size(), RAngleLoc);
7818 return TemplateParams;
7819}
7820
7821void
7822ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007823ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007824 ModuleFile &F, const RecordData &Record,
7825 unsigned &Idx) {
7826 unsigned NumTemplateArgs = Record[Idx++];
7827 TemplArgs.reserve(NumTemplateArgs);
7828 while (NumTemplateArgs--)
7829 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7830}
7831
7832/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007833void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007834 const RecordData &Record, unsigned &Idx) {
7835 unsigned NumDecls = Record[Idx++];
7836 Set.reserve(Context, NumDecls);
7837 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007838 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007839 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007840 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007841 }
7842}
7843
7844CXXBaseSpecifier
7845ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7846 const RecordData &Record, unsigned &Idx) {
7847 bool isVirtual = static_cast<bool>(Record[Idx++]);
7848 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7849 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7850 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7851 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7852 SourceRange Range = ReadSourceRange(F, Record, Idx);
7853 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7854 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7855 EllipsisLoc);
7856 Result.setInheritConstructors(inheritConstructors);
7857 return Result;
7858}
7859
Richard Smithc2bb8182015-03-24 06:36:48 +00007860CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007861ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7862 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007863 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007864 assert(NumInitializers && "wrote ctor initializers but have no inits");
7865 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7866 for (unsigned i = 0; i != NumInitializers; ++i) {
7867 TypeSourceInfo *TInfo = nullptr;
7868 bool IsBaseVirtual = false;
7869 FieldDecl *Member = nullptr;
7870 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007871
Richard Smithc2bb8182015-03-24 06:36:48 +00007872 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7873 switch (Type) {
7874 case CTOR_INITIALIZER_BASE:
7875 TInfo = GetTypeSourceInfo(F, Record, Idx);
7876 IsBaseVirtual = Record[Idx++];
7877 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007878
Richard Smithc2bb8182015-03-24 06:36:48 +00007879 case CTOR_INITIALIZER_DELEGATING:
7880 TInfo = GetTypeSourceInfo(F, Record, Idx);
7881 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007882
Richard Smithc2bb8182015-03-24 06:36:48 +00007883 case CTOR_INITIALIZER_MEMBER:
7884 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7885 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007886
Richard Smithc2bb8182015-03-24 06:36:48 +00007887 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7888 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7889 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007890 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007891
7892 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7893 Expr *Init = ReadExpr(F);
7894 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7895 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7896 bool IsWritten = Record[Idx++];
7897 unsigned SourceOrderOrNumArrayIndices;
7898 SmallVector<VarDecl *, 8> Indices;
7899 if (IsWritten) {
7900 SourceOrderOrNumArrayIndices = Record[Idx++];
7901 } else {
7902 SourceOrderOrNumArrayIndices = Record[Idx++];
7903 Indices.reserve(SourceOrderOrNumArrayIndices);
7904 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7905 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7906 }
7907
7908 CXXCtorInitializer *BOMInit;
7909 if (Type == CTOR_INITIALIZER_BASE) {
7910 BOMInit = new (Context)
7911 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7912 RParenLoc, MemberOrEllipsisLoc);
7913 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7914 BOMInit = new (Context)
7915 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7916 } else if (IsWritten) {
7917 if (Member)
7918 BOMInit = new (Context) CXXCtorInitializer(
7919 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7920 else
7921 BOMInit = new (Context)
7922 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7923 LParenLoc, Init, RParenLoc);
7924 } else {
7925 if (IndirectMember) {
7926 assert(Indices.empty() && "Indirect field improperly initialized");
7927 BOMInit = new (Context)
7928 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7929 LParenLoc, Init, RParenLoc);
7930 } else {
7931 BOMInit = CXXCtorInitializer::Create(
7932 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7933 Indices.data(), Indices.size());
7934 }
7935 }
7936
7937 if (IsWritten)
7938 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7939 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007940 }
7941
Richard Smithc2bb8182015-03-24 06:36:48 +00007942 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007943}
7944
7945NestedNameSpecifier *
7946ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7947 const RecordData &Record, unsigned &Idx) {
7948 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007949 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007950 for (unsigned I = 0; I != N; ++I) {
7951 NestedNameSpecifier::SpecifierKind Kind
7952 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7953 switch (Kind) {
7954 case NestedNameSpecifier::Identifier: {
7955 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7956 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7957 break;
7958 }
7959
7960 case NestedNameSpecifier::Namespace: {
7961 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7962 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7963 break;
7964 }
7965
7966 case NestedNameSpecifier::NamespaceAlias: {
7967 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7968 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7969 break;
7970 }
7971
7972 case NestedNameSpecifier::TypeSpec:
7973 case NestedNameSpecifier::TypeSpecWithTemplate: {
7974 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7975 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007976 return nullptr;
7977
Guy Benyei11169dd2012-12-18 14:30:41 +00007978 bool Template = Record[Idx++];
7979 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7980 break;
7981 }
7982
7983 case NestedNameSpecifier::Global: {
7984 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7985 // No associated value, and there can't be a prefix.
7986 break;
7987 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007988
7989 case NestedNameSpecifier::Super: {
7990 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7991 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7992 break;
7993 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007994 }
7995 Prev = NNS;
7996 }
7997 return NNS;
7998}
7999
8000NestedNameSpecifierLoc
8001ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8002 unsigned &Idx) {
8003 unsigned N = Record[Idx++];
8004 NestedNameSpecifierLocBuilder Builder;
8005 for (unsigned I = 0; I != N; ++I) {
8006 NestedNameSpecifier::SpecifierKind Kind
8007 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8008 switch (Kind) {
8009 case NestedNameSpecifier::Identifier: {
8010 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8011 SourceRange Range = ReadSourceRange(F, Record, Idx);
8012 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8013 break;
8014 }
8015
8016 case NestedNameSpecifier::Namespace: {
8017 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8018 SourceRange Range = ReadSourceRange(F, Record, Idx);
8019 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8020 break;
8021 }
8022
8023 case NestedNameSpecifier::NamespaceAlias: {
8024 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8025 SourceRange Range = ReadSourceRange(F, Record, Idx);
8026 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8027 break;
8028 }
8029
8030 case NestedNameSpecifier::TypeSpec:
8031 case NestedNameSpecifier::TypeSpecWithTemplate: {
8032 bool Template = Record[Idx++];
8033 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8034 if (!T)
8035 return NestedNameSpecifierLoc();
8036 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8037
8038 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8039 Builder.Extend(Context,
8040 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8041 T->getTypeLoc(), ColonColonLoc);
8042 break;
8043 }
8044
8045 case NestedNameSpecifier::Global: {
8046 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8047 Builder.MakeGlobal(Context, ColonColonLoc);
8048 break;
8049 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008050
8051 case NestedNameSpecifier::Super: {
8052 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8053 SourceRange Range = ReadSourceRange(F, Record, Idx);
8054 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8055 break;
8056 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008057 }
8058 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008059
Guy Benyei11169dd2012-12-18 14:30:41 +00008060 return Builder.getWithLocInContext(Context);
8061}
8062
8063SourceRange
8064ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8065 unsigned &Idx) {
8066 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8067 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8068 return SourceRange(beg, end);
8069}
8070
8071/// \brief Read an integral value
8072llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8073 unsigned BitWidth = Record[Idx++];
8074 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8075 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8076 Idx += NumWords;
8077 return Result;
8078}
8079
8080/// \brief Read a signed integral value
8081llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8082 bool isUnsigned = Record[Idx++];
8083 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8084}
8085
8086/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008087llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8088 const llvm::fltSemantics &Sem,
8089 unsigned &Idx) {
8090 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008091}
8092
8093// \brief Read a string
8094std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8095 unsigned Len = Record[Idx++];
8096 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8097 Idx += Len;
8098 return Result;
8099}
8100
Richard Smith7ed1bc92014-12-05 22:42:13 +00008101std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8102 unsigned &Idx) {
8103 std::string Filename = ReadString(Record, Idx);
8104 ResolveImportedPath(F, Filename);
8105 return Filename;
8106}
8107
Guy Benyei11169dd2012-12-18 14:30:41 +00008108VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8109 unsigned &Idx) {
8110 unsigned Major = Record[Idx++];
8111 unsigned Minor = Record[Idx++];
8112 unsigned Subminor = Record[Idx++];
8113 if (Minor == 0)
8114 return VersionTuple(Major);
8115 if (Subminor == 0)
8116 return VersionTuple(Major, Minor - 1);
8117 return VersionTuple(Major, Minor - 1, Subminor - 1);
8118}
8119
8120CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8121 const RecordData &Record,
8122 unsigned &Idx) {
8123 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8124 return CXXTemporary::Create(Context, Decl);
8125}
8126
8127DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008128 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008129}
8130
8131DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8132 return Diags.Report(Loc, DiagID);
8133}
8134
8135/// \brief Retrieve the identifier table associated with the
8136/// preprocessor.
8137IdentifierTable &ASTReader::getIdentifierTable() {
8138 return PP.getIdentifierTable();
8139}
8140
8141/// \brief Record that the given ID maps to the given switch-case
8142/// statement.
8143void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008144 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008145 "Already have a SwitchCase with this ID");
8146 (*CurrSwitchCaseStmts)[ID] = SC;
8147}
8148
8149/// \brief Retrieve the switch-case statement with the given ID.
8150SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008151 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008152 return (*CurrSwitchCaseStmts)[ID];
8153}
8154
8155void ASTReader::ClearSwitchCaseIDs() {
8156 CurrSwitchCaseStmts->clear();
8157}
8158
8159void ASTReader::ReadComments() {
8160 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008161 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008162 serialization::ModuleFile *> >::iterator
8163 I = CommentsCursors.begin(),
8164 E = CommentsCursors.end();
8165 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008166 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008167 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008168 serialization::ModuleFile &F = *I->second;
8169 SavedStreamPosition SavedPosition(Cursor);
8170
8171 RecordData Record;
8172 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008173 llvm::BitstreamEntry Entry =
8174 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008175
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008176 switch (Entry.Kind) {
8177 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8178 case llvm::BitstreamEntry::Error:
8179 Error("malformed block record in AST file");
8180 return;
8181 case llvm::BitstreamEntry::EndBlock:
8182 goto NextCursor;
8183 case llvm::BitstreamEntry::Record:
8184 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008185 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008186 }
8187
8188 // Read a record.
8189 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008190 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008191 case COMMENTS_RAW_COMMENT: {
8192 unsigned Idx = 0;
8193 SourceRange SR = ReadSourceRange(F, Record, Idx);
8194 RawComment::CommentKind Kind =
8195 (RawComment::CommentKind) Record[Idx++];
8196 bool IsTrailingComment = Record[Idx++];
8197 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008198 Comments.push_back(new (Context) RawComment(
8199 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8200 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008201 break;
8202 }
8203 }
8204 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008205 NextCursor:
8206 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008207 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008208}
8209
Argyrios Kyrtzidis1bde1172014-11-18 05:24:18 +00008210void ASTReader::getInputFiles(ModuleFile &F,
8211 SmallVectorImpl<serialization::InputFile> &Files) {
8212 for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
8213 unsigned ID = I+1;
8214 Files.push_back(getInputFile(F, ID));
8215 }
8216}
8217
Richard Smithcd45dbc2014-04-19 03:48:30 +00008218std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8219 // If we know the owning module, use it.
8220 if (Module *M = D->getOwningModule())
8221 return M->getFullModuleName();
8222
8223 // Otherwise, use the name of the top-level module the decl is within.
8224 if (ModuleFile *M = getOwningModuleFile(D))
8225 return M->ModuleName;
8226
8227 // Not from a module.
8228 return "";
8229}
8230
Guy Benyei11169dd2012-12-18 14:30:41 +00008231void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008232 while (!PendingIdentifierInfos.empty() ||
8233 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008234 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008235 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008236 // If any identifiers with corresponding top-level declarations have
8237 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008238 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8239 TopLevelDeclsMap;
8240 TopLevelDeclsMap TopLevelDecls;
8241
Guy Benyei11169dd2012-12-18 14:30:41 +00008242 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008243 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008244 SmallVector<uint32_t, 4> DeclIDs =
8245 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008246 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008247
8248 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008249 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008250
Richard Smith851072e2014-05-19 20:59:20 +00008251 // For each decl chain that we wanted to complete while deserializing, mark
8252 // it as "still needs to be completed".
8253 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8254 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8255 }
8256 PendingIncompleteDeclChains.clear();
8257
Guy Benyei11169dd2012-12-18 14:30:41 +00008258 // Load pending declaration chains.
Richard Smithfe620d22015-03-05 23:24:12 +00008259 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
Richard Smithfe620d22015-03-05 23:24:12 +00008260 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
Richard Smithe687bf82015-03-16 20:54:07 +00008261 loadPendingDeclChain(PendingDeclChains[I]);
Richard Smithfe620d22015-03-05 23:24:12 +00008262 }
8263 assert(PendingDeclChainsKnown.empty());
Guy Benyei11169dd2012-12-18 14:30:41 +00008264 PendingDeclChains.clear();
8265
Douglas Gregor6168bd22013-02-18 15:53:43 +00008266 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008267 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8268 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008269 IdentifierInfo *II = TLD->first;
8270 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008271 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008272 }
8273 }
8274
Guy Benyei11169dd2012-12-18 14:30:41 +00008275 // Load any pending macro definitions.
8276 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008277 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8278 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8279 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8280 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008281 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008282 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008283 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008284 if (Info.M->Kind != MK_ImplicitModule &&
8285 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008286 resolvePendingMacro(II, Info);
8287 }
8288 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008289 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008290 ++IDIdx) {
8291 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008292 if (Info.M->Kind == MK_ImplicitModule ||
8293 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008294 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008295 }
8296 }
8297 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008298
8299 // Wire up the DeclContexts for Decls that we delayed setting until
8300 // recursive loading is completed.
8301 while (!PendingDeclContextInfos.empty()) {
8302 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8303 PendingDeclContextInfos.pop_front();
8304 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8305 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8306 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8307 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008308
Richard Smithd1c46742014-04-30 02:24:17 +00008309 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008310 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008311 auto Update = PendingUpdateRecords.pop_back_val();
8312 ReadingKindTracker ReadingKind(Read_Decl, *this);
8313 loadDeclUpdateRecords(Update.first, Update.second);
8314 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008315 }
Richard Smith8a639892015-01-24 01:07:20 +00008316
8317 // At this point, all update records for loaded decls are in place, so any
8318 // fake class definitions should have become real.
8319 assert(PendingFakeDefinitionData.empty() &&
8320 "faked up a class definition but never saw the real one");
8321
Guy Benyei11169dd2012-12-18 14:30:41 +00008322 // If we deserialized any C++ or Objective-C class definitions, any
8323 // Objective-C protocol definitions, or any redeclarable templates, make sure
8324 // that all redeclarations point to the definitions. Note that this can only
8325 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008326 for (Decl *D : PendingDefinitions) {
8327 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008328 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008329 // Make sure that the TagType points at the definition.
8330 const_cast<TagType*>(TagT)->decl = TD;
8331 }
Richard Smith8ce51082015-03-11 01:44:51 +00008332
Craig Topperc6914d02014-08-25 04:15:02 +00008333 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008334 for (auto *R = getMostRecentExistingDecl(RD); R;
8335 R = R->getPreviousDecl()) {
8336 assert((R == D) ==
8337 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008338 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008339 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008340 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008341 }
8342
8343 continue;
8344 }
Richard Smith8ce51082015-03-11 01:44:51 +00008345
Craig Topperc6914d02014-08-25 04:15:02 +00008346 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008347 // Make sure that the ObjCInterfaceType points at the definition.
8348 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8349 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008350
8351 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8352 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8353
Guy Benyei11169dd2012-12-18 14:30:41 +00008354 continue;
8355 }
Richard Smith8ce51082015-03-11 01:44:51 +00008356
Craig Topperc6914d02014-08-25 04:15:02 +00008357 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008358 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8359 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8360
Guy Benyei11169dd2012-12-18 14:30:41 +00008361 continue;
8362 }
Richard Smith8ce51082015-03-11 01:44:51 +00008363
Craig Topperc6914d02014-08-25 04:15:02 +00008364 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008365 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8366 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008367 }
8368 PendingDefinitions.clear();
8369
8370 // Load the bodies of any functions or methods we've encountered. We do
8371 // this now (delayed) so that we can be sure that the declaration chains
8372 // have been fully wired up.
Richard Smith8ce51082015-03-11 01:44:51 +00008373 // FIXME: There seems to be no point in delaying this, it does not depend
8374 // on the redecl chains having been wired up.
Guy Benyei11169dd2012-12-18 14:30:41 +00008375 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8376 PBEnd = PendingBodies.end();
8377 PB != PBEnd; ++PB) {
8378 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8379 // FIXME: Check for =delete/=default?
8380 // FIXME: Complain about ODR violations here?
8381 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8382 FD->setLazyBody(PB->second);
8383 continue;
8384 }
8385
8386 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8387 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8388 MD->setLazyBody(PB->second);
8389 }
8390 PendingBodies.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008391}
8392
8393void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008394 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8395 return;
8396
Richard Smitha0ce9c42014-07-29 23:23:27 +00008397 // Trigger the import of the full definition of each class that had any
8398 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008399 // These updates may in turn find and diagnose some ODR failures, so take
8400 // ownership of the set first.
8401 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8402 PendingOdrMergeFailures.clear();
8403 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008404 Merge.first->buildLookup();
8405 Merge.first->decls_begin();
8406 Merge.first->bases_begin();
8407 Merge.first->vbases_begin();
8408 for (auto *RD : Merge.second) {
8409 RD->decls_begin();
8410 RD->bases_begin();
8411 RD->vbases_begin();
8412 }
8413 }
8414
8415 // For each declaration from a merged context, check that the canonical
8416 // definition of that context also contains a declaration of the same
8417 // entity.
8418 //
8419 // Caution: this loop does things that might invalidate iterators into
8420 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8421 while (!PendingOdrMergeChecks.empty()) {
8422 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8423
8424 // FIXME: Skip over implicit declarations for now. This matters for things
8425 // like implicitly-declared special member functions. This isn't entirely
8426 // correct; we can end up with multiple unmerged declarations of the same
8427 // implicit entity.
8428 if (D->isImplicit())
8429 continue;
8430
8431 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008432
8433 bool Found = false;
8434 const Decl *DCanon = D->getCanonicalDecl();
8435
Richard Smith01bdb7a2014-08-28 05:44:07 +00008436 for (auto RI : D->redecls()) {
8437 if (RI->getLexicalDeclContext() == CanonDef) {
8438 Found = true;
8439 break;
8440 }
8441 }
8442 if (Found)
8443 continue;
8444
Richard Smitha0ce9c42014-07-29 23:23:27 +00008445 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith01bdb7a2014-08-28 05:44:07 +00008446 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
Richard Smitha0ce9c42014-07-29 23:23:27 +00008447 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8448 !Found && I != E; ++I) {
8449 for (auto RI : (*I)->redecls()) {
8450 if (RI->getLexicalDeclContext() == CanonDef) {
8451 // This declaration is present in the canonical definition. If it's
8452 // in the same redecl chain, it's the one we're looking for.
8453 if (RI->getCanonicalDecl() == DCanon)
8454 Found = true;
8455 else
8456 Candidates.push_back(cast<NamedDecl>(RI));
8457 break;
8458 }
8459 }
8460 }
8461
8462 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008463 // The AST doesn't like TagDecls becoming invalid after they've been
8464 // completed. We only really need to mark FieldDecls as invalid here.
8465 if (!isa<TagDecl>(D))
8466 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008467
8468 // Ensure we don't accidentally recursively enter deserialization while
8469 // we're producing our diagnostic.
8470 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008471
8472 std::string CanonDefModule =
8473 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8474 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8475 << D << getOwningModuleNameForDiagnostic(D)
8476 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8477
8478 if (Candidates.empty())
8479 Diag(cast<Decl>(CanonDef)->getLocation(),
8480 diag::note_module_odr_violation_no_possible_decls) << D;
8481 else {
8482 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8483 Diag(Candidates[I]->getLocation(),
8484 diag::note_module_odr_violation_possible_decl)
8485 << Candidates[I];
8486 }
8487
8488 DiagnosedOdrMergeFailures.insert(CanonDef);
8489 }
8490 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008491
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008492 if (OdrMergeFailures.empty())
8493 return;
8494
8495 // Ensure we don't accidentally recursively enter deserialization while
8496 // we're producing our diagnostics.
8497 Deserializing RecursionGuard(this);
8498
Richard Smithcd45dbc2014-04-19 03:48:30 +00008499 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008500 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008501 // If we've already pointed out a specific problem with this class, don't
8502 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008503 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008504 continue;
8505
8506 bool Diagnosed = false;
8507 for (auto *RD : Merge.second) {
8508 // Multiple different declarations got merged together; tell the user
8509 // where they came from.
8510 if (Merge.first != RD) {
8511 // FIXME: Walk the definition, figure out what's different,
8512 // and diagnose that.
8513 if (!Diagnosed) {
8514 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8515 Diag(Merge.first->getLocation(),
8516 diag::err_module_odr_violation_different_definitions)
8517 << Merge.first << Module.empty() << Module;
8518 Diagnosed = true;
8519 }
8520
8521 Diag(RD->getLocation(),
8522 diag::note_module_odr_violation_different_definitions)
8523 << getOwningModuleNameForDiagnostic(RD);
8524 }
8525 }
8526
8527 if (!Diagnosed) {
8528 // All definitions are updates to the same declaration. This happens if a
8529 // module instantiates the declaration of a class template specialization
8530 // and two or more other modules instantiate its definition.
8531 //
8532 // FIXME: Indicate which modules had instantiations of this definition.
8533 // FIXME: How can this even happen?
8534 Diag(Merge.first->getLocation(),
8535 diag::err_module_odr_violation_different_instantiations)
8536 << Merge.first;
8537 }
8538 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008539}
8540
8541void ASTReader::FinishedDeserializing() {
8542 assert(NumCurrentElementsDeserializing &&
8543 "FinishedDeserializing not paired with StartedDeserializing");
8544 if (NumCurrentElementsDeserializing == 1) {
8545 // We decrease NumCurrentElementsDeserializing only after pending actions
8546 // are finished, to avoid recursively re-calling finishPendingActions().
8547 finishPendingActions();
8548 }
8549 --NumCurrentElementsDeserializing;
8550
Richard Smitha0ce9c42014-07-29 23:23:27 +00008551 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008552 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008553 while (!PendingExceptionSpecUpdates.empty()) {
8554 auto Updates = std::move(PendingExceptionSpecUpdates);
8555 PendingExceptionSpecUpdates.clear();
8556 for (auto Update : Updates) {
8557 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8558 SemaObj->UpdateExceptionSpec(Update.second,
8559 FPT->getExtProtoInfo().ExceptionSpec);
8560 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008561 }
8562
Richard Smitha0ce9c42014-07-29 23:23:27 +00008563 diagnoseOdrViolations();
8564
Richard Smith04d05b52014-03-23 00:27:18 +00008565 // We are not in recursive loading, so it's safe to pass the "interesting"
8566 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008567 if (Consumer)
8568 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008569 }
8570}
8571
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008572void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008573 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8574 // Remove any fake results before adding any real ones.
8575 auto It = PendingFakeLookupResults.find(II);
8576 if (It != PendingFakeLookupResults.end()) {
8577 for (auto *ND : PendingFakeLookupResults[II])
8578 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008579 // FIXME: this works around module+PCH performance issue.
8580 // Rather than erase the result from the map, which is O(n), just clear
8581 // the vector of NamedDecls.
8582 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008583 }
8584 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008585
8586 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8587 SemaObj->TUScope->AddDecl(D);
8588 } else if (SemaObj->TUScope) {
8589 // Adding the decl to IdResolver may have failed because it was already in
8590 // (even though it was not added in scope). If it is already in, make sure
8591 // it gets in the scope as well.
8592 if (std::find(SemaObj->IdResolver.begin(Name),
8593 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8594 SemaObj->TUScope->AddDecl(D);
8595 }
8596}
8597
Nico Weber824285e2014-05-08 04:26:47 +00008598ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8599 bool DisableValidation, bool AllowASTWithCompilerErrors,
8600 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008601 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008602 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008603 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Craig Toppera13603a2014-05-22 05:54:18 +00008604 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
8605 SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
8606 ModuleMgr(PP.getFileManager()), isysroot(isysroot),
8607 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008608 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8609 AllowConfigurationMismatch(AllowConfigurationMismatch),
8610 ValidateSystemInputs(ValidateSystemInputs),
8611 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Richard Smith053f6c62014-05-16 23:01:30 +00008612 CurrSwitchCaseStmts(&SwitchCaseStmts),
Nico Weber824285e2014-05-08 04:26:47 +00008613 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8614 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8615 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8616 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8617 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8618 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8619 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8620 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8621 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008622 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008623 SourceMgr.setExternalSLocEntrySource(this);
8624}
8625
8626ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008627 if (OwnsDeserializationListener)
8628 delete DeserializationListener;
8629
Guy Benyei11169dd2012-12-18 14:30:41 +00008630 for (DeclContextVisibleUpdatesPending::iterator
8631 I = PendingVisibleUpdates.begin(),
8632 E = PendingVisibleUpdates.end();
8633 I != E; ++I) {
8634 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8635 F = I->second.end();
8636 J != F; ++J)
8637 delete J->first;
8638 }
8639}