blob: 921c06ce670cc427e269c3acd024aea1c951f985 [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
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001726void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1727 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001728 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001729
1730 BitstreamCursor &Cursor = M.MacroCursor;
1731 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001732 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001733
Richard Smith713369b2015-04-23 20:40:50 +00001734 struct ModuleMacroRecord {
1735 SubmoduleID SubModID;
1736 MacroInfo *MI;
1737 SmallVector<SubmoduleID, 8> Overrides;
1738 };
1739 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001740
Richard Smithd7329392015-04-21 21:46:32 +00001741 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1742 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1743 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001744 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001745 while (true) {
1746 llvm::BitstreamEntry Entry =
1747 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1748 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1749 Error("malformed block record in AST file");
1750 return;
1751 }
1752
1753 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001754 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001755 case PP_MACRO_DIRECTIVE_HISTORY:
1756 break;
1757
1758 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001759 ModuleMacros.push_back(ModuleMacroRecord());
1760 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001761 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1762 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001763 for (int I = 2, N = Record.size(); I != N; ++I)
1764 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001765 continue;
1766 }
1767
1768 default:
1769 Error("malformed block record in AST file");
1770 return;
1771 }
1772
1773 // We found the macro directive history; that's the last record
1774 // for this macro.
1775 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001776 }
1777
Richard Smithd7329392015-04-21 21:46:32 +00001778 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001779 {
1780 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001781 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001782 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001783 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001784 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001785 Module *Mod = getSubmodule(ModID);
1786 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001787 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001788 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001789 }
1790
1791 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001792 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001793 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001794 }
1795 }
1796
1797 // Don't read the directive history for a module; we don't have anywhere
1798 // to put it.
1799 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1800 return;
1801
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001802 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001803 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001804 unsigned Idx = 0, N = Record.size();
1805 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001806 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001807 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001808 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1809 switch (K) {
1810 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001811 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smithdaa69e02014-07-25 04:40:03 +00001812 bool IsAmbiguous = Record[Idx++];
Richard Smith713369b2015-04-23 20:40:50 +00001813 ModuleMacro *MM = nullptr;
1814 if (SubmoduleID ImportedFrom = getGlobalSubmoduleID(M, Record[Idx++]))
1815 MM = PP.getModuleMacro(getSubmodule(ImportedFrom), II);
Richard Smith50474bf2015-04-23 23:29:05 +00001816 MD = MM ? PP.AllocateImportedMacroDirective(MM, Loc)
1817 : PP.AllocateDefMacroDirective(MI, Loc);
1818 cast<DefMacroDirective>(MD)->setAmbiguous(IsAmbiguous);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001819 break;
1820 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001821 case MacroDirective::MD_Undefine: {
Richard Smith713369b2015-04-23 20:40:50 +00001822 ModuleMacro *MM = nullptr;
1823 if (SubmoduleID ImportedFrom = getGlobalSubmoduleID(M, Record[Idx++]))
1824 MM = PP.getModuleMacro(getSubmodule(ImportedFrom), II);
Richard Smith50474bf2015-04-23 23:29:05 +00001825 MD = MM ? PP.AllocateImportedMacroDirective(MM, Loc)
1826 : PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001827 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001828 }
1829 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001830 bool isPublic = Record[Idx++];
1831 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1832 break;
1833 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001834
1835 if (!Latest)
1836 Latest = MD;
1837 if (Earliest)
1838 Earliest->setPrevious(MD);
1839 Earliest = MD;
1840 }
1841
1842 PP.setLoadedMacroDirective(II, Latest);
1843}
1844
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001845ASTReader::InputFileInfo
1846ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001847 // Go find this input file.
1848 BitstreamCursor &Cursor = F.InputFilesCursor;
1849 SavedStreamPosition SavedPosition(Cursor);
1850 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1851
1852 unsigned Code = Cursor.ReadCode();
1853 RecordData Record;
1854 StringRef Blob;
1855
1856 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1857 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1858 "invalid record type for input file");
1859 (void)Result;
1860
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001861 std::string Filename;
1862 off_t StoredSize;
1863 time_t StoredTime;
1864 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001865
Ben Langmuir198c1682014-03-07 07:27:49 +00001866 assert(Record[0] == ID && "Bogus stored ID or offset");
1867 StoredSize = static_cast<off_t>(Record[1]);
1868 StoredTime = static_cast<time_t>(Record[2]);
1869 Overridden = static_cast<bool>(Record[3]);
1870 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001871 ResolveImportedPath(F, Filename);
1872
Hans Wennborg73945142014-03-14 17:45:06 +00001873 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1874 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001875}
1876
1877std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001878 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00001879}
1880
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001881InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001882 // If this ID is bogus, just return an empty input file.
1883 if (ID == 0 || ID > F.InputFilesLoaded.size())
1884 return InputFile();
1885
1886 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001887 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001888 return F.InputFilesLoaded[ID-1];
1889
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001890 if (F.InputFilesLoaded[ID-1].isNotFound())
1891 return InputFile();
1892
Guy Benyei11169dd2012-12-18 14:30:41 +00001893 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001894 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001895 SavedStreamPosition SavedPosition(Cursor);
1896 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1897
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001898 InputFileInfo FI = readInputFileInfo(F, ID);
1899 off_t StoredSize = FI.StoredSize;
1900 time_t StoredTime = FI.StoredTime;
1901 bool Overridden = FI.Overridden;
1902 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001903
Ben Langmuir198c1682014-03-07 07:27:49 +00001904 const FileEntry *File
1905 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1906 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1907
1908 // If we didn't find the file, resolve it relative to the
1909 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00001910 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00001911 F.OriginalDir != CurrentDir) {
1912 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1913 F.OriginalDir,
1914 CurrentDir);
1915 if (!Resolved.empty())
1916 File = FileMgr.getFile(Resolved);
1917 }
1918
1919 // For an overridden file, create a virtual file with the stored
1920 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00001921 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001922 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1923 }
1924
Craig Toppera13603a2014-05-22 05:54:18 +00001925 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001926 if (Complain) {
1927 std::string ErrorStr = "could not find file '";
1928 ErrorStr += Filename;
1929 ErrorStr += "' referenced by AST file";
1930 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001931 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001932 // Record that we didn't find the file.
1933 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1934 return InputFile();
1935 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001936
Ben Langmuir198c1682014-03-07 07:27:49 +00001937 // Check if there was a request to override the contents of the file
1938 // that was part of the precompiled header. Overridding such a file
1939 // can lead to problems when lexing using the source locations from the
1940 // PCH.
1941 SourceManager &SM = getSourceManager();
1942 if (!Overridden && SM.isFileOverridden(File)) {
1943 if (Complain)
1944 Error(diag::err_fe_pch_file_overridden, Filename);
1945 // After emitting the diagnostic, recover by disabling the override so
1946 // that the original file will be used.
1947 SM.disableFileContentsOverride(File);
1948 // The FileEntry is a virtual file entry with the size of the contents
1949 // that would override the original contents. Set it to the original's
1950 // size/time.
1951 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1952 StoredSize, StoredTime);
1953 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001954
Ben Langmuir198c1682014-03-07 07:27:49 +00001955 bool IsOutOfDate = false;
1956
1957 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00001958 if (!Overridden && //
1959 (StoredSize != File->getSize() ||
1960#if defined(LLVM_ON_WIN32)
1961 false
1962#else
Ben Langmuir198c1682014-03-07 07:27:49 +00001963 // In our regression testing, the Windows file system seems to
1964 // have inconsistent modification times that sometimes
1965 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00001966 //
1967 // This also happens in networked file systems, so disable this
1968 // check if validation is disabled or if we have an explicitly
1969 // built PCM file.
1970 //
1971 // FIXME: Should we also do this for PCH files? They could also
1972 // reasonably get shared across a network during a distributed build.
1973 (StoredTime != File->getModificationTime() && !DisableValidation &&
1974 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001975#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00001976 )) {
1977 if (Complain) {
1978 // Build a list of the PCH imports that got us here (in reverse).
1979 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1980 while (ImportStack.back()->ImportedBy.size() > 0)
1981 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00001982
Ben Langmuir198c1682014-03-07 07:27:49 +00001983 // The top-level PCH is stale.
1984 StringRef TopLevelPCHName(ImportStack.back()->FileName);
1985 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00001986
Ben Langmuir198c1682014-03-07 07:27:49 +00001987 // Print the import stack.
1988 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
1989 Diag(diag::note_pch_required_by)
1990 << Filename << ImportStack[0]->FileName;
1991 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00001992 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00001993 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00001994 }
1995
Ben Langmuir198c1682014-03-07 07:27:49 +00001996 if (!Diags.isDiagnosticInFlight())
1997 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00001998 }
1999
Ben Langmuir198c1682014-03-07 07:27:49 +00002000 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002001 }
2002
Ben Langmuir198c1682014-03-07 07:27:49 +00002003 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2004
2005 // Note that we've loaded this input file.
2006 F.InputFilesLoaded[ID-1] = IF;
2007 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002008}
2009
Richard Smith7ed1bc92014-12-05 22:42:13 +00002010/// \brief If we are loading a relocatable PCH or module file, and the filename
2011/// is not an absolute path, add the system or module root to the beginning of
2012/// the file name.
2013void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2014 // Resolve relative to the base directory, if we have one.
2015 if (!M.BaseDirectory.empty())
2016 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002017}
2018
Richard Smith7ed1bc92014-12-05 22:42:13 +00002019void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002020 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2021 return;
2022
Richard Smith7ed1bc92014-12-05 22:42:13 +00002023 SmallString<128> Buffer;
2024 llvm::sys::path::append(Buffer, Prefix, Filename);
2025 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002026}
2027
2028ASTReader::ASTReadResult
2029ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002030 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002031 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002032 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002033 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002034
2035 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2036 Error("malformed block record in AST file");
2037 return Failure;
2038 }
2039
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002040 // Should we allow the configuration of the module file to differ from the
2041 // configuration of the current translation unit in a compatible way?
2042 //
2043 // FIXME: Allow this for files explicitly specified with -include-pch too.
2044 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2045
Guy Benyei11169dd2012-12-18 14:30:41 +00002046 // Read all of the records and blocks in the control block.
2047 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002048 unsigned NumInputs = 0;
2049 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002050 while (1) {
2051 llvm::BitstreamEntry Entry = Stream.advance();
2052
2053 switch (Entry.Kind) {
2054 case llvm::BitstreamEntry::Error:
2055 Error("malformed block record in AST file");
2056 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002057 case llvm::BitstreamEntry::EndBlock: {
2058 // Validate input files.
2059 const HeaderSearchOptions &HSOpts =
2060 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002061
Richard Smitha1825302014-10-23 22:18:29 +00002062 // All user input files reside at the index range [0, NumUserInputs), and
2063 // system input files reside at [NumUserInputs, NumInputs).
Ben Langmuiracb803e2014-11-10 22:13:10 +00002064 if (!DisableValidation) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002065 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002066
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002067 // If we are reading a module, we will create a verification timestamp,
2068 // so we verify all input files. Otherwise, verify only user input
2069 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002070
2071 unsigned N = NumUserInputs;
2072 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002073 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002074 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002075 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002076 N = NumInputs;
2077
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002078 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002079 InputFile IF = getInputFile(F, I+1, Complain);
2080 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002081 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002082 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002083 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002084
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002085 if (Listener)
2086 Listener->visitModuleFile(F.FileName);
2087
Ben Langmuircb69b572014-03-07 06:40:32 +00002088 if (Listener && Listener->needsInputFileVisitation()) {
2089 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2090 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002091 for (unsigned I = 0; I < N; ++I) {
2092 bool IsSystem = I >= NumUserInputs;
2093 InputFileInfo FI = readInputFileInfo(F, I+1);
2094 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2095 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002096 }
2097
Guy Benyei11169dd2012-12-18 14:30:41 +00002098 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002099 }
2100
Chris Lattnere7b154b2013-01-19 21:39:22 +00002101 case llvm::BitstreamEntry::SubBlock:
2102 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002103 case INPUT_FILES_BLOCK_ID:
2104 F.InputFilesCursor = Stream;
2105 if (Stream.SkipBlock() || // Skip with the main cursor
2106 // Read the abbreviations
2107 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2108 Error("malformed block record in AST file");
2109 return Failure;
2110 }
2111 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002112
Guy Benyei11169dd2012-12-18 14:30:41 +00002113 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002114 if (Stream.SkipBlock()) {
2115 Error("malformed block record in AST file");
2116 return Failure;
2117 }
2118 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002119 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002120
2121 case llvm::BitstreamEntry::Record:
2122 // The interesting case.
2123 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002124 }
2125
2126 // Read and process a record.
2127 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002128 StringRef Blob;
2129 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002130 case METADATA: {
2131 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2132 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002133 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2134 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002135 return VersionMismatch;
2136 }
2137
2138 bool hasErrors = Record[5];
2139 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2140 Diag(diag::err_pch_with_compiler_errors);
2141 return HadErrors;
2142 }
2143
2144 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002145 // Relative paths in a relocatable PCH are relative to our sysroot.
2146 if (F.RelocatablePCH)
2147 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002148
2149 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002150 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002151 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2152 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002153 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002154 return VersionMismatch;
2155 }
2156 break;
2157 }
2158
Ben Langmuir487ea142014-10-23 18:05:36 +00002159 case SIGNATURE:
2160 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2161 F.Signature = Record[0];
2162 break;
2163
Guy Benyei11169dd2012-12-18 14:30:41 +00002164 case IMPORTS: {
2165 // Load each of the imported PCH files.
2166 unsigned Idx = 0, N = Record.size();
2167 while (Idx < N) {
2168 // Read information about the AST file.
2169 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2170 // The import location will be the local one for now; we will adjust
2171 // all import locations of module imports after the global source
2172 // location info are setup.
2173 SourceLocation ImportLoc =
2174 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002175 off_t StoredSize = (off_t)Record[Idx++];
2176 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002177 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002178 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002179
2180 // Load the AST file.
2181 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00002182 StoredSize, StoredModTime, StoredSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00002183 ClientLoadCapabilities)) {
2184 case Failure: return Failure;
2185 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002186 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002187 case OutOfDate: return OutOfDate;
2188 case VersionMismatch: return VersionMismatch;
2189 case ConfigurationMismatch: return ConfigurationMismatch;
2190 case HadErrors: return HadErrors;
2191 case Success: break;
2192 }
2193 }
2194 break;
2195 }
2196
Richard Smith7f330cd2015-03-18 01:42:29 +00002197 case KNOWN_MODULE_FILES:
2198 break;
2199
Guy Benyei11169dd2012-12-18 14:30:41 +00002200 case LANGUAGE_OPTIONS: {
2201 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002202 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002203 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002204 ParseLanguageOptions(Record, Complain, *Listener,
2205 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002206 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002207 return ConfigurationMismatch;
2208 break;
2209 }
2210
2211 case TARGET_OPTIONS: {
2212 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2213 if (Listener && &F == *ModuleMgr.begin() &&
Chandler Carruth0d745bc2015-03-14 04:47:43 +00002214 ParseTargetOptions(Record, Complain, *Listener,
2215 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002216 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002217 return ConfigurationMismatch;
2218 break;
2219 }
2220
2221 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002222 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002223 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002224 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002225 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002226 !DisableValidation)
2227 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002228 break;
2229 }
2230
2231 case FILE_SYSTEM_OPTIONS: {
2232 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2233 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002234 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002235 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002236 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002237 return ConfigurationMismatch;
2238 break;
2239 }
2240
2241 case HEADER_SEARCH_OPTIONS: {
2242 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2243 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002244 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002245 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002246 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002247 return ConfigurationMismatch;
2248 break;
2249 }
2250
2251 case PREPROCESSOR_OPTIONS: {
2252 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2253 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002254 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002255 ParsePreprocessorOptions(Record, Complain, *Listener,
2256 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002257 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002258 return ConfigurationMismatch;
2259 break;
2260 }
2261
2262 case ORIGINAL_FILE:
2263 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002264 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002265 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002266 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002267 break;
2268
2269 case ORIGINAL_FILE_ID:
2270 F.OriginalSourceFileID = FileID::get(Record[0]);
2271 break;
2272
2273 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002274 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002275 break;
2276
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002277 case MODULE_NAME:
2278 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002279 if (Listener)
2280 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002281 break;
2282
Richard Smith223d3f22014-12-06 03:21:08 +00002283 case MODULE_DIRECTORY: {
2284 assert(!F.ModuleName.empty() &&
2285 "MODULE_DIRECTORY found before MODULE_NAME");
2286 // If we've already loaded a module map file covering this module, we may
2287 // have a better path for it (relative to the current build).
2288 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2289 if (M && M->Directory) {
2290 // If we're implicitly loading a module, the base directory can't
2291 // change between the build and use.
2292 if (F.Kind != MK_ExplicitModule) {
2293 const DirectoryEntry *BuildDir =
2294 PP.getFileManager().getDirectory(Blob);
2295 if (!BuildDir || BuildDir != M->Directory) {
2296 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2297 Diag(diag::err_imported_module_relocated)
2298 << F.ModuleName << Blob << M->Directory->getName();
2299 return OutOfDate;
2300 }
2301 }
2302 F.BaseDirectory = M->Directory->getName();
2303 } else {
2304 F.BaseDirectory = Blob;
2305 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002306 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002307 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002308
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002309 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002310 if (ASTReadResult Result =
2311 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2312 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002313 break;
2314
Guy Benyei11169dd2012-12-18 14:30:41 +00002315 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002316 NumInputs = Record[0];
2317 NumUserInputs = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00002318 F.InputFileOffsets = (const uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002319 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002320 break;
2321 }
2322 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002323}
2324
Ben Langmuir2c9af442014-04-10 17:57:43 +00002325ASTReader::ASTReadResult
2326ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002327 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002328
2329 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2330 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002331 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002332 }
2333
2334 // Read all of the records and blocks for the AST file.
2335 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002336 while (1) {
2337 llvm::BitstreamEntry Entry = Stream.advance();
2338
2339 switch (Entry.Kind) {
2340 case llvm::BitstreamEntry::Error:
2341 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002342 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002343 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002344 // Outside of C++, we do not store a lookup map for the translation unit.
2345 // Instead, mark it as needing a lookup map to be built if this module
2346 // contains any declarations lexically within it (which it always does!).
2347 // This usually has no cost, since we very rarely need the lookup map for
2348 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002349 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002350 if (DC->hasExternalLexicalStorage() &&
2351 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002352 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002353
Ben Langmuir2c9af442014-04-10 17:57:43 +00002354 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002355 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002356 case llvm::BitstreamEntry::SubBlock:
2357 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002358 case DECLTYPES_BLOCK_ID:
2359 // We lazily load the decls block, but we want to set up the
2360 // DeclsCursor cursor to point into it. Clone our current bitcode
2361 // cursor to it, enter the block and read the abbrevs in that block.
2362 // With the main cursor, we just skip over it.
2363 F.DeclsCursor = Stream;
2364 if (Stream.SkipBlock() || // Skip with the main cursor.
2365 // Read the abbrevs.
2366 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2367 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002368 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002369 }
2370 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002371
Guy Benyei11169dd2012-12-18 14:30:41 +00002372 case PREPROCESSOR_BLOCK_ID:
2373 F.MacroCursor = Stream;
2374 if (!PP.getExternalSource())
2375 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002376
Guy Benyei11169dd2012-12-18 14:30:41 +00002377 if (Stream.SkipBlock() ||
2378 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2379 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002380 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002381 }
2382 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2383 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002384
Guy Benyei11169dd2012-12-18 14:30:41 +00002385 case PREPROCESSOR_DETAIL_BLOCK_ID:
2386 F.PreprocessorDetailCursor = Stream;
2387 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002388 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002389 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002390 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002391 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002392 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002393 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002394 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2395
Guy Benyei11169dd2012-12-18 14:30:41 +00002396 if (!PP.getPreprocessingRecord())
2397 PP.createPreprocessingRecord();
2398 if (!PP.getPreprocessingRecord()->getExternalSource())
2399 PP.getPreprocessingRecord()->SetExternalSource(*this);
2400 break;
2401
2402 case SOURCE_MANAGER_BLOCK_ID:
2403 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002404 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002405 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002406
Guy Benyei11169dd2012-12-18 14:30:41 +00002407 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002408 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2409 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002410 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002411
Guy Benyei11169dd2012-12-18 14:30:41 +00002412 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002413 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002414 if (Stream.SkipBlock() ||
2415 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2416 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002417 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002418 }
2419 CommentsCursors.push_back(std::make_pair(C, &F));
2420 break;
2421 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002422
Guy Benyei11169dd2012-12-18 14:30:41 +00002423 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002424 if (Stream.SkipBlock()) {
2425 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002426 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002427 }
2428 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002429 }
2430 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002431
2432 case llvm::BitstreamEntry::Record:
2433 // The interesting case.
2434 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002435 }
2436
2437 // Read and process a record.
2438 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002439 StringRef Blob;
2440 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002441 default: // Default behavior: ignore.
2442 break;
2443
2444 case TYPE_OFFSET: {
2445 if (F.LocalNumTypes != 0) {
2446 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002447 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002448 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002449 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002450 F.LocalNumTypes = Record[0];
2451 unsigned LocalBaseTypeIndex = Record[1];
2452 F.BaseTypeIndex = getTotalNumTypes();
2453
2454 if (F.LocalNumTypes > 0) {
2455 // Introduce the global -> local mapping for types within this module.
2456 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2457
2458 // Introduce the local -> global mapping for types within this module.
2459 F.TypeRemap.insertOrReplace(
2460 std::make_pair(LocalBaseTypeIndex,
2461 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002462
2463 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002464 }
2465 break;
2466 }
2467
2468 case DECL_OFFSET: {
2469 if (F.LocalNumDecls != 0) {
2470 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002471 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002472 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002473 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002474 F.LocalNumDecls = Record[0];
2475 unsigned LocalBaseDeclID = Record[1];
2476 F.BaseDeclID = getTotalNumDecls();
2477
2478 if (F.LocalNumDecls > 0) {
2479 // Introduce the global -> local mapping for declarations within this
2480 // module.
2481 GlobalDeclMap.insert(
2482 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2483
2484 // Introduce the local -> global mapping for declarations within this
2485 // module.
2486 F.DeclRemap.insertOrReplace(
2487 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2488
2489 // Introduce the global -> local mapping for declarations within this
2490 // module.
2491 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002492
Ben Langmuir52ca6782014-10-20 16:27:32 +00002493 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2494 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002495 break;
2496 }
2497
2498 case TU_UPDATE_LEXICAL: {
2499 DeclContext *TU = Context.getTranslationUnitDecl();
2500 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002501 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002502 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002503 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002504 TU->setHasExternalLexicalStorage(true);
2505 break;
2506 }
2507
2508 case UPDATE_VISIBLE: {
2509 unsigned Idx = 0;
2510 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2511 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002512 ASTDeclContextNameLookupTable::Create(
2513 (const unsigned char *)Blob.data() + Record[Idx++],
2514 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2515 (const unsigned char *)Blob.data(),
2516 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002517 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002518 auto *DC = cast<DeclContext>(D);
2519 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002520 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2521 delete LookupTable;
2522 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002523 } else
2524 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2525 break;
2526 }
2527
2528 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002529 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002530 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002531 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2532 (const unsigned char *)F.IdentifierTableData + Record[0],
2533 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2534 (const unsigned char *)F.IdentifierTableData,
2535 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002536
2537 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2538 }
2539 break;
2540
2541 case IDENTIFIER_OFFSET: {
2542 if (F.LocalNumIdentifiers != 0) {
2543 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002544 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002545 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002546 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002547 F.LocalNumIdentifiers = Record[0];
2548 unsigned LocalBaseIdentifierID = Record[1];
2549 F.BaseIdentifierID = getTotalNumIdentifiers();
2550
2551 if (F.LocalNumIdentifiers > 0) {
2552 // Introduce the global -> local mapping for identifiers within this
2553 // module.
2554 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2555 &F));
2556
2557 // Introduce the local -> global mapping for identifiers within this
2558 // module.
2559 F.IdentifierRemap.insertOrReplace(
2560 std::make_pair(LocalBaseIdentifierID,
2561 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002562
Ben Langmuir52ca6782014-10-20 16:27:32 +00002563 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2564 + F.LocalNumIdentifiers);
2565 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002566 break;
2567 }
2568
Ben Langmuir332aafe2014-01-31 01:06:56 +00002569 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002570 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2571 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002573 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002574 break;
2575
2576 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002577 if (SpecialTypes.empty()) {
2578 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2579 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2580 break;
2581 }
2582
2583 if (SpecialTypes.size() != Record.size()) {
2584 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002585 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002586 }
2587
2588 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2589 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2590 if (!SpecialTypes[I])
2591 SpecialTypes[I] = ID;
2592 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2593 // merge step?
2594 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 break;
2596
2597 case STATISTICS:
2598 TotalNumStatements += Record[0];
2599 TotalNumMacros += Record[1];
2600 TotalLexicalDeclContexts += Record[2];
2601 TotalVisibleDeclContexts += Record[3];
2602 break;
2603
2604 case UNUSED_FILESCOPED_DECLS:
2605 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2606 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2607 break;
2608
2609 case DELEGATING_CTORS:
2610 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2611 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2612 break;
2613
2614 case WEAK_UNDECLARED_IDENTIFIERS:
2615 if (Record.size() % 4 != 0) {
2616 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002617 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002618 }
2619
2620 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2621 // files. This isn't the way to do it :)
2622 WeakUndeclaredIdentifiers.clear();
2623
2624 // Translate the weak, undeclared identifiers into global IDs.
2625 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2626 WeakUndeclaredIdentifiers.push_back(
2627 getGlobalIdentifierID(F, Record[I++]));
2628 WeakUndeclaredIdentifiers.push_back(
2629 getGlobalIdentifierID(F, Record[I++]));
2630 WeakUndeclaredIdentifiers.push_back(
2631 ReadSourceLocation(F, Record, I).getRawEncoding());
2632 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2633 }
2634 break;
2635
Guy Benyei11169dd2012-12-18 14:30:41 +00002636 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002637 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002638 F.LocalNumSelectors = Record[0];
2639 unsigned LocalBaseSelectorID = Record[1];
2640 F.BaseSelectorID = getTotalNumSelectors();
2641
2642 if (F.LocalNumSelectors > 0) {
2643 // Introduce the global -> local mapping for selectors within this
2644 // module.
2645 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2646
2647 // Introduce the local -> global mapping for selectors within this
2648 // module.
2649 F.SelectorRemap.insertOrReplace(
2650 std::make_pair(LocalBaseSelectorID,
2651 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002652
2653 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002654 }
2655 break;
2656 }
2657
2658 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002659 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002660 if (Record[0])
2661 F.SelectorLookupTable
2662 = ASTSelectorLookupTable::Create(
2663 F.SelectorLookupTableData + Record[0],
2664 F.SelectorLookupTableData,
2665 ASTSelectorLookupTrait(*this, F));
2666 TotalNumMethodPoolEntries += Record[1];
2667 break;
2668
2669 case REFERENCED_SELECTOR_POOL:
2670 if (!Record.empty()) {
2671 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2672 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2673 Record[Idx++]));
2674 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2675 getRawEncoding());
2676 }
2677 }
2678 break;
2679
2680 case PP_COUNTER_VALUE:
2681 if (!Record.empty() && Listener)
2682 Listener->ReadCounter(F, Record[0]);
2683 break;
2684
2685 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002686 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002687 F.NumFileSortedDecls = Record[0];
2688 break;
2689
2690 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002691 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002692 F.LocalNumSLocEntries = Record[0];
2693 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002694 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002695 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002696 SLocSpaceSize);
2697 // Make our entry in the range map. BaseID is negative and growing, so
2698 // we invert it. Because we invert it, though, we need the other end of
2699 // the range.
2700 unsigned RangeStart =
2701 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2702 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2703 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2704
2705 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2706 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2707 GlobalSLocOffsetMap.insert(
2708 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2709 - SLocSpaceSize,&F));
2710
2711 // Initialize the remapping table.
2712 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002713 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002714 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002715 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002716 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2717
2718 TotalNumSLocEntries += F.LocalNumSLocEntries;
2719 break;
2720 }
2721
2722 case MODULE_OFFSET_MAP: {
2723 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002724 const unsigned char *Data = (const unsigned char*)Blob.data();
2725 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002726
2727 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2728 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2729 F.SLocRemap.insert(std::make_pair(0U, 0));
2730 F.SLocRemap.insert(std::make_pair(2U, 1));
2731 }
2732
Guy Benyei11169dd2012-12-18 14:30:41 +00002733 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002734 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2735 RemapBuilder;
2736 RemapBuilder SLocRemap(F.SLocRemap);
2737 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2738 RemapBuilder MacroRemap(F.MacroRemap);
2739 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2740 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2741 RemapBuilder SelectorRemap(F.SelectorRemap);
2742 RemapBuilder DeclRemap(F.DeclRemap);
2743 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002744
2745 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002746 using namespace llvm::support;
2747 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002748 StringRef Name = StringRef((const char*)Data, Len);
2749 Data += Len;
2750 ModuleFile *OM = ModuleMgr.lookup(Name);
2751 if (!OM) {
2752 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002753 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002754 }
2755
Justin Bogner57ba0b22014-03-28 22:03:24 +00002756 uint32_t SLocOffset =
2757 endian::readNext<uint32_t, little, unaligned>(Data);
2758 uint32_t IdentifierIDOffset =
2759 endian::readNext<uint32_t, little, unaligned>(Data);
2760 uint32_t MacroIDOffset =
2761 endian::readNext<uint32_t, little, unaligned>(Data);
2762 uint32_t PreprocessedEntityIDOffset =
2763 endian::readNext<uint32_t, little, unaligned>(Data);
2764 uint32_t SubmoduleIDOffset =
2765 endian::readNext<uint32_t, little, unaligned>(Data);
2766 uint32_t SelectorIDOffset =
2767 endian::readNext<uint32_t, little, unaligned>(Data);
2768 uint32_t DeclIDOffset =
2769 endian::readNext<uint32_t, little, unaligned>(Data);
2770 uint32_t TypeIndexOffset =
2771 endian::readNext<uint32_t, little, unaligned>(Data);
2772
Ben Langmuir785180e2014-10-20 16:27:30 +00002773 uint32_t None = std::numeric_limits<uint32_t>::max();
2774
2775 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2776 RemapBuilder &Remap) {
2777 if (Offset != None)
2778 Remap.insert(std::make_pair(Offset,
2779 static_cast<int>(BaseOffset - Offset)));
2780 };
2781 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2782 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2783 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2784 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2785 PreprocessedEntityRemap);
2786 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2787 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2788 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2789 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002790
2791 // Global -> local mappings.
2792 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2793 }
2794 break;
2795 }
2796
2797 case SOURCE_MANAGER_LINE_TABLE:
2798 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002799 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002800 break;
2801
2802 case SOURCE_LOCATION_PRELOADS: {
2803 // Need to transform from the local view (1-based IDs) to the global view,
2804 // which is based off F.SLocEntryBaseID.
2805 if (!F.PreloadSLocEntries.empty()) {
2806 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002807 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002808 }
2809
2810 F.PreloadSLocEntries.swap(Record);
2811 break;
2812 }
2813
2814 case EXT_VECTOR_DECLS:
2815 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2816 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2817 break;
2818
2819 case VTABLE_USES:
2820 if (Record.size() % 3 != 0) {
2821 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002822 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002823 }
2824
2825 // Later tables overwrite earlier ones.
2826 // FIXME: Modules will have some trouble with this. This is clearly not
2827 // the right way to do this.
2828 VTableUses.clear();
2829
2830 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2831 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2832 VTableUses.push_back(
2833 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2834 VTableUses.push_back(Record[Idx++]);
2835 }
2836 break;
2837
Guy Benyei11169dd2012-12-18 14:30:41 +00002838 case PENDING_IMPLICIT_INSTANTIATIONS:
2839 if (PendingInstantiations.size() % 2 != 0) {
2840 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002841 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002842 }
2843
2844 if (Record.size() % 2 != 0) {
2845 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002846 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002847 }
2848
2849 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2850 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2851 PendingInstantiations.push_back(
2852 ReadSourceLocation(F, Record, I).getRawEncoding());
2853 }
2854 break;
2855
2856 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002857 if (Record.size() != 2) {
2858 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002859 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002860 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002861 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2862 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2863 break;
2864
2865 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002866 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2867 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2868 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002869
2870 unsigned LocalBasePreprocessedEntityID = Record[0];
2871
2872 unsigned StartingID;
2873 if (!PP.getPreprocessingRecord())
2874 PP.createPreprocessingRecord();
2875 if (!PP.getPreprocessingRecord()->getExternalSource())
2876 PP.getPreprocessingRecord()->SetExternalSource(*this);
2877 StartingID
2878 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00002879 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00002880 F.BasePreprocessedEntityID = StartingID;
2881
2882 if (F.NumPreprocessedEntities > 0) {
2883 // Introduce the global -> local mapping for preprocessed entities in
2884 // this module.
2885 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2886
2887 // Introduce the local -> global mapping for preprocessed entities in
2888 // this module.
2889 F.PreprocessedEntityRemap.insertOrReplace(
2890 std::make_pair(LocalBasePreprocessedEntityID,
2891 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2892 }
2893
2894 break;
2895 }
2896
2897 case DECL_UPDATE_OFFSETS: {
2898 if (Record.size() % 2 != 0) {
2899 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002900 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002901 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00002902 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
2903 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
2904 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
2905
2906 // If we've already loaded the decl, perform the updates when we finish
2907 // loading this block.
2908 if (Decl *D = GetExistingDecl(ID))
2909 PendingUpdateRecords.push_back(std::make_pair(ID, D));
2910 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002911 break;
2912 }
2913
2914 case DECL_REPLACEMENTS: {
2915 if (Record.size() % 3 != 0) {
2916 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002917 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002918 }
2919 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2920 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2921 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2922 break;
2923 }
2924
2925 case OBJC_CATEGORIES_MAP: {
2926 if (F.LocalNumObjCCategoriesInMap != 0) {
2927 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002928 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002929 }
2930
2931 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002932 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002933 break;
2934 }
2935
2936 case OBJC_CATEGORIES:
2937 F.ObjCCategories.swap(Record);
2938 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00002939
Guy Benyei11169dd2012-12-18 14:30:41 +00002940 case CXX_BASE_SPECIFIER_OFFSETS: {
2941 if (F.LocalNumCXXBaseSpecifiers != 0) {
2942 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002943 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002944 }
Richard Smithc2bb8182015-03-24 06:36:48 +00002945
Guy Benyei11169dd2012-12-18 14:30:41 +00002946 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002947 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00002948 break;
2949 }
2950
2951 case CXX_CTOR_INITIALIZERS_OFFSETS: {
2952 if (F.LocalNumCXXCtorInitializers != 0) {
2953 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
2954 return Failure;
2955 }
2956
2957 F.LocalNumCXXCtorInitializers = Record[0];
2958 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002959 break;
2960 }
2961
2962 case DIAG_PRAGMA_MAPPINGS:
2963 if (F.PragmaDiagMappings.empty())
2964 F.PragmaDiagMappings.swap(Record);
2965 else
2966 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2967 Record.begin(), Record.end());
2968 break;
2969
2970 case CUDA_SPECIAL_DECL_REFS:
2971 // Later tables overwrite earlier ones.
2972 // FIXME: Modules will have trouble with this.
2973 CUDASpecialDeclRefs.clear();
2974 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2975 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2976 break;
2977
2978 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002979 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002980 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00002981 if (Record[0]) {
2982 F.HeaderFileInfoTable
2983 = HeaderFileInfoLookupTable::Create(
2984 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2985 (const unsigned char *)F.HeaderFileInfoTableData,
2986 HeaderFileInfoTrait(*this, F,
2987 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00002988 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002989
2990 PP.getHeaderSearchInfo().SetExternalSource(this);
2991 if (!PP.getHeaderSearchInfo().getExternalLookup())
2992 PP.getHeaderSearchInfo().SetExternalLookup(this);
2993 }
2994 break;
2995 }
2996
2997 case FP_PRAGMA_OPTIONS:
2998 // Later tables overwrite earlier ones.
2999 FPPragmaOptions.swap(Record);
3000 break;
3001
3002 case OPENCL_EXTENSIONS:
3003 // Later tables overwrite earlier ones.
3004 OpenCLExtensions.swap(Record);
3005 break;
3006
3007 case TENTATIVE_DEFINITIONS:
3008 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3009 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3010 break;
3011
3012 case KNOWN_NAMESPACES:
3013 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3014 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3015 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003016
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003017 case UNDEFINED_BUT_USED:
3018 if (UndefinedButUsed.size() % 2 != 0) {
3019 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003020 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003021 }
3022
3023 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003024 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003025 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003026 }
3027 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003028 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3029 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003030 ReadSourceLocation(F, Record, I).getRawEncoding());
3031 }
3032 break;
3033
Guy Benyei11169dd2012-12-18 14:30:41 +00003034 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003035 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003036 // If we aren't loading a module (which has its own exports), make
3037 // all of the imported modules visible.
3038 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003039 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3040 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3041 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3042 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003043 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003044 }
3045 }
3046 break;
3047 }
3048
3049 case LOCAL_REDECLARATIONS: {
3050 F.RedeclarationChains.swap(Record);
3051 break;
3052 }
3053
3054 case LOCAL_REDECLARATIONS_MAP: {
3055 if (F.LocalNumRedeclarationsInMap != 0) {
3056 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003057 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003058 }
3059
3060 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003061 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003062 break;
3063 }
3064
Guy Benyei11169dd2012-12-18 14:30:41 +00003065 case MACRO_OFFSET: {
3066 if (F.LocalNumMacros != 0) {
3067 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003068 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003069 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003070 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003071 F.LocalNumMacros = Record[0];
3072 unsigned LocalBaseMacroID = Record[1];
3073 F.BaseMacroID = getTotalNumMacros();
3074
3075 if (F.LocalNumMacros > 0) {
3076 // Introduce the global -> local mapping for macros within this module.
3077 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3078
3079 // Introduce the local -> global mapping for macros within this module.
3080 F.MacroRemap.insertOrReplace(
3081 std::make_pair(LocalBaseMacroID,
3082 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003083
3084 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003085 }
3086 break;
3087 }
3088
Richard Smithe40f2ba2013-08-07 21:41:30 +00003089 case LATE_PARSED_TEMPLATE: {
3090 LateParsedTemplates.append(Record.begin(), Record.end());
3091 break;
3092 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003093
3094 case OPTIMIZE_PRAGMA_OPTIONS:
3095 if (Record.size() != 1) {
3096 Error("invalid pragma optimize record");
3097 return Failure;
3098 }
3099 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3100 break;
Nico Weber72889432014-09-06 01:25:55 +00003101
3102 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3103 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3104 UnusedLocalTypedefNameCandidates.push_back(
3105 getGlobalDeclID(F, Record[I]));
3106 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003107 }
3108 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003109}
3110
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003111ASTReader::ASTReadResult
3112ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3113 const ModuleFile *ImportedBy,
3114 unsigned ClientLoadCapabilities) {
3115 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003116 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003117
Richard Smithe842a472014-10-22 02:05:46 +00003118 if (F.Kind == MK_ExplicitModule) {
3119 // For an explicitly-loaded module, we don't care whether the original
3120 // module map file exists or matches.
3121 return Success;
3122 }
3123
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003124 // Try to resolve ModuleName in the current header search context and
3125 // verify that it is found in the same module map file as we saved. If the
3126 // top-level AST file is a main file, skip this check because there is no
3127 // usable header search context.
3128 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003129 "MODULE_NAME should come before MODULE_MAP_FILE");
3130 if (F.Kind == MK_ImplicitModule &&
3131 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3132 // An implicitly-loaded module file should have its module listed in some
3133 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003134 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003135 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3136 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3137 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003138 assert(ImportedBy && "top-level import should be verified");
3139 if ((ClientLoadCapabilities & ARR_Missing) == 0)
Richard Smithe842a472014-10-22 02:05:46 +00003140 Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3141 << ImportedBy->FileName
3142 << F.ModuleMapPath;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003143 return Missing;
3144 }
3145
Richard Smithe842a472014-10-22 02:05:46 +00003146 assert(M->Name == F.ModuleName && "found module with different name");
3147
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003148 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003149 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003150 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3151 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003152 assert(ImportedBy && "top-level import should be verified");
3153 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3154 Diag(diag::err_imported_module_modmap_changed)
3155 << F.ModuleName << ImportedBy->FileName
3156 << ModMap->getName() << F.ModuleMapPath;
3157 return OutOfDate;
3158 }
3159
3160 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3161 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3162 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003163 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003164 const FileEntry *F =
3165 FileMgr.getFile(Filename, false, false);
3166 if (F == nullptr) {
3167 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3168 Error("could not find file '" + Filename +"' referenced by AST file");
3169 return OutOfDate;
3170 }
3171 AdditionalStoredMaps.insert(F);
3172 }
3173
3174 // Check any additional module map files (e.g. module.private.modulemap)
3175 // that are not in the pcm.
3176 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3177 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3178 // Remove files that match
3179 // Note: SmallPtrSet::erase is really remove
3180 if (!AdditionalStoredMaps.erase(ModMap)) {
3181 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3182 Diag(diag::err_module_different_modmap)
3183 << F.ModuleName << /*new*/0 << ModMap->getName();
3184 return OutOfDate;
3185 }
3186 }
3187 }
3188
3189 // Check any additional module map files that are in the pcm, but not
3190 // found in header search. Cases that match are already removed.
3191 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3192 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3193 Diag(diag::err_module_different_modmap)
3194 << F.ModuleName << /*not new*/1 << ModMap->getName();
3195 return OutOfDate;
3196 }
3197 }
3198
3199 if (Listener)
3200 Listener->ReadModuleMapFile(F.ModuleMapPath);
3201 return Success;
3202}
3203
3204
Douglas Gregorc1489562013-02-12 23:36:21 +00003205/// \brief Move the given method to the back of the global list of methods.
3206static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3207 // Find the entry for this selector in the method pool.
3208 Sema::GlobalMethodPool::iterator Known
3209 = S.MethodPool.find(Method->getSelector());
3210 if (Known == S.MethodPool.end())
3211 return;
3212
3213 // Retrieve the appropriate method list.
3214 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3215 : Known->second.second;
3216 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003217 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003218 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003219 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003220 Found = true;
3221 } else {
3222 // Keep searching.
3223 continue;
3224 }
3225 }
3226
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003227 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003228 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003229 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003230 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003231 }
3232}
3233
Richard Smithde711422015-04-23 21:20:19 +00003234void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
3235 assert(Owner->NameVisibility >= Module::MacrosVisible &&
3236 "nothing to make visible?");
3237
Richard Smithe657bbd2014-07-18 22:13:40 +00003238 // FIXME: Only do this if Owner->NameVisibility == AllVisible.
Richard Smith20e883e2015-04-29 23:20:19 +00003239 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003240 bool wasHidden = D->Hidden;
3241 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003242
Richard Smith49f906a2014-03-01 00:08:04 +00003243 if (wasHidden && SemaObj) {
3244 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3245 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003246 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003247 }
3248 }
3249}
3250
Richard Smith49f906a2014-03-01 00:08:04 +00003251void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003252 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003253 SourceLocation ImportLoc,
3254 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003255 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003256 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003257 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003258 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003259 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003260
3261 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003262 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003263 // there is nothing more to do.
3264 continue;
3265 }
Richard Smith49f906a2014-03-01 00:08:04 +00003266
Guy Benyei11169dd2012-12-18 14:30:41 +00003267 if (!Mod->isAvailable()) {
3268 // Modules that aren't available cannot be made visible.
3269 continue;
3270 }
3271
3272 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003273 if (NameVisibility >= Module::MacrosVisible &&
3274 Mod->NameVisibility < Module::MacrosVisible)
3275 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003276 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003277
Guy Benyei11169dd2012-12-18 14:30:41 +00003278 // If we've already deserialized any names from this module,
3279 // mark them as visible.
3280 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3281 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003282 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003283 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003284 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003285 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3286 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003287 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003288
Guy Benyei11169dd2012-12-18 14:30:41 +00003289 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003290 SmallVector<Module *, 16> Exports;
3291 Mod->getExportedModules(Exports);
3292 for (SmallVectorImpl<Module *>::iterator
3293 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3294 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003295 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003296 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003297 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003298
3299 // Detect any conflicts.
3300 if (Complain) {
3301 assert(ImportLoc.isValid() && "Missing import location");
3302 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3303 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3304 Diag(ImportLoc, diag::warn_module_conflict)
3305 << Mod->getFullModuleName()
3306 << Mod->Conflicts[I].Other->getFullModuleName()
3307 << Mod->Conflicts[I].Message;
3308 // FIXME: Need note where the other module was imported.
3309 }
3310 }
3311 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003312 }
3313}
3314
Douglas Gregore060e572013-01-25 01:03:03 +00003315bool ASTReader::loadGlobalIndex() {
3316 if (GlobalIndex)
3317 return false;
3318
3319 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3320 !Context.getLangOpts().Modules)
3321 return true;
3322
3323 // Try to load the global index.
3324 TriedLoadingGlobalIndex = true;
3325 StringRef ModuleCachePath
3326 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3327 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003328 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003329 if (!Result.first)
3330 return true;
3331
3332 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003333 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003334 return false;
3335}
3336
3337bool ASTReader::isGlobalIndexUnavailable() const {
3338 return Context.getLangOpts().Modules && UseGlobalIndex &&
3339 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3340}
3341
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003342static void updateModuleTimestamp(ModuleFile &MF) {
3343 // Overwrite the timestamp file contents so that file's mtime changes.
3344 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003345 std::error_code EC;
3346 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3347 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003348 return;
3349 OS << "Timestamp file\n";
3350}
3351
Guy Benyei11169dd2012-12-18 14:30:41 +00003352ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3353 ModuleKind Type,
3354 SourceLocation ImportLoc,
3355 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003356 llvm::SaveAndRestore<SourceLocation>
3357 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3358
Richard Smithd1c46742014-04-30 02:24:17 +00003359 // Defer any pending actions until we get to the end of reading the AST file.
3360 Deserializing AnASTFile(this);
3361
Guy Benyei11169dd2012-12-18 14:30:41 +00003362 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003363 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003364
3365 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003366 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003367 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003368 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003369 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003370 ClientLoadCapabilities)) {
3371 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003372 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003373 case OutOfDate:
3374 case VersionMismatch:
3375 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003376 case HadErrors: {
3377 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3378 for (const ImportedModule &IM : Loaded)
3379 LoadedSet.insert(IM.Mod);
3380
Douglas Gregor7029ce12013-03-19 00:28:20 +00003381 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003382 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003383 Context.getLangOpts().Modules
3384 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003385 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003386
3387 // If we find that any modules are unusable, the global index is going
3388 // to be out-of-date. Just remove it.
3389 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003390 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003391 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003392 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003393 case Success:
3394 break;
3395 }
3396
3397 // Here comes stuff that we only do once the entire chain is loaded.
3398
3399 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003400 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3401 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003402 M != MEnd; ++M) {
3403 ModuleFile &F = *M->Mod;
3404
3405 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003406 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3407 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003408
3409 // Once read, set the ModuleFile bit base offset and update the size in
3410 // bits of all files we've seen.
3411 F.GlobalBitOffset = TotalModulesSizeInBits;
3412 TotalModulesSizeInBits += F.SizeInBits;
3413 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3414
3415 // Preload SLocEntries.
3416 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3417 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3418 // Load it through the SourceManager and don't call ReadSLocEntry()
3419 // directly because the entry may have already been loaded in which case
3420 // calling ReadSLocEntry() directly would trigger an assertion in
3421 // SourceManager.
3422 SourceMgr.getLoadedSLocEntryByID(Index);
3423 }
3424 }
3425
Douglas Gregor603cd862013-03-22 18:50:14 +00003426 // Setup the import locations and notify the module manager that we've
3427 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003428 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3429 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003430 M != MEnd; ++M) {
3431 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003432
3433 ModuleMgr.moduleFileAccepted(&F);
3434
3435 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003436 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003437 if (!M->ImportedBy)
3438 F.ImportLoc = M->ImportLoc;
3439 else
3440 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3441 M->ImportLoc.getRawEncoding());
3442 }
3443
3444 // Mark all of the identifiers in the identifier table as being out of date,
3445 // so that various accessors know to check the loaded modules when the
3446 // identifier is used.
3447 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3448 IdEnd = PP.getIdentifierTable().end();
3449 Id != IdEnd; ++Id)
3450 Id->second->setOutOfDate(true);
3451
3452 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003453 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3454 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003455 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3456 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003457
3458 switch (Unresolved.Kind) {
3459 case UnresolvedModuleRef::Conflict:
3460 if (ResolvedMod) {
3461 Module::Conflict Conflict;
3462 Conflict.Other = ResolvedMod;
3463 Conflict.Message = Unresolved.String.str();
3464 Unresolved.Mod->Conflicts.push_back(Conflict);
3465 }
3466 continue;
3467
3468 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003469 if (ResolvedMod)
3470 Unresolved.Mod->Imports.push_back(ResolvedMod);
3471 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003472
Douglas Gregorfb912652013-03-20 21:10:35 +00003473 case UnresolvedModuleRef::Export:
3474 if (ResolvedMod || Unresolved.IsWildcard)
3475 Unresolved.Mod->Exports.push_back(
3476 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3477 continue;
3478 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003479 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003480 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003481
3482 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3483 // Might be unnecessary as use declarations are only used to build the
3484 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003485
3486 InitializeContext();
3487
Richard Smith3d8e97e2013-10-18 06:54:39 +00003488 if (SemaObj)
3489 UpdateSema();
3490
Guy Benyei11169dd2012-12-18 14:30:41 +00003491 if (DeserializationListener)
3492 DeserializationListener->ReaderInitialized(this);
3493
3494 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3495 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3496 PrimaryModule.OriginalSourceFileID
3497 = FileID::get(PrimaryModule.SLocEntryBaseID
3498 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3499
3500 // If this AST file is a precompiled preamble, then set the
3501 // preamble file ID of the source manager to the file source file
3502 // from which the preamble was built.
3503 if (Type == MK_Preamble) {
3504 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3505 } else if (Type == MK_MainFile) {
3506 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3507 }
3508 }
3509
3510 // For any Objective-C class definitions we have already loaded, make sure
3511 // that we load any additional categories.
3512 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3513 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3514 ObjCClassesLoaded[I],
3515 PreviousGeneration);
3516 }
Douglas Gregore060e572013-01-25 01:03:03 +00003517
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003518 if (PP.getHeaderSearchInfo()
3519 .getHeaderSearchOpts()
3520 .ModulesValidateOncePerBuildSession) {
3521 // Now we are certain that the module and all modules it depends on are
3522 // up to date. Create or update timestamp files for modules that are
3523 // located in the module cache (not for PCH files that could be anywhere
3524 // in the filesystem).
3525 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3526 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003527 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003528 updateModuleTimestamp(*M.Mod);
3529 }
3530 }
3531 }
3532
Guy Benyei11169dd2012-12-18 14:30:41 +00003533 return Success;
3534}
3535
Ben Langmuir487ea142014-10-23 18:05:36 +00003536static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3537
Ben Langmuir70a1b812015-03-24 04:43:52 +00003538/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3539static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3540 return Stream.Read(8) == 'C' &&
3541 Stream.Read(8) == 'P' &&
3542 Stream.Read(8) == 'C' &&
3543 Stream.Read(8) == 'H';
3544}
3545
Guy Benyei11169dd2012-12-18 14:30:41 +00003546ASTReader::ASTReadResult
3547ASTReader::ReadASTCore(StringRef FileName,
3548 ModuleKind Type,
3549 SourceLocation ImportLoc,
3550 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003551 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003552 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003553 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003554 unsigned ClientLoadCapabilities) {
3555 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003556 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003557 ModuleManager::AddModuleResult AddResult
3558 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003559 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003560 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003561 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003562
Douglas Gregor7029ce12013-03-19 00:28:20 +00003563 switch (AddResult) {
3564 case ModuleManager::AlreadyLoaded:
3565 return Success;
3566
3567 case ModuleManager::NewlyLoaded:
3568 // Load module file below.
3569 break;
3570
3571 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003572 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003573 // it.
3574 if (ClientLoadCapabilities & ARR_Missing)
3575 return Missing;
3576
3577 // Otherwise, return an error.
3578 {
3579 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3580 + ErrorStr;
3581 Error(Msg);
3582 }
3583 return Failure;
3584
3585 case ModuleManager::OutOfDate:
3586 // We couldn't load the module file because it is out-of-date. If the
3587 // client can handle out-of-date, return it.
3588 if (ClientLoadCapabilities & ARR_OutOfDate)
3589 return OutOfDate;
3590
3591 // Otherwise, return an error.
3592 {
3593 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3594 + ErrorStr;
3595 Error(Msg);
3596 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003597 return Failure;
3598 }
3599
Douglas Gregor7029ce12013-03-19 00:28:20 +00003600 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003601
3602 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3603 // module?
3604 if (FileName != "-") {
3605 CurrentDir = llvm::sys::path::parent_path(FileName);
3606 if (CurrentDir.empty()) CurrentDir = ".";
3607 }
3608
3609 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003610 BitstreamCursor &Stream = F.Stream;
Rafael Espindolafd832392014-11-12 14:48:44 +00003611 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003612 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3613
Guy Benyei11169dd2012-12-18 14:30:41 +00003614 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003615 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003616 Diag(diag::err_not_a_pch_file) << FileName;
3617 return Failure;
3618 }
3619
3620 // This is used for compatibility with older PCH formats.
3621 bool HaveReadControlBlock = false;
3622
Chris Lattnerefa77172013-01-20 00:00:22 +00003623 while (1) {
3624 llvm::BitstreamEntry Entry = Stream.advance();
3625
3626 switch (Entry.Kind) {
3627 case llvm::BitstreamEntry::Error:
3628 case llvm::BitstreamEntry::EndBlock:
3629 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003630 Error("invalid record at top-level of AST file");
3631 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003632
3633 case llvm::BitstreamEntry::SubBlock:
3634 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003635 }
3636
Guy Benyei11169dd2012-12-18 14:30:41 +00003637 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003638 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003639 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3640 if (Stream.ReadBlockInfoBlock()) {
3641 Error("malformed BlockInfoBlock in AST file");
3642 return Failure;
3643 }
3644 break;
3645 case CONTROL_BLOCK_ID:
3646 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003647 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003648 case Success:
3649 break;
3650
3651 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003652 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003653 case OutOfDate: return OutOfDate;
3654 case VersionMismatch: return VersionMismatch;
3655 case ConfigurationMismatch: return ConfigurationMismatch;
3656 case HadErrors: return HadErrors;
3657 }
3658 break;
3659 case AST_BLOCK_ID:
3660 if (!HaveReadControlBlock) {
3661 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003662 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003663 return VersionMismatch;
3664 }
3665
3666 // Record that we've loaded this module.
3667 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3668 return Success;
3669
3670 default:
3671 if (Stream.SkipBlock()) {
3672 Error("malformed block record in AST file");
3673 return Failure;
3674 }
3675 break;
3676 }
3677 }
3678
3679 return Success;
3680}
3681
3682void ASTReader::InitializeContext() {
3683 // If there's a listener, notify them that we "read" the translation unit.
3684 if (DeserializationListener)
3685 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3686 Context.getTranslationUnitDecl());
3687
Guy Benyei11169dd2012-12-18 14:30:41 +00003688 // FIXME: Find a better way to deal with collisions between these
3689 // built-in types. Right now, we just ignore the problem.
3690
3691 // Load the special types.
3692 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3693 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3694 if (!Context.CFConstantStringTypeDecl)
3695 Context.setCFConstantStringType(GetType(String));
3696 }
3697
3698 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3699 QualType FileType = GetType(File);
3700 if (FileType.isNull()) {
3701 Error("FILE type is NULL");
3702 return;
3703 }
3704
3705 if (!Context.FILEDecl) {
3706 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3707 Context.setFILEDecl(Typedef->getDecl());
3708 else {
3709 const TagType *Tag = FileType->getAs<TagType>();
3710 if (!Tag) {
3711 Error("Invalid FILE type in AST file");
3712 return;
3713 }
3714 Context.setFILEDecl(Tag->getDecl());
3715 }
3716 }
3717 }
3718
3719 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3720 QualType Jmp_bufType = GetType(Jmp_buf);
3721 if (Jmp_bufType.isNull()) {
3722 Error("jmp_buf type is NULL");
3723 return;
3724 }
3725
3726 if (!Context.jmp_bufDecl) {
3727 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3728 Context.setjmp_bufDecl(Typedef->getDecl());
3729 else {
3730 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3731 if (!Tag) {
3732 Error("Invalid jmp_buf type in AST file");
3733 return;
3734 }
3735 Context.setjmp_bufDecl(Tag->getDecl());
3736 }
3737 }
3738 }
3739
3740 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3741 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3742 if (Sigjmp_bufType.isNull()) {
3743 Error("sigjmp_buf type is NULL");
3744 return;
3745 }
3746
3747 if (!Context.sigjmp_bufDecl) {
3748 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3749 Context.setsigjmp_bufDecl(Typedef->getDecl());
3750 else {
3751 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3752 assert(Tag && "Invalid sigjmp_buf type in AST file");
3753 Context.setsigjmp_bufDecl(Tag->getDecl());
3754 }
3755 }
3756 }
3757
3758 if (unsigned ObjCIdRedef
3759 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3760 if (Context.ObjCIdRedefinitionType.isNull())
3761 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3762 }
3763
3764 if (unsigned ObjCClassRedef
3765 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3766 if (Context.ObjCClassRedefinitionType.isNull())
3767 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3768 }
3769
3770 if (unsigned ObjCSelRedef
3771 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3772 if (Context.ObjCSelRedefinitionType.isNull())
3773 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3774 }
3775
3776 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3777 QualType Ucontext_tType = GetType(Ucontext_t);
3778 if (Ucontext_tType.isNull()) {
3779 Error("ucontext_t type is NULL");
3780 return;
3781 }
3782
3783 if (!Context.ucontext_tDecl) {
3784 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3785 Context.setucontext_tDecl(Typedef->getDecl());
3786 else {
3787 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3788 assert(Tag && "Invalid ucontext_t type in AST file");
3789 Context.setucontext_tDecl(Tag->getDecl());
3790 }
3791 }
3792 }
3793 }
3794
3795 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3796
3797 // If there were any CUDA special declarations, deserialize them.
3798 if (!CUDASpecialDeclRefs.empty()) {
3799 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3800 Context.setcudaConfigureCallDecl(
3801 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3802 }
Richard Smith56be7542014-03-21 00:33:59 +00003803
Guy Benyei11169dd2012-12-18 14:30:41 +00003804 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00003805 // FIXME: This does not make macro-only imports visible again. It also doesn't
3806 // make #includes mapped to module imports visible.
3807 for (auto &Import : ImportedModules) {
3808 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003809 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00003810 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00003811 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00003812 }
3813 ImportedModules.clear();
3814}
3815
3816void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00003817 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00003818}
3819
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003820/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3821/// cursor into the start of the given block ID, returning false on success and
3822/// true on failure.
3823static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003824 while (1) {
3825 llvm::BitstreamEntry Entry = Cursor.advance();
3826 switch (Entry.Kind) {
3827 case llvm::BitstreamEntry::Error:
3828 case llvm::BitstreamEntry::EndBlock:
3829 return true;
3830
3831 case llvm::BitstreamEntry::Record:
3832 // Ignore top-level records.
3833 Cursor.skipRecord(Entry.ID);
3834 break;
3835
3836 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003837 if (Entry.ID == BlockID) {
3838 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003839 return true;
3840 // Found it!
3841 return false;
3842 }
3843
3844 if (Cursor.SkipBlock())
3845 return true;
3846 }
3847 }
3848}
3849
Ben Langmuir70a1b812015-03-24 04:43:52 +00003850/// \brief Reads and return the signature record from \p StreamFile's control
3851/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00003852static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
3853 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00003854 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00003855 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00003856
3857 // Scan for the CONTROL_BLOCK_ID block.
3858 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
3859 return 0;
3860
3861 // Scan for SIGNATURE inside the control block.
3862 ASTReader::RecordData Record;
3863 while (1) {
3864 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3865 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
3866 Entry.Kind != llvm::BitstreamEntry::Record)
3867 return 0;
3868
3869 Record.clear();
3870 StringRef Blob;
3871 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
3872 return Record[0];
3873 }
3874}
3875
Guy Benyei11169dd2012-12-18 14:30:41 +00003876/// \brief Retrieve the name of the original source file name
3877/// directly from the AST file, without actually loading the AST
3878/// file.
3879std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3880 FileManager &FileMgr,
3881 DiagnosticsEngine &Diags) {
3882 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00003883 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00003884 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00003885 Diags.Report(diag::err_fe_unable_to_read_pch_file)
3886 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00003887 return std::string();
3888 }
3889
3890 // Initialize the stream
3891 llvm::BitstreamReader StreamFile;
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003892 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
3893 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00003894 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003895
3896 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003897 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003898 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3899 return std::string();
3900 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003901
Chris Lattnere7b154b2013-01-19 21:39:22 +00003902 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003903 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003904 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3905 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003906 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003907
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003908 // Scan for ORIGINAL_FILE inside the control block.
3909 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003910 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003911 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003912 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3913 return std::string();
3914
3915 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3916 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3917 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003918 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003919
Guy Benyei11169dd2012-12-18 14:30:41 +00003920 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003921 StringRef Blob;
3922 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3923 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003924 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003925}
3926
3927namespace {
3928 class SimplePCHValidator : public ASTReaderListener {
3929 const LangOptions &ExistingLangOpts;
3930 const TargetOptions &ExistingTargetOpts;
3931 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003932 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00003933 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003934
Guy Benyei11169dd2012-12-18 14:30:41 +00003935 public:
3936 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3937 const TargetOptions &ExistingTargetOpts,
3938 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003939 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00003940 FileManager &FileMgr)
3941 : ExistingLangOpts(ExistingLangOpts),
3942 ExistingTargetOpts(ExistingTargetOpts),
3943 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003944 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00003945 FileMgr(FileMgr)
3946 {
3947 }
3948
Richard Smith1e2cf0d2014-10-31 02:28:58 +00003949 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
3950 bool AllowCompatibleDifferences) override {
3951 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
3952 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00003953 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00003954 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
3955 bool AllowCompatibleDifferences) override {
3956 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
3957 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00003958 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003959 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
3960 StringRef SpecificModuleCachePath,
3961 bool Complain) override {
3962 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
3963 ExistingModuleCachePath,
3964 nullptr, ExistingLangOpts);
3965 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003966 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3967 bool Complain,
3968 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00003969 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00003970 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00003971 }
3972 };
3973}
3974
3975bool ASTReader::readASTFileControlBlock(StringRef Filename,
3976 FileManager &FileMgr,
3977 ASTReaderListener &Listener) {
3978 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00003979 // FIXME: This allows use of the VFS; we do not allow use of the
3980 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00003981 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00003982 if (!Buffer) {
3983 return true;
3984 }
3985
3986 // Initialize the stream
3987 llvm::BitstreamReader StreamFile;
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003988 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
3989 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00003990 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003991
3992 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003993 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00003994 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003995
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003996 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003997 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003998 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003999
4000 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004001 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004002 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004003 BitstreamCursor InputFilesCursor;
4004 if (NeedsInputFiles) {
4005 InputFilesCursor = Stream;
4006 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4007 return true;
4008
4009 // Read the abbreviations
4010 while (true) {
4011 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4012 unsigned Code = InputFilesCursor.ReadCode();
4013
4014 // We expect all abbrevs to be at the start of the block.
4015 if (Code != llvm::bitc::DEFINE_ABBREV) {
4016 InputFilesCursor.JumpToBit(Offset);
4017 break;
4018 }
4019 InputFilesCursor.ReadAbbrevRecord();
4020 }
4021 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004022
4023 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004024 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004025 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004026 while (1) {
4027 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4028 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4029 return false;
4030
4031 if (Entry.Kind != llvm::BitstreamEntry::Record)
4032 return true;
4033
Guy Benyei11169dd2012-12-18 14:30:41 +00004034 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004035 StringRef Blob;
4036 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004037 switch ((ControlRecordTypes)RecCode) {
4038 case METADATA: {
4039 if (Record[0] != VERSION_MAJOR)
4040 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004041
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004042 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004043 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004044
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004045 break;
4046 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004047 case MODULE_NAME:
4048 Listener.ReadModuleName(Blob);
4049 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004050 case MODULE_DIRECTORY:
4051 ModuleDir = Blob;
4052 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004053 case MODULE_MAP_FILE: {
4054 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004055 auto Path = ReadString(Record, Idx);
4056 ResolveImportedPath(Path, ModuleDir);
4057 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004058 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004059 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004060 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004061 if (ParseLanguageOptions(Record, false, Listener,
4062 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004063 return true;
4064 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004065
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004066 case TARGET_OPTIONS:
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004067 if (ParseTargetOptions(Record, false, Listener,
4068 /*AllowCompatibleConfigurationMismatch*/ false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004069 return true;
4070 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004071
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004072 case DIAGNOSTIC_OPTIONS:
4073 if (ParseDiagnosticOptions(Record, false, Listener))
4074 return true;
4075 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004076
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004077 case FILE_SYSTEM_OPTIONS:
4078 if (ParseFileSystemOptions(Record, false, Listener))
4079 return true;
4080 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004081
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004082 case HEADER_SEARCH_OPTIONS:
4083 if (ParseHeaderSearchOptions(Record, false, Listener))
4084 return true;
4085 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004086
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004087 case PREPROCESSOR_OPTIONS: {
4088 std::string IgnoredSuggestedPredefines;
4089 if (ParsePreprocessorOptions(Record, false, Listener,
4090 IgnoredSuggestedPredefines))
4091 return true;
4092 break;
4093 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004094
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004095 case INPUT_FILE_OFFSETS: {
4096 if (!NeedsInputFiles)
4097 break;
4098
4099 unsigned NumInputFiles = Record[0];
4100 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004101 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004102 for (unsigned I = 0; I != NumInputFiles; ++I) {
4103 // Go find this input file.
4104 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004105
4106 if (isSystemFile && !NeedsSystemInputFiles)
4107 break; // the rest are system input files
4108
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004109 BitstreamCursor &Cursor = InputFilesCursor;
4110 SavedStreamPosition SavedPosition(Cursor);
4111 Cursor.JumpToBit(InputFileOffs[I]);
4112
4113 unsigned Code = Cursor.ReadCode();
4114 RecordData Record;
4115 StringRef Blob;
4116 bool shouldContinue = false;
4117 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4118 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004119 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004120 std::string Filename = Blob;
4121 ResolveImportedPath(Filename, ModuleDir);
4122 shouldContinue =
4123 Listener.visitInputFile(Filename, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004124 break;
4125 }
4126 if (!shouldContinue)
4127 break;
4128 }
4129 break;
4130 }
4131
Richard Smithd4b230b2014-10-27 23:01:16 +00004132 case IMPORTS: {
4133 if (!NeedsImports)
4134 break;
4135
4136 unsigned Idx = 0, N = Record.size();
4137 while (Idx < N) {
4138 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004139 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004140 std::string Filename = ReadString(Record, Idx);
4141 ResolveImportedPath(Filename, ModuleDir);
4142 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004143 }
4144 break;
4145 }
4146
Richard Smith7f330cd2015-03-18 01:42:29 +00004147 case KNOWN_MODULE_FILES: {
4148 // Known-but-not-technically-used module files are treated as imports.
4149 if (!NeedsImports)
4150 break;
4151
4152 unsigned Idx = 0, N = Record.size();
4153 while (Idx < N) {
4154 std::string Filename = ReadString(Record, Idx);
4155 ResolveImportedPath(Filename, ModuleDir);
4156 Listener.visitImport(Filename);
4157 }
4158 break;
4159 }
4160
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004161 default:
4162 // No other validation to perform.
4163 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004164 }
4165 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004166}
4167
4168
4169bool ASTReader::isAcceptableASTFile(StringRef Filename,
4170 FileManager &FileMgr,
4171 const LangOptions &LangOpts,
4172 const TargetOptions &TargetOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004173 const PreprocessorOptions &PPOpts,
4174 std::string ExistingModuleCachePath) {
4175 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4176 ExistingModuleCachePath, FileMgr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004177 return !readASTFileControlBlock(Filename, FileMgr, validator);
4178}
4179
Ben Langmuir2c9af442014-04-10 17:57:43 +00004180ASTReader::ASTReadResult
4181ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004182 // Enter the submodule block.
4183 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4184 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004185 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004186 }
4187
4188 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4189 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004190 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004191 RecordData Record;
4192 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004193 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4194
4195 switch (Entry.Kind) {
4196 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4197 case llvm::BitstreamEntry::Error:
4198 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004199 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004200 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004201 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004202 case llvm::BitstreamEntry::Record:
4203 // The interesting case.
4204 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004205 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004206
Guy Benyei11169dd2012-12-18 14:30:41 +00004207 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004208 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004209 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004210 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4211
4212 if ((Kind == SUBMODULE_METADATA) != First) {
4213 Error("submodule metadata record should be at beginning of block");
4214 return Failure;
4215 }
4216 First = false;
4217
4218 // Submodule information is only valid if we have a current module.
4219 // FIXME: Should we error on these cases?
4220 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4221 Kind != SUBMODULE_DEFINITION)
4222 continue;
4223
4224 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004225 default: // Default behavior: ignore.
4226 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004227
Richard Smith03478d92014-10-23 22:12:14 +00004228 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004229 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004230 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004231 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004232 }
Richard Smith03478d92014-10-23 22:12:14 +00004233
Chris Lattner0e6c9402013-01-20 02:38:54 +00004234 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004235 unsigned Idx = 0;
4236 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4237 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4238 bool IsFramework = Record[Idx++];
4239 bool IsExplicit = Record[Idx++];
4240 bool IsSystem = Record[Idx++];
4241 bool IsExternC = Record[Idx++];
4242 bool InferSubmodules = Record[Idx++];
4243 bool InferExplicitSubmodules = Record[Idx++];
4244 bool InferExportWildcard = Record[Idx++];
4245 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004246
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004247 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004248 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004249 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004250
Guy Benyei11169dd2012-12-18 14:30:41 +00004251 // Retrieve this (sub)module from the module map, creating it if
4252 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004253 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004254 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004255
4256 // FIXME: set the definition loc for CurrentModule, or call
4257 // ModMap.setInferredModuleAllowedBy()
4258
Guy Benyei11169dd2012-12-18 14:30:41 +00004259 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4260 if (GlobalIndex >= SubmodulesLoaded.size() ||
4261 SubmodulesLoaded[GlobalIndex]) {
4262 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004263 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004264 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004265
Douglas Gregor7029ce12013-03-19 00:28:20 +00004266 if (!ParentModule) {
4267 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4268 if (CurFile != F.File) {
4269 if (!Diags.isDiagnosticInFlight()) {
4270 Diag(diag::err_module_file_conflict)
4271 << CurrentModule->getTopLevelModuleName()
4272 << CurFile->getName()
4273 << F.File->getName();
4274 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004275 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004276 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004277 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004278
4279 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004280 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004281
Guy Benyei11169dd2012-12-18 14:30:41 +00004282 CurrentModule->IsFromModuleFile = true;
4283 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004284 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004285 CurrentModule->InferSubmodules = InferSubmodules;
4286 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4287 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004288 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004289 if (DeserializationListener)
4290 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4291
4292 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004293
Douglas Gregorfb912652013-03-20 21:10:35 +00004294 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004295 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004296 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004297 CurrentModule->UnresolvedConflicts.clear();
4298 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004299 break;
4300 }
4301
4302 case SUBMODULE_UMBRELLA_HEADER: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004303 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004304 if (!CurrentModule->getUmbrellaHeader())
4305 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4306 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004307 // This can be a spurious difference caused by changing the VFS to
4308 // point to a different copy of the file, and it is too late to
4309 // to rebuild safely.
4310 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4311 // after input file validation only real problems would remain and we
4312 // could just error. For now, assume it's okay.
4313 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004314 }
4315 }
4316 break;
4317 }
4318
Richard Smith202210b2014-10-24 20:23:01 +00004319 case SUBMODULE_HEADER:
4320 case SUBMODULE_EXCLUDED_HEADER:
4321 case SUBMODULE_PRIVATE_HEADER:
4322 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004323 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4324 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004325 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004326
Richard Smith202210b2014-10-24 20:23:01 +00004327 case SUBMODULE_TEXTUAL_HEADER:
4328 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4329 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4330 // them here.
4331 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004332
Guy Benyei11169dd2012-12-18 14:30:41 +00004333 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004334 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004335 break;
4336 }
4337
4338 case SUBMODULE_UMBRELLA_DIR: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004339 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004340 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004341 if (!CurrentModule->getUmbrellaDir())
4342 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4343 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004344 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4345 Error("mismatched umbrella directories in submodule");
4346 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004347 }
4348 }
4349 break;
4350 }
4351
4352 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004353 F.BaseSubmoduleID = getTotalNumSubmodules();
4354 F.LocalNumSubmodules = Record[0];
4355 unsigned LocalBaseSubmoduleID = Record[1];
4356 if (F.LocalNumSubmodules > 0) {
4357 // Introduce the global -> local mapping for submodules within this
4358 // module.
4359 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4360
4361 // Introduce the local -> global mapping for submodules within this
4362 // module.
4363 F.SubmoduleRemap.insertOrReplace(
4364 std::make_pair(LocalBaseSubmoduleID,
4365 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004366
Ben Langmuir52ca6782014-10-20 16:27:32 +00004367 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4368 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004369 break;
4370 }
4371
4372 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004373 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004374 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004375 Unresolved.File = &F;
4376 Unresolved.Mod = CurrentModule;
4377 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004378 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004379 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004380 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004381 }
4382 break;
4383 }
4384
4385 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004386 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004387 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004388 Unresolved.File = &F;
4389 Unresolved.Mod = CurrentModule;
4390 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004391 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004392 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004393 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004394 }
4395
4396 // Once we've loaded the set of exports, there's no reason to keep
4397 // the parsed, unresolved exports around.
4398 CurrentModule->UnresolvedExports.clear();
4399 break;
4400 }
4401 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004402 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004403 Context.getTargetInfo());
4404 break;
4405 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004406
4407 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004408 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004409 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004410 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004411
4412 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004413 CurrentModule->ConfigMacros.push_back(Blob.str());
4414 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004415
4416 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004417 UnresolvedModuleRef Unresolved;
4418 Unresolved.File = &F;
4419 Unresolved.Mod = CurrentModule;
4420 Unresolved.ID = Record[0];
4421 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4422 Unresolved.IsWildcard = false;
4423 Unresolved.String = Blob;
4424 UnresolvedModuleRefs.push_back(Unresolved);
4425 break;
4426 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004427 }
4428 }
4429}
4430
4431/// \brief Parse the record that corresponds to a LangOptions data
4432/// structure.
4433///
4434/// This routine parses the language options from the AST file and then gives
4435/// them to the AST listener if one is set.
4436///
4437/// \returns true if the listener deems the file unacceptable, false otherwise.
4438bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4439 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004440 ASTReaderListener &Listener,
4441 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004442 LangOptions LangOpts;
4443 unsigned Idx = 0;
4444#define LANGOPT(Name, Bits, Default, Description) \
4445 LangOpts.Name = Record[Idx++];
4446#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4447 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4448#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004449#define SANITIZER(NAME, ID) \
4450 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004451#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004452
4453 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4454 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4455 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4456
4457 unsigned Length = Record[Idx++];
4458 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4459 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004460
4461 Idx += Length;
4462
4463 // Comment options.
4464 for (unsigned N = Record[Idx++]; N; --N) {
4465 LangOpts.CommentOpts.BlockCommandNames.push_back(
4466 ReadString(Record, Idx));
4467 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004468 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004469
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004470 return Listener.ReadLanguageOptions(LangOpts, Complain,
4471 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004472}
4473
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004474bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4475 ASTReaderListener &Listener,
4476 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004477 unsigned Idx = 0;
4478 TargetOptions TargetOpts;
4479 TargetOpts.Triple = ReadString(Record, Idx);
4480 TargetOpts.CPU = ReadString(Record, Idx);
4481 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004482 for (unsigned N = Record[Idx++]; N; --N) {
4483 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4484 }
4485 for (unsigned N = Record[Idx++]; N; --N) {
4486 TargetOpts.Features.push_back(ReadString(Record, Idx));
4487 }
4488
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004489 return Listener.ReadTargetOptions(TargetOpts, Complain,
4490 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004491}
4492
4493bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4494 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004495 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004496 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004497#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004498#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004499 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004500#include "clang/Basic/DiagnosticOptions.def"
4501
Richard Smith3be1cb22014-08-07 00:24:21 +00004502 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004503 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004504 for (unsigned N = Record[Idx++]; N; --N)
4505 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004506
4507 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4508}
4509
4510bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4511 ASTReaderListener &Listener) {
4512 FileSystemOptions FSOpts;
4513 unsigned Idx = 0;
4514 FSOpts.WorkingDir = ReadString(Record, Idx);
4515 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4516}
4517
4518bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4519 bool Complain,
4520 ASTReaderListener &Listener) {
4521 HeaderSearchOptions HSOpts;
4522 unsigned Idx = 0;
4523 HSOpts.Sysroot = ReadString(Record, Idx);
4524
4525 // Include entries.
4526 for (unsigned N = Record[Idx++]; N; --N) {
4527 std::string Path = ReadString(Record, Idx);
4528 frontend::IncludeDirGroup Group
4529 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004530 bool IsFramework = Record[Idx++];
4531 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004532 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004533 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004534 }
4535
4536 // System header prefixes.
4537 for (unsigned N = Record[Idx++]; N; --N) {
4538 std::string Prefix = ReadString(Record, Idx);
4539 bool IsSystemHeader = Record[Idx++];
4540 HSOpts.SystemHeaderPrefixes.push_back(
4541 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4542 }
4543
4544 HSOpts.ResourceDir = ReadString(Record, Idx);
4545 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004546 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004547 HSOpts.DisableModuleHash = Record[Idx++];
4548 HSOpts.UseBuiltinIncludes = Record[Idx++];
4549 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4550 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4551 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004552 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004553
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004554 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4555 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004556}
4557
4558bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4559 bool Complain,
4560 ASTReaderListener &Listener,
4561 std::string &SuggestedPredefines) {
4562 PreprocessorOptions PPOpts;
4563 unsigned Idx = 0;
4564
4565 // Macro definitions/undefs
4566 for (unsigned N = Record[Idx++]; N; --N) {
4567 std::string Macro = ReadString(Record, Idx);
4568 bool IsUndef = Record[Idx++];
4569 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4570 }
4571
4572 // Includes
4573 for (unsigned N = Record[Idx++]; N; --N) {
4574 PPOpts.Includes.push_back(ReadString(Record, Idx));
4575 }
4576
4577 // Macro Includes
4578 for (unsigned N = Record[Idx++]; N; --N) {
4579 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4580 }
4581
4582 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004583 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004584 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4585 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4586 PPOpts.ObjCXXARCStandardLibrary =
4587 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4588 SuggestedPredefines.clear();
4589 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4590 SuggestedPredefines);
4591}
4592
4593std::pair<ModuleFile *, unsigned>
4594ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4595 GlobalPreprocessedEntityMapType::iterator
4596 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4597 assert(I != GlobalPreprocessedEntityMap.end() &&
4598 "Corrupted global preprocessed entity map");
4599 ModuleFile *M = I->second;
4600 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4601 return std::make_pair(M, LocalIndex);
4602}
4603
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004604llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004605ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4606 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4607 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4608 Mod.NumPreprocessedEntities);
4609
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004610 return llvm::make_range(PreprocessingRecord::iterator(),
4611 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004612}
4613
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004614llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004615ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004616 return llvm::make_range(
4617 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4618 ModuleDeclIterator(this, &Mod,
4619 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004620}
4621
4622PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4623 PreprocessedEntityID PPID = Index+1;
4624 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4625 ModuleFile &M = *PPInfo.first;
4626 unsigned LocalIndex = PPInfo.second;
4627 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4628
Guy Benyei11169dd2012-12-18 14:30:41 +00004629 if (!PP.getPreprocessingRecord()) {
4630 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004631 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004632 }
4633
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004634 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4635 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4636
4637 llvm::BitstreamEntry Entry =
4638 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4639 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004640 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004641
Guy Benyei11169dd2012-12-18 14:30:41 +00004642 // Read the record.
4643 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4644 ReadSourceLocation(M, PPOffs.End));
4645 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004646 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004647 RecordData Record;
4648 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004649 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4650 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004651 switch (RecType) {
4652 case PPD_MACRO_EXPANSION: {
4653 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004654 IdentifierInfo *Name = nullptr;
4655 MacroDefinition *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004656 if (isBuiltin)
4657 Name = getLocalIdentifier(M, Record[1]);
4658 else {
4659 PreprocessedEntityID
4660 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4661 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4662 }
4663
4664 MacroExpansion *ME;
4665 if (isBuiltin)
4666 ME = new (PPRec) MacroExpansion(Name, Range);
4667 else
4668 ME = new (PPRec) MacroExpansion(Def, Range);
4669
4670 return ME;
4671 }
4672
4673 case PPD_MACRO_DEFINITION: {
4674 // Decode the identifier info and then check again; if the macro is
4675 // still defined and associated with the identifier,
4676 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4677 MacroDefinition *MD
4678 = new (PPRec) MacroDefinition(II, Range);
4679
4680 if (DeserializationListener)
4681 DeserializationListener->MacroDefinitionRead(PPID, MD);
4682
4683 return MD;
4684 }
4685
4686 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004687 const char *FullFileNameStart = Blob.data() + Record[0];
4688 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004689 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004690 if (!FullFileName.empty())
4691 File = PP.getFileManager().getFile(FullFileName);
4692
4693 // FIXME: Stable encoding
4694 InclusionDirective::InclusionKind Kind
4695 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4696 InclusionDirective *ID
4697 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004698 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004699 Record[1], Record[3],
4700 File,
4701 Range);
4702 return ID;
4703 }
4704 }
4705
4706 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4707}
4708
4709/// \brief \arg SLocMapI points at a chunk of a module that contains no
4710/// preprocessed entities or the entities it contains are not the ones we are
4711/// looking for. Find the next module that contains entities and return the ID
4712/// of the first entry.
4713PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4714 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4715 ++SLocMapI;
4716 for (GlobalSLocOffsetMapType::const_iterator
4717 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4718 ModuleFile &M = *SLocMapI->second;
4719 if (M.NumPreprocessedEntities)
4720 return M.BasePreprocessedEntityID;
4721 }
4722
4723 return getTotalNumPreprocessedEntities();
4724}
4725
4726namespace {
4727
4728template <unsigned PPEntityOffset::*PPLoc>
4729struct PPEntityComp {
4730 const ASTReader &Reader;
4731 ModuleFile &M;
4732
4733 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4734
4735 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4736 SourceLocation LHS = getLoc(L);
4737 SourceLocation RHS = getLoc(R);
4738 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4739 }
4740
4741 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4742 SourceLocation LHS = getLoc(L);
4743 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4744 }
4745
4746 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4747 SourceLocation RHS = getLoc(R);
4748 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4749 }
4750
4751 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4752 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4753 }
4754};
4755
4756}
4757
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004758PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4759 bool EndsAfter) const {
4760 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004761 return getTotalNumPreprocessedEntities();
4762
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004763 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4764 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004765 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4766 "Corrupted global sloc offset map");
4767
4768 if (SLocMapI->second->NumPreprocessedEntities == 0)
4769 return findNextPreprocessedEntity(SLocMapI);
4770
4771 ModuleFile &M = *SLocMapI->second;
4772 typedef const PPEntityOffset *pp_iterator;
4773 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4774 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4775
4776 size_t Count = M.NumPreprocessedEntities;
4777 size_t Half;
4778 pp_iterator First = pp_begin;
4779 pp_iterator PPI;
4780
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004781 if (EndsAfter) {
4782 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4783 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4784 } else {
4785 // Do a binary search manually instead of using std::lower_bound because
4786 // The end locations of entities may be unordered (when a macro expansion
4787 // is inside another macro argument), but for this case it is not important
4788 // whether we get the first macro expansion or its containing macro.
4789 while (Count > 0) {
4790 Half = Count / 2;
4791 PPI = First;
4792 std::advance(PPI, Half);
4793 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4794 Loc)) {
4795 First = PPI;
4796 ++First;
4797 Count = Count - Half - 1;
4798 } else
4799 Count = Half;
4800 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004801 }
4802
4803 if (PPI == pp_end)
4804 return findNextPreprocessedEntity(SLocMapI);
4805
4806 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4807}
4808
Guy Benyei11169dd2012-12-18 14:30:41 +00004809/// \brief Returns a pair of [Begin, End) indices of preallocated
4810/// preprocessed entities that \arg Range encompasses.
4811std::pair<unsigned, unsigned>
4812 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4813 if (Range.isInvalid())
4814 return std::make_pair(0,0);
4815 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4816
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004817 PreprocessedEntityID BeginID =
4818 findPreprocessedEntity(Range.getBegin(), false);
4819 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004820 return std::make_pair(BeginID, EndID);
4821}
4822
4823/// \brief Optionally returns true or false if the preallocated preprocessed
4824/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004825Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004826 FileID FID) {
4827 if (FID.isInvalid())
4828 return false;
4829
4830 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4831 ModuleFile &M = *PPInfo.first;
4832 unsigned LocalIndex = PPInfo.second;
4833 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4834
4835 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4836 if (Loc.isInvalid())
4837 return false;
4838
4839 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4840 return true;
4841 else
4842 return false;
4843}
4844
4845namespace {
4846 /// \brief Visitor used to search for information about a header file.
4847 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004848 const FileEntry *FE;
4849
David Blaikie05785d12013-02-20 22:23:23 +00004850 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004851
4852 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004853 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4854 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004855
4856 static bool visit(ModuleFile &M, void *UserData) {
4857 HeaderFileInfoVisitor *This
4858 = static_cast<HeaderFileInfoVisitor *>(UserData);
4859
Guy Benyei11169dd2012-12-18 14:30:41 +00004860 HeaderFileInfoLookupTable *Table
4861 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4862 if (!Table)
4863 return false;
4864
4865 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00004866 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004867 if (Pos == Table->end())
4868 return false;
4869
4870 This->HFI = *Pos;
4871 return true;
4872 }
4873
David Blaikie05785d12013-02-20 22:23:23 +00004874 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004875 };
4876}
4877
4878HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004879 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004880 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004881 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004882 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004883
4884 return HeaderFileInfo();
4885}
4886
4887void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4888 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004889 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004890 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4891 ModuleFile &F = *(*I);
4892 unsigned Idx = 0;
4893 DiagStates.clear();
4894 assert(!Diag.DiagStates.empty());
4895 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4896 while (Idx < F.PragmaDiagMappings.size()) {
4897 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4898 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4899 if (DiagStateID != 0) {
4900 Diag.DiagStatePoints.push_back(
4901 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4902 FullSourceLoc(Loc, SourceMgr)));
4903 continue;
4904 }
4905
4906 assert(DiagStateID == 0);
4907 // A new DiagState was created here.
4908 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4909 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4910 DiagStates.push_back(NewState);
4911 Diag.DiagStatePoints.push_back(
4912 DiagnosticsEngine::DiagStatePoint(NewState,
4913 FullSourceLoc(Loc, SourceMgr)));
4914 while (1) {
4915 assert(Idx < F.PragmaDiagMappings.size() &&
4916 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4917 if (Idx >= F.PragmaDiagMappings.size()) {
4918 break; // Something is messed up but at least avoid infinite loop in
4919 // release build.
4920 }
4921 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4922 if (DiagID == (unsigned)-1) {
4923 break; // no more diag/map pairs for this location.
4924 }
Alp Tokerc726c362014-06-10 09:31:37 +00004925 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
4926 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
4927 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00004928 }
4929 }
4930 }
4931}
4932
4933/// \brief Get the correct cursor and offset for loading a type.
4934ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4935 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4936 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4937 ModuleFile *M = I->second;
4938 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4939}
4940
4941/// \brief Read and return the type with the given index..
4942///
4943/// The index is the type ID, shifted and minus the number of predefs. This
4944/// routine actually reads the record corresponding to the type at the given
4945/// location. It is a helper routine for GetType, which deals with reading type
4946/// IDs.
4947QualType ASTReader::readTypeRecord(unsigned Index) {
4948 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004949 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00004950
4951 // Keep track of where we are in the stream, then jump back there
4952 // after reading this type.
4953 SavedStreamPosition SavedPosition(DeclsCursor);
4954
4955 ReadingKindTracker ReadingKind(Read_Type, *this);
4956
4957 // Note that we are loading a type record.
4958 Deserializing AType(this);
4959
4960 unsigned Idx = 0;
4961 DeclsCursor.JumpToBit(Loc.Offset);
4962 RecordData Record;
4963 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004964 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004965 case TYPE_EXT_QUAL: {
4966 if (Record.size() != 2) {
4967 Error("Incorrect encoding of extended qualifier type");
4968 return QualType();
4969 }
4970 QualType Base = readType(*Loc.F, Record, Idx);
4971 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4972 return Context.getQualifiedType(Base, Quals);
4973 }
4974
4975 case TYPE_COMPLEX: {
4976 if (Record.size() != 1) {
4977 Error("Incorrect encoding of complex type");
4978 return QualType();
4979 }
4980 QualType ElemType = readType(*Loc.F, Record, Idx);
4981 return Context.getComplexType(ElemType);
4982 }
4983
4984 case TYPE_POINTER: {
4985 if (Record.size() != 1) {
4986 Error("Incorrect encoding of pointer type");
4987 return QualType();
4988 }
4989 QualType PointeeType = readType(*Loc.F, Record, Idx);
4990 return Context.getPointerType(PointeeType);
4991 }
4992
Reid Kleckner8a365022013-06-24 17:51:48 +00004993 case TYPE_DECAYED: {
4994 if (Record.size() != 1) {
4995 Error("Incorrect encoding of decayed type");
4996 return QualType();
4997 }
4998 QualType OriginalType = readType(*Loc.F, Record, Idx);
4999 QualType DT = Context.getAdjustedParameterType(OriginalType);
5000 if (!isa<DecayedType>(DT))
5001 Error("Decayed type does not decay");
5002 return DT;
5003 }
5004
Reid Kleckner0503a872013-12-05 01:23:43 +00005005 case TYPE_ADJUSTED: {
5006 if (Record.size() != 2) {
5007 Error("Incorrect encoding of adjusted type");
5008 return QualType();
5009 }
5010 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5011 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5012 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5013 }
5014
Guy Benyei11169dd2012-12-18 14:30:41 +00005015 case TYPE_BLOCK_POINTER: {
5016 if (Record.size() != 1) {
5017 Error("Incorrect encoding of block pointer type");
5018 return QualType();
5019 }
5020 QualType PointeeType = readType(*Loc.F, Record, Idx);
5021 return Context.getBlockPointerType(PointeeType);
5022 }
5023
5024 case TYPE_LVALUE_REFERENCE: {
5025 if (Record.size() != 2) {
5026 Error("Incorrect encoding of lvalue reference type");
5027 return QualType();
5028 }
5029 QualType PointeeType = readType(*Loc.F, Record, Idx);
5030 return Context.getLValueReferenceType(PointeeType, Record[1]);
5031 }
5032
5033 case TYPE_RVALUE_REFERENCE: {
5034 if (Record.size() != 1) {
5035 Error("Incorrect encoding of rvalue reference type");
5036 return QualType();
5037 }
5038 QualType PointeeType = readType(*Loc.F, Record, Idx);
5039 return Context.getRValueReferenceType(PointeeType);
5040 }
5041
5042 case TYPE_MEMBER_POINTER: {
5043 if (Record.size() != 2) {
5044 Error("Incorrect encoding of member pointer type");
5045 return QualType();
5046 }
5047 QualType PointeeType = readType(*Loc.F, Record, Idx);
5048 QualType ClassType = readType(*Loc.F, Record, Idx);
5049 if (PointeeType.isNull() || ClassType.isNull())
5050 return QualType();
5051
5052 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5053 }
5054
5055 case TYPE_CONSTANT_ARRAY: {
5056 QualType ElementType = readType(*Loc.F, Record, Idx);
5057 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5058 unsigned IndexTypeQuals = Record[2];
5059 unsigned Idx = 3;
5060 llvm::APInt Size = ReadAPInt(Record, Idx);
5061 return Context.getConstantArrayType(ElementType, Size,
5062 ASM, IndexTypeQuals);
5063 }
5064
5065 case TYPE_INCOMPLETE_ARRAY: {
5066 QualType ElementType = readType(*Loc.F, Record, Idx);
5067 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5068 unsigned IndexTypeQuals = Record[2];
5069 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5070 }
5071
5072 case TYPE_VARIABLE_ARRAY: {
5073 QualType ElementType = readType(*Loc.F, Record, Idx);
5074 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5075 unsigned IndexTypeQuals = Record[2];
5076 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5077 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5078 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5079 ASM, IndexTypeQuals,
5080 SourceRange(LBLoc, RBLoc));
5081 }
5082
5083 case TYPE_VECTOR: {
5084 if (Record.size() != 3) {
5085 Error("incorrect encoding of vector type in AST file");
5086 return QualType();
5087 }
5088
5089 QualType ElementType = readType(*Loc.F, Record, Idx);
5090 unsigned NumElements = Record[1];
5091 unsigned VecKind = Record[2];
5092 return Context.getVectorType(ElementType, NumElements,
5093 (VectorType::VectorKind)VecKind);
5094 }
5095
5096 case TYPE_EXT_VECTOR: {
5097 if (Record.size() != 3) {
5098 Error("incorrect encoding of extended vector type in AST file");
5099 return QualType();
5100 }
5101
5102 QualType ElementType = readType(*Loc.F, Record, Idx);
5103 unsigned NumElements = Record[1];
5104 return Context.getExtVectorType(ElementType, NumElements);
5105 }
5106
5107 case TYPE_FUNCTION_NO_PROTO: {
5108 if (Record.size() != 6) {
5109 Error("incorrect encoding of no-proto function type");
5110 return QualType();
5111 }
5112 QualType ResultType = readType(*Loc.F, Record, Idx);
5113 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5114 (CallingConv)Record[4], Record[5]);
5115 return Context.getFunctionNoProtoType(ResultType, Info);
5116 }
5117
5118 case TYPE_FUNCTION_PROTO: {
5119 QualType ResultType = readType(*Loc.F, Record, Idx);
5120
5121 FunctionProtoType::ExtProtoInfo EPI;
5122 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5123 /*hasregparm*/ Record[2],
5124 /*regparm*/ Record[3],
5125 static_cast<CallingConv>(Record[4]),
5126 /*produces*/ Record[5]);
5127
5128 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005129
5130 EPI.Variadic = Record[Idx++];
5131 EPI.HasTrailingReturn = Record[Idx++];
5132 EPI.TypeQuals = Record[Idx++];
5133 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005134 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005135 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005136
5137 unsigned NumParams = Record[Idx++];
5138 SmallVector<QualType, 16> ParamTypes;
5139 for (unsigned I = 0; I != NumParams; ++I)
5140 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5141
Jordan Rose5c382722013-03-08 21:51:21 +00005142 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005143 }
5144
5145 case TYPE_UNRESOLVED_USING: {
5146 unsigned Idx = 0;
5147 return Context.getTypeDeclType(
5148 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5149 }
5150
5151 case TYPE_TYPEDEF: {
5152 if (Record.size() != 2) {
5153 Error("incorrect encoding of typedef type");
5154 return QualType();
5155 }
5156 unsigned Idx = 0;
5157 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5158 QualType Canonical = readType(*Loc.F, Record, Idx);
5159 if (!Canonical.isNull())
5160 Canonical = Context.getCanonicalType(Canonical);
5161 return Context.getTypedefType(Decl, Canonical);
5162 }
5163
5164 case TYPE_TYPEOF_EXPR:
5165 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5166
5167 case TYPE_TYPEOF: {
5168 if (Record.size() != 1) {
5169 Error("incorrect encoding of typeof(type) in AST file");
5170 return QualType();
5171 }
5172 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5173 return Context.getTypeOfType(UnderlyingType);
5174 }
5175
5176 case TYPE_DECLTYPE: {
5177 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5178 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5179 }
5180
5181 case TYPE_UNARY_TRANSFORM: {
5182 QualType BaseType = readType(*Loc.F, Record, Idx);
5183 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5184 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5185 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5186 }
5187
Richard Smith74aeef52013-04-26 16:15:35 +00005188 case TYPE_AUTO: {
5189 QualType Deduced = readType(*Loc.F, Record, Idx);
5190 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005191 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005192 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005193 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005194
5195 case TYPE_RECORD: {
5196 if (Record.size() != 2) {
5197 Error("incorrect encoding of record type");
5198 return QualType();
5199 }
5200 unsigned Idx = 0;
5201 bool IsDependent = Record[Idx++];
5202 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5203 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5204 QualType T = Context.getRecordType(RD);
5205 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5206 return T;
5207 }
5208
5209 case TYPE_ENUM: {
5210 if (Record.size() != 2) {
5211 Error("incorrect encoding of enum type");
5212 return QualType();
5213 }
5214 unsigned Idx = 0;
5215 bool IsDependent = Record[Idx++];
5216 QualType T
5217 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5218 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5219 return T;
5220 }
5221
5222 case TYPE_ATTRIBUTED: {
5223 if (Record.size() != 3) {
5224 Error("incorrect encoding of attributed type");
5225 return QualType();
5226 }
5227 QualType modifiedType = readType(*Loc.F, Record, Idx);
5228 QualType equivalentType = readType(*Loc.F, Record, Idx);
5229 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5230 return Context.getAttributedType(kind, modifiedType, equivalentType);
5231 }
5232
5233 case TYPE_PAREN: {
5234 if (Record.size() != 1) {
5235 Error("incorrect encoding of paren type");
5236 return QualType();
5237 }
5238 QualType InnerType = readType(*Loc.F, Record, Idx);
5239 return Context.getParenType(InnerType);
5240 }
5241
5242 case TYPE_PACK_EXPANSION: {
5243 if (Record.size() != 2) {
5244 Error("incorrect encoding of pack expansion type");
5245 return QualType();
5246 }
5247 QualType Pattern = readType(*Loc.F, Record, Idx);
5248 if (Pattern.isNull())
5249 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005250 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005251 if (Record[1])
5252 NumExpansions = Record[1] - 1;
5253 return Context.getPackExpansionType(Pattern, NumExpansions);
5254 }
5255
5256 case TYPE_ELABORATED: {
5257 unsigned Idx = 0;
5258 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5259 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5260 QualType NamedType = readType(*Loc.F, Record, Idx);
5261 return Context.getElaboratedType(Keyword, NNS, NamedType);
5262 }
5263
5264 case TYPE_OBJC_INTERFACE: {
5265 unsigned Idx = 0;
5266 ObjCInterfaceDecl *ItfD
5267 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5268 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5269 }
5270
5271 case TYPE_OBJC_OBJECT: {
5272 unsigned Idx = 0;
5273 QualType Base = readType(*Loc.F, Record, Idx);
5274 unsigned NumProtos = Record[Idx++];
5275 SmallVector<ObjCProtocolDecl*, 4> Protos;
5276 for (unsigned I = 0; I != NumProtos; ++I)
5277 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5278 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5279 }
5280
5281 case TYPE_OBJC_OBJECT_POINTER: {
5282 unsigned Idx = 0;
5283 QualType Pointee = readType(*Loc.F, Record, Idx);
5284 return Context.getObjCObjectPointerType(Pointee);
5285 }
5286
5287 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5288 unsigned Idx = 0;
5289 QualType Parm = readType(*Loc.F, Record, Idx);
5290 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005291 return Context.getSubstTemplateTypeParmType(
5292 cast<TemplateTypeParmType>(Parm),
5293 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005294 }
5295
5296 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5297 unsigned Idx = 0;
5298 QualType Parm = readType(*Loc.F, Record, Idx);
5299 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5300 return Context.getSubstTemplateTypeParmPackType(
5301 cast<TemplateTypeParmType>(Parm),
5302 ArgPack);
5303 }
5304
5305 case TYPE_INJECTED_CLASS_NAME: {
5306 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5307 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5308 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5309 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005310 const Type *T = nullptr;
5311 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5312 if (const Type *Existing = DI->getTypeForDecl()) {
5313 T = Existing;
5314 break;
5315 }
5316 }
5317 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005318 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005319 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5320 DI->setTypeForDecl(T);
5321 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005322 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005323 }
5324
5325 case TYPE_TEMPLATE_TYPE_PARM: {
5326 unsigned Idx = 0;
5327 unsigned Depth = Record[Idx++];
5328 unsigned Index = Record[Idx++];
5329 bool Pack = Record[Idx++];
5330 TemplateTypeParmDecl *D
5331 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5332 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5333 }
5334
5335 case TYPE_DEPENDENT_NAME: {
5336 unsigned Idx = 0;
5337 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5338 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5339 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5340 QualType Canon = readType(*Loc.F, Record, Idx);
5341 if (!Canon.isNull())
5342 Canon = Context.getCanonicalType(Canon);
5343 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5344 }
5345
5346 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5347 unsigned Idx = 0;
5348 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5349 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5350 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5351 unsigned NumArgs = Record[Idx++];
5352 SmallVector<TemplateArgument, 8> Args;
5353 Args.reserve(NumArgs);
5354 while (NumArgs--)
5355 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5356 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5357 Args.size(), Args.data());
5358 }
5359
5360 case TYPE_DEPENDENT_SIZED_ARRAY: {
5361 unsigned Idx = 0;
5362
5363 // ArrayType
5364 QualType ElementType = readType(*Loc.F, Record, Idx);
5365 ArrayType::ArraySizeModifier ASM
5366 = (ArrayType::ArraySizeModifier)Record[Idx++];
5367 unsigned IndexTypeQuals = Record[Idx++];
5368
5369 // DependentSizedArrayType
5370 Expr *NumElts = ReadExpr(*Loc.F);
5371 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5372
5373 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5374 IndexTypeQuals, Brackets);
5375 }
5376
5377 case TYPE_TEMPLATE_SPECIALIZATION: {
5378 unsigned Idx = 0;
5379 bool IsDependent = Record[Idx++];
5380 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5381 SmallVector<TemplateArgument, 8> Args;
5382 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5383 QualType Underlying = readType(*Loc.F, Record, Idx);
5384 QualType T;
5385 if (Underlying.isNull())
5386 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5387 Args.size());
5388 else
5389 T = Context.getTemplateSpecializationType(Name, Args.data(),
5390 Args.size(), Underlying);
5391 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5392 return T;
5393 }
5394
5395 case TYPE_ATOMIC: {
5396 if (Record.size() != 1) {
5397 Error("Incorrect encoding of atomic type");
5398 return QualType();
5399 }
5400 QualType ValueType = readType(*Loc.F, Record, Idx);
5401 return Context.getAtomicType(ValueType);
5402 }
5403 }
5404 llvm_unreachable("Invalid TypeCode!");
5405}
5406
Richard Smith564417a2014-03-20 21:47:22 +00005407void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5408 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005409 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005410 const RecordData &Record, unsigned &Idx) {
5411 ExceptionSpecificationType EST =
5412 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005413 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005414 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005415 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005416 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005417 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005418 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005419 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005420 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005421 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5422 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005423 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005424 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005425 }
5426}
5427
Guy Benyei11169dd2012-12-18 14:30:41 +00005428class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5429 ASTReader &Reader;
5430 ModuleFile &F;
5431 const ASTReader::RecordData &Record;
5432 unsigned &Idx;
5433
5434 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5435 unsigned &I) {
5436 return Reader.ReadSourceLocation(F, R, I);
5437 }
5438
5439 template<typename T>
5440 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5441 return Reader.ReadDeclAs<T>(F, Record, Idx);
5442 }
5443
5444public:
5445 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5446 const ASTReader::RecordData &Record, unsigned &Idx)
5447 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5448 { }
5449
5450 // We want compile-time assurance that we've enumerated all of
5451 // these, so unfortunately we have to declare them first, then
5452 // define them out-of-line.
5453#define ABSTRACT_TYPELOC(CLASS, PARENT)
5454#define TYPELOC(CLASS, PARENT) \
5455 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5456#include "clang/AST/TypeLocNodes.def"
5457
5458 void VisitFunctionTypeLoc(FunctionTypeLoc);
5459 void VisitArrayTypeLoc(ArrayTypeLoc);
5460};
5461
5462void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5463 // nothing to do
5464}
5465void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5466 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5467 if (TL.needsExtraLocalData()) {
5468 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5469 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5470 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5471 TL.setModeAttr(Record[Idx++]);
5472 }
5473}
5474void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5475 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5476}
5477void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5478 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5479}
Reid Kleckner8a365022013-06-24 17:51:48 +00005480void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5481 // nothing to do
5482}
Reid Kleckner0503a872013-12-05 01:23:43 +00005483void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5484 // nothing to do
5485}
Guy Benyei11169dd2012-12-18 14:30:41 +00005486void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5487 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5488}
5489void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5490 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5491}
5492void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5493 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5494}
5495void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5496 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5497 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5498}
5499void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5500 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5501 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5502 if (Record[Idx++])
5503 TL.setSizeExpr(Reader.ReadExpr(F));
5504 else
Craig Toppera13603a2014-05-22 05:54:18 +00005505 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005506}
5507void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5508 VisitArrayTypeLoc(TL);
5509}
5510void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5511 VisitArrayTypeLoc(TL);
5512}
5513void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5514 VisitArrayTypeLoc(TL);
5515}
5516void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5517 DependentSizedArrayTypeLoc TL) {
5518 VisitArrayTypeLoc(TL);
5519}
5520void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5521 DependentSizedExtVectorTypeLoc TL) {
5522 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5523}
5524void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5525 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5526}
5527void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5528 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5529}
5530void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5531 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5532 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5533 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5534 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005535 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5536 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005537 }
5538}
5539void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5540 VisitFunctionTypeLoc(TL);
5541}
5542void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5543 VisitFunctionTypeLoc(TL);
5544}
5545void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5546 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5547}
5548void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5549 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5550}
5551void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5552 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5553 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5554 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5555}
5556void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5557 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5558 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5559 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5560 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5561}
5562void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5563 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5564}
5565void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5566 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5567 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5568 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5569 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5570}
5571void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5572 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5573}
5574void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5575 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5576}
5577void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5578 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5579}
5580void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5581 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5582 if (TL.hasAttrOperand()) {
5583 SourceRange range;
5584 range.setBegin(ReadSourceLocation(Record, Idx));
5585 range.setEnd(ReadSourceLocation(Record, Idx));
5586 TL.setAttrOperandParensRange(range);
5587 }
5588 if (TL.hasAttrExprOperand()) {
5589 if (Record[Idx++])
5590 TL.setAttrExprOperand(Reader.ReadExpr(F));
5591 else
Craig Toppera13603a2014-05-22 05:54:18 +00005592 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005593 } else if (TL.hasAttrEnumOperand())
5594 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5595}
5596void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5597 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5598}
5599void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5600 SubstTemplateTypeParmTypeLoc TL) {
5601 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5602}
5603void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5604 SubstTemplateTypeParmPackTypeLoc TL) {
5605 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5606}
5607void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5608 TemplateSpecializationTypeLoc TL) {
5609 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5610 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5611 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5612 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5613 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5614 TL.setArgLocInfo(i,
5615 Reader.GetTemplateArgumentLocInfo(F,
5616 TL.getTypePtr()->getArg(i).getKind(),
5617 Record, Idx));
5618}
5619void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5620 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5621 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5622}
5623void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5624 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5625 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5626}
5627void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5628 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5629}
5630void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5631 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5632 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5633 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5634}
5635void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5636 DependentTemplateSpecializationTypeLoc TL) {
5637 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5638 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5639 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5640 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5641 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5642 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5643 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5644 TL.setArgLocInfo(I,
5645 Reader.GetTemplateArgumentLocInfo(F,
5646 TL.getTypePtr()->getArg(I).getKind(),
5647 Record, Idx));
5648}
5649void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5650 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5651}
5652void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5653 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5654}
5655void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5656 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5657 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5658 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5659 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5660 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5661}
5662void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5663 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5664}
5665void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5666 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5667 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5668 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5669}
5670
5671TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5672 const RecordData &Record,
5673 unsigned &Idx) {
5674 QualType InfoTy = readType(F, Record, Idx);
5675 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005676 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005677
5678 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5679 TypeLocReader TLR(*this, F, Record, Idx);
5680 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5681 TLR.Visit(TL);
5682 return TInfo;
5683}
5684
5685QualType ASTReader::GetType(TypeID ID) {
5686 unsigned FastQuals = ID & Qualifiers::FastMask;
5687 unsigned Index = ID >> Qualifiers::FastWidth;
5688
5689 if (Index < NUM_PREDEF_TYPE_IDS) {
5690 QualType T;
5691 switch ((PredefinedTypeIDs)Index) {
5692 case PREDEF_TYPE_NULL_ID: return QualType();
5693 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5694 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5695
5696 case PREDEF_TYPE_CHAR_U_ID:
5697 case PREDEF_TYPE_CHAR_S_ID:
5698 // FIXME: Check that the signedness of CharTy is correct!
5699 T = Context.CharTy;
5700 break;
5701
5702 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5703 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5704 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5705 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5706 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5707 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5708 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5709 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5710 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5711 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5712 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5713 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5714 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5715 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5716 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5717 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5718 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5719 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5720 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5721 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5722 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5723 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5724 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5725 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5726 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5727 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5728 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5729 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005730 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5731 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5732 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5733 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5734 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5735 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005736 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005737 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005738 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5739
5740 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5741 T = Context.getAutoRRefDeductType();
5742 break;
5743
5744 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5745 T = Context.ARCUnbridgedCastTy;
5746 break;
5747
5748 case PREDEF_TYPE_VA_LIST_TAG:
5749 T = Context.getVaListTagType();
5750 break;
5751
5752 case PREDEF_TYPE_BUILTIN_FN:
5753 T = Context.BuiltinFnTy;
5754 break;
5755 }
5756
5757 assert(!T.isNull() && "Unknown predefined type");
5758 return T.withFastQualifiers(FastQuals);
5759 }
5760
5761 Index -= NUM_PREDEF_TYPE_IDS;
5762 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5763 if (TypesLoaded[Index].isNull()) {
5764 TypesLoaded[Index] = readTypeRecord(Index);
5765 if (TypesLoaded[Index].isNull())
5766 return QualType();
5767
5768 TypesLoaded[Index]->setFromAST();
5769 if (DeserializationListener)
5770 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5771 TypesLoaded[Index]);
5772 }
5773
5774 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5775}
5776
5777QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5778 return GetType(getGlobalTypeID(F, LocalID));
5779}
5780
5781serialization::TypeID
5782ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5783 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5784 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5785
5786 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5787 return LocalID;
5788
5789 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5790 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5791 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5792
5793 unsigned GlobalIndex = LocalIndex + I->second;
5794 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5795}
5796
5797TemplateArgumentLocInfo
5798ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5799 TemplateArgument::ArgKind Kind,
5800 const RecordData &Record,
5801 unsigned &Index) {
5802 switch (Kind) {
5803 case TemplateArgument::Expression:
5804 return ReadExpr(F);
5805 case TemplateArgument::Type:
5806 return GetTypeSourceInfo(F, Record, Index);
5807 case TemplateArgument::Template: {
5808 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5809 Index);
5810 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5811 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5812 SourceLocation());
5813 }
5814 case TemplateArgument::TemplateExpansion: {
5815 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5816 Index);
5817 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5818 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5819 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5820 EllipsisLoc);
5821 }
5822 case TemplateArgument::Null:
5823 case TemplateArgument::Integral:
5824 case TemplateArgument::Declaration:
5825 case TemplateArgument::NullPtr:
5826 case TemplateArgument::Pack:
5827 // FIXME: Is this right?
5828 return TemplateArgumentLocInfo();
5829 }
5830 llvm_unreachable("unexpected template argument loc");
5831}
5832
5833TemplateArgumentLoc
5834ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5835 const RecordData &Record, unsigned &Index) {
5836 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5837
5838 if (Arg.getKind() == TemplateArgument::Expression) {
5839 if (Record[Index++]) // bool InfoHasSameExpr.
5840 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5841 }
5842 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5843 Record, Index));
5844}
5845
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005846const ASTTemplateArgumentListInfo*
5847ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5848 const RecordData &Record,
5849 unsigned &Index) {
5850 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5851 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5852 unsigned NumArgsAsWritten = Record[Index++];
5853 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5854 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5855 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5856 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5857}
5858
Guy Benyei11169dd2012-12-18 14:30:41 +00005859Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5860 return GetDecl(ID);
5861}
5862
Richard Smith50895422015-01-31 03:04:55 +00005863template<typename TemplateSpecializationDecl>
5864static void completeRedeclChainForTemplateSpecialization(Decl *D) {
5865 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
5866 TSD->getSpecializedTemplate()->LoadLazySpecializations();
5867}
5868
Richard Smith053f6c62014-05-16 23:01:30 +00005869void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005870 if (NumCurrentElementsDeserializing) {
5871 // We arrange to not care about the complete redeclaration chain while we're
5872 // deserializing. Just remember that the AST has marked this one as complete
5873 // but that it's not actually complete yet, so we know we still need to
5874 // complete it later.
5875 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5876 return;
5877 }
5878
Richard Smith053f6c62014-05-16 23:01:30 +00005879 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5880
Richard Smith053f6c62014-05-16 23:01:30 +00005881 // If this is a named declaration, complete it by looking it up
5882 // within its context.
5883 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00005884 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00005885 // all mergeable entities within it.
5886 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5887 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5888 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
5889 auto *II = Name.getAsIdentifierInfo();
5890 if (isa<TranslationUnitDecl>(DC) && II) {
5891 // Outside of C++, we don't have a lookup table for the TU, so update
5892 // the identifier instead. In C++, either way should work fine.
5893 if (II->isOutOfDate())
5894 updateOutOfDateIdentifier(*II);
5895 } else
5896 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00005897 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
5898 // FIXME: It'd be nice to do something a bit more targeted here.
5899 D->getDeclContext()->decls_begin();
Richard Smith053f6c62014-05-16 23:01:30 +00005900 }
5901 }
Richard Smith50895422015-01-31 03:04:55 +00005902
5903 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
5904 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
5905 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
5906 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
5907 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5908 if (auto *Template = FD->getPrimaryTemplate())
5909 Template->LoadLazySpecializations();
5910 }
Richard Smith053f6c62014-05-16 23:01:30 +00005911}
5912
Richard Smithc2bb8182015-03-24 06:36:48 +00005913uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
5914 const RecordData &Record,
5915 unsigned &Idx) {
5916 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
5917 Error("malformed AST file: missing C++ ctor initializers");
5918 return 0;
5919 }
5920
5921 unsigned LocalID = Record[Idx++];
5922 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
5923}
5924
5925CXXCtorInitializer **
5926ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
5927 RecordLocation Loc = getLocalBitOffset(Offset);
5928 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
5929 SavedStreamPosition SavedPosition(Cursor);
5930 Cursor.JumpToBit(Loc.Offset);
5931 ReadingKindTracker ReadingKind(Read_Decl, *this);
5932
5933 RecordData Record;
5934 unsigned Code = Cursor.ReadCode();
5935 unsigned RecCode = Cursor.readRecord(Code, Record);
5936 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
5937 Error("malformed AST file: missing C++ ctor initializers");
5938 return nullptr;
5939 }
5940
5941 unsigned Idx = 0;
5942 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
5943}
5944
Richard Smithcd45dbc2014-04-19 03:48:30 +00005945uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
5946 const RecordData &Record,
5947 unsigned &Idx) {
5948 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
5949 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005950 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00005951 }
5952
Guy Benyei11169dd2012-12-18 14:30:41 +00005953 unsigned LocalID = Record[Idx++];
5954 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5955}
5956
5957CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5958 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005959 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005960 SavedStreamPosition SavedPosition(Cursor);
5961 Cursor.JumpToBit(Loc.Offset);
5962 ReadingKindTracker ReadingKind(Read_Decl, *this);
5963 RecordData Record;
5964 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005965 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00005966 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005967 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00005968 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005969 }
5970
5971 unsigned Idx = 0;
5972 unsigned NumBases = Record[Idx++];
5973 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5974 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5975 for (unsigned I = 0; I != NumBases; ++I)
5976 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5977 return Bases;
5978}
5979
5980serialization::DeclID
5981ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5982 if (LocalID < NUM_PREDEF_DECL_IDS)
5983 return LocalID;
5984
5985 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5986 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5987 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5988
5989 return LocalID + I->second;
5990}
5991
5992bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5993 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00005994 // Predefined decls aren't from any module.
5995 if (ID < NUM_PREDEF_DECL_IDS)
5996 return false;
5997
Guy Benyei11169dd2012-12-18 14:30:41 +00005998 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5999 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6000 return &M == I->second;
6001}
6002
Douglas Gregor9f782892013-01-21 15:25:38 +00006003ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006004 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006005 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006006 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6007 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6008 return I->second;
6009}
6010
6011SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6012 if (ID < NUM_PREDEF_DECL_IDS)
6013 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006014
Guy Benyei11169dd2012-12-18 14:30:41 +00006015 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6016
6017 if (Index > DeclsLoaded.size()) {
6018 Error("declaration ID out-of-range for AST file");
6019 return SourceLocation();
6020 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006021
Guy Benyei11169dd2012-12-18 14:30:41 +00006022 if (Decl *D = DeclsLoaded[Index])
6023 return D->getLocation();
6024
6025 unsigned RawLocation = 0;
6026 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6027 return ReadSourceLocation(*Rec.F, RawLocation);
6028}
6029
Richard Smithfe620d22015-03-05 23:24:12 +00006030static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6031 switch (ID) {
6032 case PREDEF_DECL_NULL_ID:
6033 return nullptr;
6034
6035 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6036 return Context.getTranslationUnitDecl();
6037
6038 case PREDEF_DECL_OBJC_ID_ID:
6039 return Context.getObjCIdDecl();
6040
6041 case PREDEF_DECL_OBJC_SEL_ID:
6042 return Context.getObjCSelDecl();
6043
6044 case PREDEF_DECL_OBJC_CLASS_ID:
6045 return Context.getObjCClassDecl();
6046
6047 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6048 return Context.getObjCProtocolDecl();
6049
6050 case PREDEF_DECL_INT_128_ID:
6051 return Context.getInt128Decl();
6052
6053 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6054 return Context.getUInt128Decl();
6055
6056 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6057 return Context.getObjCInstanceTypeDecl();
6058
6059 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6060 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006061
6062 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6063 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006064 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006065 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006066}
6067
Richard Smithcd45dbc2014-04-19 03:48:30 +00006068Decl *ASTReader::GetExistingDecl(DeclID ID) {
6069 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006070 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6071 if (D) {
6072 // Track that we have merged the declaration with ID \p ID into the
6073 // pre-existing predefined declaration \p D.
6074 auto &Merged = MergedDecls[D->getCanonicalDecl()];
6075 if (Merged.empty())
6076 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006077 }
Richard Smithfe620d22015-03-05 23:24:12 +00006078 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006079 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006080
Guy Benyei11169dd2012-12-18 14:30:41 +00006081 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6082
6083 if (Index >= DeclsLoaded.size()) {
6084 assert(0 && "declaration ID out-of-range for AST file");
6085 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006086 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006087 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006088
6089 return DeclsLoaded[Index];
6090}
6091
6092Decl *ASTReader::GetDecl(DeclID ID) {
6093 if (ID < NUM_PREDEF_DECL_IDS)
6094 return GetExistingDecl(ID);
6095
6096 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6097
6098 if (Index >= DeclsLoaded.size()) {
6099 assert(0 && "declaration ID out-of-range for AST file");
6100 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006101 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006102 }
6103
Guy Benyei11169dd2012-12-18 14:30:41 +00006104 if (!DeclsLoaded[Index]) {
6105 ReadDeclRecord(ID);
6106 if (DeserializationListener)
6107 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6108 }
6109
6110 return DeclsLoaded[Index];
6111}
6112
6113DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6114 DeclID GlobalID) {
6115 if (GlobalID < NUM_PREDEF_DECL_IDS)
6116 return GlobalID;
6117
6118 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6119 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6120 ModuleFile *Owner = I->second;
6121
6122 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6123 = M.GlobalToLocalDeclIDs.find(Owner);
6124 if (Pos == M.GlobalToLocalDeclIDs.end())
6125 return 0;
6126
6127 return GlobalID - Owner->BaseDeclID + Pos->second;
6128}
6129
6130serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6131 const RecordData &Record,
6132 unsigned &Idx) {
6133 if (Idx >= Record.size()) {
6134 Error("Corrupted AST file");
6135 return 0;
6136 }
6137
6138 return getGlobalDeclID(F, Record[Idx++]);
6139}
6140
6141/// \brief Resolve the offset of a statement into a statement.
6142///
6143/// This operation will read a new statement from the external
6144/// source each time it is called, and is meant to be used via a
6145/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6146Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6147 // Switch case IDs are per Decl.
6148 ClearSwitchCaseIDs();
6149
6150 // Offset here is a global offset across the entire chain.
6151 RecordLocation Loc = getLocalBitOffset(Offset);
6152 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6153 return ReadStmtFromStream(*Loc.F);
6154}
6155
6156namespace {
6157 class FindExternalLexicalDeclsVisitor {
6158 ASTReader &Reader;
6159 const DeclContext *DC;
6160 bool (*isKindWeWant)(Decl::Kind);
6161
6162 SmallVectorImpl<Decl*> &Decls;
6163 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6164
6165 public:
6166 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6167 bool (*isKindWeWant)(Decl::Kind),
6168 SmallVectorImpl<Decl*> &Decls)
6169 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6170 {
6171 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6172 PredefsVisited[I] = false;
6173 }
6174
6175 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6176 if (Preorder)
6177 return false;
6178
6179 FindExternalLexicalDeclsVisitor *This
6180 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6181
6182 ModuleFile::DeclContextInfosMap::iterator Info
6183 = M.DeclContextInfos.find(This->DC);
6184 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6185 return false;
6186
6187 // Load all of the declaration IDs
6188 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6189 *IDE = ID + Info->second.NumLexicalDecls;
6190 ID != IDE; ++ID) {
6191 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6192 continue;
6193
6194 // Don't add predefined declarations to the lexical context more
6195 // than once.
6196 if (ID->second < NUM_PREDEF_DECL_IDS) {
6197 if (This->PredefsVisited[ID->second])
6198 continue;
6199
6200 This->PredefsVisited[ID->second] = true;
6201 }
6202
6203 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6204 if (!This->DC->isDeclInLexicalTraversal(D))
6205 This->Decls.push_back(D);
6206 }
6207 }
6208
6209 return false;
6210 }
6211 };
6212}
6213
6214ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6215 bool (*isKindWeWant)(Decl::Kind),
6216 SmallVectorImpl<Decl*> &Decls) {
6217 // There might be lexical decls in multiple modules, for the TU at
6218 // least. Walk all of the modules in the order they were loaded.
6219 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6220 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6221 ++NumLexicalDeclContextsRead;
6222 return ELR_Success;
6223}
6224
6225namespace {
6226
6227class DeclIDComp {
6228 ASTReader &Reader;
6229 ModuleFile &Mod;
6230
6231public:
6232 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6233
6234 bool operator()(LocalDeclID L, LocalDeclID R) const {
6235 SourceLocation LHS = getLocation(L);
6236 SourceLocation RHS = getLocation(R);
6237 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6238 }
6239
6240 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6241 SourceLocation RHS = getLocation(R);
6242 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6243 }
6244
6245 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6246 SourceLocation LHS = getLocation(L);
6247 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6248 }
6249
6250 SourceLocation getLocation(LocalDeclID ID) const {
6251 return Reader.getSourceManager().getFileLoc(
6252 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6253 }
6254};
6255
6256}
6257
6258void ASTReader::FindFileRegionDecls(FileID File,
6259 unsigned Offset, unsigned Length,
6260 SmallVectorImpl<Decl *> &Decls) {
6261 SourceManager &SM = getSourceManager();
6262
6263 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6264 if (I == FileDeclIDs.end())
6265 return;
6266
6267 FileDeclsInfo &DInfo = I->second;
6268 if (DInfo.Decls.empty())
6269 return;
6270
6271 SourceLocation
6272 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6273 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6274
6275 DeclIDComp DIDComp(*this, *DInfo.Mod);
6276 ArrayRef<serialization::LocalDeclID>::iterator
6277 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6278 BeginLoc, DIDComp);
6279 if (BeginIt != DInfo.Decls.begin())
6280 --BeginIt;
6281
6282 // If we are pointing at a top-level decl inside an objc container, we need
6283 // to backtrack until we find it otherwise we will fail to report that the
6284 // region overlaps with an objc container.
6285 while (BeginIt != DInfo.Decls.begin() &&
6286 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6287 ->isTopLevelDeclInObjCContainer())
6288 --BeginIt;
6289
6290 ArrayRef<serialization::LocalDeclID>::iterator
6291 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6292 EndLoc, DIDComp);
6293 if (EndIt != DInfo.Decls.end())
6294 ++EndIt;
6295
6296 for (ArrayRef<serialization::LocalDeclID>::iterator
6297 DIt = BeginIt; DIt != EndIt; ++DIt)
6298 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6299}
6300
6301namespace {
6302 /// \brief ModuleFile visitor used to perform name lookup into a
6303 /// declaration context.
6304 class DeclContextNameLookupVisitor {
6305 ASTReader &Reader;
Richard Smith8c913ec2014-08-14 02:21:01 +00006306 ArrayRef<const DeclContext *> Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006307 DeclarationName Name;
6308 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006309 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006310
6311 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006312 DeclContextNameLookupVisitor(ASTReader &Reader,
6313 ArrayRef<const DeclContext *> Contexts,
Guy Benyei11169dd2012-12-18 14:30:41 +00006314 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006315 SmallVectorImpl<NamedDecl *> &Decls,
6316 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
6317 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls),
6318 DeclSet(DeclSet) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006319
6320 static bool visit(ModuleFile &M, void *UserData) {
6321 DeclContextNameLookupVisitor *This
6322 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6323
6324 // Check whether we have any visible declaration information for
6325 // this context in this module.
6326 ModuleFile::DeclContextInfosMap::iterator Info;
6327 bool FoundInfo = false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006328 for (auto *DC : This->Contexts) {
6329 Info = M.DeclContextInfos.find(DC);
6330 if (Info != M.DeclContextInfos.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006331 Info->second.NameLookupTableData) {
6332 FoundInfo = true;
6333 break;
6334 }
6335 }
6336
6337 if (!FoundInfo)
6338 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006339
Guy Benyei11169dd2012-12-18 14:30:41 +00006340 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006341 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006342 Info->second.NameLookupTableData;
6343 ASTDeclContextNameLookupTable::iterator Pos
6344 = LookupTable->find(This->Name);
6345 if (Pos == LookupTable->end())
6346 return false;
6347
6348 bool FoundAnything = false;
6349 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6350 for (; Data.first != Data.second; ++Data.first) {
6351 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6352 if (!ND)
6353 continue;
6354
6355 if (ND->getDeclName() != This->Name) {
6356 // A name might be null because the decl's redeclarable part is
6357 // currently read before reading its name. The lookup is triggered by
6358 // building that decl (likely indirectly), and so it is later in the
6359 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006360 // FIXME: This should not happen; deserializing declarations should
6361 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006362 continue;
6363 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006364
Guy Benyei11169dd2012-12-18 14:30:41 +00006365 // Record this declaration.
6366 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006367 if (This->DeclSet.insert(ND).second)
6368 This->Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006369 }
6370
6371 return FoundAnything;
6372 }
6373 };
6374}
6375
Douglas Gregor9f782892013-01-21 15:25:38 +00006376/// \brief Retrieve the "definitive" module file for the definition of the
6377/// given declaration context, if there is one.
6378///
6379/// The "definitive" module file is the only place where we need to look to
6380/// find information about the declarations within the given declaration
6381/// context. For example, C++ and Objective-C classes, C structs/unions, and
6382/// Objective-C protocols, categories, and extensions are all defined in a
6383/// single place in the source code, so they have definitive module files
6384/// associated with them. C++ namespaces, on the other hand, can have
6385/// definitions in multiple different module files.
6386///
6387/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6388/// NDEBUG checking.
6389static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6390 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006391 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6392 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006393
Craig Toppera13603a2014-05-22 05:54:18 +00006394 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006395}
6396
Richard Smith9ce12e32013-02-07 03:30:24 +00006397bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006398ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6399 DeclarationName Name) {
6400 assert(DC->hasExternalVisibleStorage() &&
6401 "DeclContext has no visible decls in storage");
6402 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006403 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006404
Richard Smith8c913ec2014-08-14 02:21:01 +00006405 Deserializing LookupResults(this);
6406
Guy Benyei11169dd2012-12-18 14:30:41 +00006407 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006408 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006409
Guy Benyei11169dd2012-12-18 14:30:41 +00006410 // Compute the declaration contexts we need to look into. Multiple such
6411 // declaration contexts occur when two declaration contexts from disjoint
6412 // modules get merged, e.g., when two namespaces with the same name are
6413 // independently defined in separate modules.
6414 SmallVector<const DeclContext *, 2> Contexts;
6415 Contexts.push_back(DC);
Richard Smith8c913ec2014-08-14 02:21:01 +00006416
Guy Benyei11169dd2012-12-18 14:30:41 +00006417 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006418 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006419 if (Merged != MergedDecls.end()) {
6420 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6421 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6422 }
6423 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006424
6425 auto LookUpInContexts = [&](ArrayRef<const DeclContext*> Contexts) {
Richard Smith52874ec2015-02-13 20:17:14 +00006426 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls, DeclSet);
Richard Smith8c913ec2014-08-14 02:21:01 +00006427
6428 // If we can definitively determine which module file to look into,
6429 // only look there. Otherwise, look in all module files.
6430 ModuleFile *Definitive;
6431 if (Contexts.size() == 1 &&
6432 (Definitive = getDefinitiveModuleFileFor(Contexts[0], *this))) {
6433 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6434 } else {
6435 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6436 }
6437 };
6438
6439 LookUpInContexts(Contexts);
6440
6441 // If this might be an implicit special member function, then also search
6442 // all merged definitions of the surrounding class. We need to search them
6443 // individually, because finding an entity in one of them doesn't imply that
6444 // we can't find a different entity in another one.
Richard Smithcd45dbc2014-04-19 03:48:30 +00006445 if (isa<CXXRecordDecl>(DC)) {
Richard Smith02793752015-03-27 21:16:39 +00006446 auto Merged = MergedLookups.find(DC);
6447 if (Merged != MergedLookups.end()) {
6448 for (unsigned I = 0; I != Merged->second.size(); ++I) {
6449 const DeclContext *Context = Merged->second[I];
6450 LookUpInContexts(Context);
6451 // We might have just added some more merged lookups. If so, our
6452 // iterator is now invalid, so grab a fresh one before continuing.
6453 Merged = MergedLookups.find(DC);
Richard Smithe0612472014-11-21 05:16:13 +00006454 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006455 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006456 }
6457
Guy Benyei11169dd2012-12-18 14:30:41 +00006458 ++NumVisibleDeclContextsRead;
6459 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006460 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006461}
6462
6463namespace {
6464 /// \brief ModuleFile visitor used to retrieve all visible names in a
6465 /// declaration context.
6466 class DeclContextAllNamesVisitor {
6467 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006468 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006469 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006470 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006471 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006472
6473 public:
6474 DeclContextAllNamesVisitor(ASTReader &Reader,
6475 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006476 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006477 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006478
6479 static bool visit(ModuleFile &M, void *UserData) {
6480 DeclContextAllNamesVisitor *This
6481 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6482
6483 // Check whether we have any visible declaration information for
6484 // this context in this module.
6485 ModuleFile::DeclContextInfosMap::iterator Info;
6486 bool FoundInfo = false;
6487 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6488 Info = M.DeclContextInfos.find(This->Contexts[I]);
6489 if (Info != M.DeclContextInfos.end() &&
6490 Info->second.NameLookupTableData) {
6491 FoundInfo = true;
6492 break;
6493 }
6494 }
6495
6496 if (!FoundInfo)
6497 return false;
6498
Richard Smith52e3fba2014-03-11 07:17:35 +00006499 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006500 Info->second.NameLookupTableData;
6501 bool FoundAnything = false;
6502 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006503 I = LookupTable->data_begin(), E = LookupTable->data_end();
6504 I != E;
6505 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006506 ASTDeclContextNameLookupTrait::data_type Data = *I;
6507 for (; Data.first != Data.second; ++Data.first) {
6508 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6509 *Data.first);
6510 if (!ND)
6511 continue;
6512
6513 // Record this declaration.
6514 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006515 if (This->DeclSet.insert(ND).second)
6516 This->Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006517 }
6518 }
6519
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006520 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006521 }
6522 };
6523}
6524
6525void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6526 if (!DC->hasExternalVisibleStorage())
6527 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006528 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006529
6530 // Compute the declaration contexts we need to look into. Multiple such
6531 // declaration contexts occur when two declaration contexts from disjoint
6532 // modules get merged, e.g., when two namespaces with the same name are
6533 // independently defined in separate modules.
6534 SmallVector<const DeclContext *, 2> Contexts;
6535 Contexts.push_back(DC);
6536
6537 if (DC->isNamespace()) {
6538 MergedDeclsMap::iterator Merged
6539 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6540 if (Merged != MergedDecls.end()) {
6541 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6542 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6543 }
6544 }
6545
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006546 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6547 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006548 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6549 ++NumVisibleDeclContextsRead;
6550
Craig Topper79be4cd2013-07-05 04:33:53 +00006551 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006552 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6553 }
6554 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6555}
6556
6557/// \brief Under non-PCH compilation the consumer receives the objc methods
6558/// before receiving the implementation, and codegen depends on this.
6559/// We simulate this by deserializing and passing to consumer the methods of the
6560/// implementation before passing the deserialized implementation decl.
6561static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6562 ASTConsumer *Consumer) {
6563 assert(ImplD && Consumer);
6564
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006565 for (auto *I : ImplD->methods())
6566 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006567
6568 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6569}
6570
6571void ASTReader::PassInterestingDeclsToConsumer() {
6572 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006573
6574 if (PassingDeclsToConsumer)
6575 return;
6576
6577 // Guard variable to avoid recursively redoing the process of passing
6578 // decls to consumer.
6579 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6580 true);
6581
Richard Smith9e2341d2015-03-23 03:25:59 +00006582 // Ensure that we've loaded all potentially-interesting declarations
6583 // that need to be eagerly loaded.
6584 for (auto ID : EagerlyDeserializedDecls)
6585 GetDecl(ID);
6586 EagerlyDeserializedDecls.clear();
6587
Guy Benyei11169dd2012-12-18 14:30:41 +00006588 while (!InterestingDecls.empty()) {
6589 Decl *D = InterestingDecls.front();
6590 InterestingDecls.pop_front();
6591
6592 PassInterestingDeclToConsumer(D);
6593 }
6594}
6595
6596void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6597 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6598 PassObjCImplDeclToConsumer(ImplD, Consumer);
6599 else
6600 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6601}
6602
6603void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6604 this->Consumer = Consumer;
6605
Richard Smith9e2341d2015-03-23 03:25:59 +00006606 if (Consumer)
6607 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006608
6609 if (DeserializationListener)
6610 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006611}
6612
6613void ASTReader::PrintStats() {
6614 std::fprintf(stderr, "*** AST File Statistics:\n");
6615
6616 unsigned NumTypesLoaded
6617 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6618 QualType());
6619 unsigned NumDeclsLoaded
6620 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006621 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006622 unsigned NumIdentifiersLoaded
6623 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6624 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006625 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006626 unsigned NumMacrosLoaded
6627 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6628 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006629 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006630 unsigned NumSelectorsLoaded
6631 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6632 SelectorsLoaded.end(),
6633 Selector());
6634
6635 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6636 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6637 NumSLocEntriesRead, TotalNumSLocEntries,
6638 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6639 if (!TypesLoaded.empty())
6640 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6641 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6642 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6643 if (!DeclsLoaded.empty())
6644 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6645 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6646 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6647 if (!IdentifiersLoaded.empty())
6648 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6649 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6650 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6651 if (!MacrosLoaded.empty())
6652 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6653 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6654 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6655 if (!SelectorsLoaded.empty())
6656 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6657 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6658 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6659 if (TotalNumStatements)
6660 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6661 NumStatementsRead, TotalNumStatements,
6662 ((float)NumStatementsRead/TotalNumStatements * 100));
6663 if (TotalNumMacros)
6664 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6665 NumMacrosRead, TotalNumMacros,
6666 ((float)NumMacrosRead/TotalNumMacros * 100));
6667 if (TotalLexicalDeclContexts)
6668 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6669 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6670 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6671 * 100));
6672 if (TotalVisibleDeclContexts)
6673 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6674 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6675 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6676 * 100));
6677 if (TotalNumMethodPoolEntries) {
6678 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6679 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6680 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6681 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006682 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006683 if (NumMethodPoolLookups) {
6684 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6685 NumMethodPoolHits, NumMethodPoolLookups,
6686 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6687 }
6688 if (NumMethodPoolTableLookups) {
6689 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6690 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6691 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6692 * 100.0));
6693 }
6694
Douglas Gregor00a50f72013-01-25 00:38:33 +00006695 if (NumIdentifierLookupHits) {
6696 std::fprintf(stderr,
6697 " %u / %u identifier table lookups succeeded (%f%%)\n",
6698 NumIdentifierLookupHits, NumIdentifierLookups,
6699 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6700 }
6701
Douglas Gregore060e572013-01-25 01:03:03 +00006702 if (GlobalIndex) {
6703 std::fprintf(stderr, "\n");
6704 GlobalIndex->printStats();
6705 }
6706
Guy Benyei11169dd2012-12-18 14:30:41 +00006707 std::fprintf(stderr, "\n");
6708 dump();
6709 std::fprintf(stderr, "\n");
6710}
6711
6712template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6713static void
6714dumpModuleIDMap(StringRef Name,
6715 const ContinuousRangeMap<Key, ModuleFile *,
6716 InitialCapacity> &Map) {
6717 if (Map.begin() == Map.end())
6718 return;
6719
6720 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6721 llvm::errs() << Name << ":\n";
6722 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6723 I != IEnd; ++I) {
6724 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6725 << "\n";
6726 }
6727}
6728
6729void ASTReader::dump() {
6730 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6731 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6732 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6733 dumpModuleIDMap("Global type map", GlobalTypeMap);
6734 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6735 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6736 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6737 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6738 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6739 dumpModuleIDMap("Global preprocessed entity map",
6740 GlobalPreprocessedEntityMap);
6741
6742 llvm::errs() << "\n*** PCH/Modules Loaded:";
6743 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6744 MEnd = ModuleMgr.end();
6745 M != MEnd; ++M)
6746 (*M)->dump();
6747}
6748
6749/// Return the amount of memory used by memory buffers, breaking down
6750/// by heap-backed versus mmap'ed memory.
6751void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6752 for (ModuleConstIterator I = ModuleMgr.begin(),
6753 E = ModuleMgr.end(); I != E; ++I) {
6754 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6755 size_t bytes = buf->getBufferSize();
6756 switch (buf->getBufferKind()) {
6757 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6758 sizes.malloc_bytes += bytes;
6759 break;
6760 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6761 sizes.mmap_bytes += bytes;
6762 break;
6763 }
6764 }
6765 }
6766}
6767
6768void ASTReader::InitializeSema(Sema &S) {
6769 SemaObj = &S;
6770 S.addExternalSource(this);
6771
6772 // Makes sure any declarations that were deserialized "too early"
6773 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006774 for (uint64_t ID : PreloadedDeclIDs) {
6775 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6776 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006777 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006778 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006779
Richard Smith3d8e97e2013-10-18 06:54:39 +00006780 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006781 if (!FPPragmaOptions.empty()) {
6782 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6783 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6784 }
6785
Richard Smith3d8e97e2013-10-18 06:54:39 +00006786 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006787 if (!OpenCLExtensions.empty()) {
6788 unsigned I = 0;
6789#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6790#include "clang/Basic/OpenCLExtensions.def"
6791
6792 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6793 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006794
6795 UpdateSema();
6796}
6797
6798void ASTReader::UpdateSema() {
6799 assert(SemaObj && "no Sema to update");
6800
6801 // Load the offsets of the declarations that Sema references.
6802 // They will be lazily deserialized when needed.
6803 if (!SemaDeclRefs.empty()) {
6804 assert(SemaDeclRefs.size() % 2 == 0);
6805 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6806 if (!SemaObj->StdNamespace)
6807 SemaObj->StdNamespace = SemaDeclRefs[I];
6808 if (!SemaObj->StdBadAlloc)
6809 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6810 }
6811 SemaDeclRefs.clear();
6812 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006813
6814 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6815 // encountered the pragma in the source.
6816 if(OptimizeOffPragmaLocation.isValid())
6817 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006818}
6819
6820IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6821 // Note that we are loading an identifier.
6822 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006823 StringRef Name(NameStart, NameEnd - NameStart);
6824
6825 // If there is a global index, look there first to determine which modules
6826 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006827 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00006828 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00006829 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006830 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6831 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006832 }
6833 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006834 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006835 NumIdentifierLookups,
6836 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006837 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006838 IdentifierInfo *II = Visitor.getIdentifierInfo();
6839 markIdentifierUpToDate(II);
6840 return II;
6841}
6842
6843namespace clang {
6844 /// \brief An identifier-lookup iterator that enumerates all of the
6845 /// identifiers stored within a set of AST files.
6846 class ASTIdentifierIterator : public IdentifierIterator {
6847 /// \brief The AST reader whose identifiers are being enumerated.
6848 const ASTReader &Reader;
6849
6850 /// \brief The current index into the chain of AST files stored in
6851 /// the AST reader.
6852 unsigned Index;
6853
6854 /// \brief The current position within the identifier lookup table
6855 /// of the current AST file.
6856 ASTIdentifierLookupTable::key_iterator Current;
6857
6858 /// \brief The end position within the identifier lookup table of
6859 /// the current AST file.
6860 ASTIdentifierLookupTable::key_iterator End;
6861
6862 public:
6863 explicit ASTIdentifierIterator(const ASTReader &Reader);
6864
Craig Topper3e89dfe2014-03-13 02:13:41 +00006865 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006866 };
6867}
6868
6869ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6870 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6871 ASTIdentifierLookupTable *IdTable
6872 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6873 Current = IdTable->key_begin();
6874 End = IdTable->key_end();
6875}
6876
6877StringRef ASTIdentifierIterator::Next() {
6878 while (Current == End) {
6879 // If we have exhausted all of our AST files, we're done.
6880 if (Index == 0)
6881 return StringRef();
6882
6883 --Index;
6884 ASTIdentifierLookupTable *IdTable
6885 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6886 IdentifierLookupTable;
6887 Current = IdTable->key_begin();
6888 End = IdTable->key_end();
6889 }
6890
6891 // We have any identifiers remaining in the current AST file; return
6892 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006893 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006894 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006895 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006896}
6897
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006898IdentifierIterator *ASTReader::getIdentifiers() {
6899 if (!loadGlobalIndex())
6900 return GlobalIndex->createIdentifierIterator();
6901
Guy Benyei11169dd2012-12-18 14:30:41 +00006902 return new ASTIdentifierIterator(*this);
6903}
6904
6905namespace clang { namespace serialization {
6906 class ReadMethodPoolVisitor {
6907 ASTReader &Reader;
6908 Selector Sel;
6909 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006910 unsigned InstanceBits;
6911 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006912 bool InstanceHasMoreThanOneDecl;
6913 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006914 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6915 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006916
6917 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00006918 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00006919 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00006920 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00006921 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
6922 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00006923
Guy Benyei11169dd2012-12-18 14:30:41 +00006924 static bool visit(ModuleFile &M, void *UserData) {
6925 ReadMethodPoolVisitor *This
6926 = static_cast<ReadMethodPoolVisitor *>(UserData);
6927
6928 if (!M.SelectorLookupTable)
6929 return false;
6930
6931 // If we've already searched this module file, skip it now.
6932 if (M.Generation <= This->PriorGeneration)
6933 return true;
6934
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006935 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006936 ASTSelectorLookupTable *PoolTable
6937 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6938 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6939 if (Pos == PoolTable->end())
6940 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006941
6942 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006943 ++This->Reader.NumSelectorsRead;
6944 // FIXME: Not quite happy with the statistics here. We probably should
6945 // disable this tracking when called via LoadSelector.
6946 // Also, should entries without methods count as misses?
6947 ++This->Reader.NumMethodPoolEntriesRead;
6948 ASTSelectorLookupTrait::data_type Data = *Pos;
6949 if (This->Reader.DeserializationListener)
6950 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6951 This->Sel);
6952
6953 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6954 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006955 This->InstanceBits = Data.InstanceBits;
6956 This->FactoryBits = Data.FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006957 This->InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
6958 This->FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00006959 return true;
6960 }
6961
6962 /// \brief Retrieve the instance methods found by this visitor.
6963 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6964 return InstanceMethods;
6965 }
6966
6967 /// \brief Retrieve the instance methods found by this visitor.
6968 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6969 return FactoryMethods;
6970 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006971
6972 unsigned getInstanceBits() const { return InstanceBits; }
6973 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00006974 bool instanceHasMoreThanOneDecl() const {
6975 return InstanceHasMoreThanOneDecl;
6976 }
6977 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006978 };
6979} } // end namespace clang::serialization
6980
6981/// \brief Add the given set of methods to the method list.
6982static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6983 ObjCMethodList &List) {
6984 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6985 S.addMethodToGlobalList(&List, Methods[I]);
6986 }
6987}
6988
6989void ASTReader::ReadMethodPool(Selector Sel) {
6990 // Get the selector generation and update it to the current generation.
6991 unsigned &Generation = SelectorGeneration[Sel];
6992 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00006993 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00006994
6995 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006996 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006997 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6998 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6999
7000 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007001 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007002 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007003
7004 ++NumMethodPoolHits;
7005
Guy Benyei11169dd2012-12-18 14:30:41 +00007006 if (!getSema())
7007 return;
7008
7009 Sema &S = *getSema();
7010 Sema::GlobalMethodPool::iterator Pos
7011 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007012
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007013 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007014 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007015 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007016 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007017
7018 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7019 // when building a module we keep every method individually and may need to
7020 // update hasMoreThanOneDecl as we add the methods.
7021 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7022 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007023}
7024
7025void ASTReader::ReadKnownNamespaces(
7026 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7027 Namespaces.clear();
7028
7029 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7030 if (NamespaceDecl *Namespace
7031 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7032 Namespaces.push_back(Namespace);
7033 }
7034}
7035
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007036void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007037 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007038 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7039 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007040 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007041 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007042 Undefined.insert(std::make_pair(D, Loc));
7043 }
7044}
Nick Lewycky8334af82013-01-26 00:35:08 +00007045
Guy Benyei11169dd2012-12-18 14:30:41 +00007046void ASTReader::ReadTentativeDefinitions(
7047 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7048 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7049 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7050 if (Var)
7051 TentativeDefs.push_back(Var);
7052 }
7053 TentativeDefinitions.clear();
7054}
7055
7056void ASTReader::ReadUnusedFileScopedDecls(
7057 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7058 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7059 DeclaratorDecl *D
7060 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7061 if (D)
7062 Decls.push_back(D);
7063 }
7064 UnusedFileScopedDecls.clear();
7065}
7066
7067void ASTReader::ReadDelegatingConstructors(
7068 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7069 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7070 CXXConstructorDecl *D
7071 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7072 if (D)
7073 Decls.push_back(D);
7074 }
7075 DelegatingCtorDecls.clear();
7076}
7077
7078void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7079 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7080 TypedefNameDecl *D
7081 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7082 if (D)
7083 Decls.push_back(D);
7084 }
7085 ExtVectorDecls.clear();
7086}
7087
Nico Weber72889432014-09-06 01:25:55 +00007088void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7089 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7090 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7091 ++I) {
7092 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7093 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7094 if (D)
7095 Decls.insert(D);
7096 }
7097 UnusedLocalTypedefNameCandidates.clear();
7098}
7099
Guy Benyei11169dd2012-12-18 14:30:41 +00007100void ASTReader::ReadReferencedSelectors(
7101 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7102 if (ReferencedSelectorsData.empty())
7103 return;
7104
7105 // If there are @selector references added them to its pool. This is for
7106 // implementation of -Wselector.
7107 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7108 unsigned I = 0;
7109 while (I < DataSize) {
7110 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7111 SourceLocation SelLoc
7112 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7113 Sels.push_back(std::make_pair(Sel, SelLoc));
7114 }
7115 ReferencedSelectorsData.clear();
7116}
7117
7118void ASTReader::ReadWeakUndeclaredIdentifiers(
7119 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7120 if (WeakUndeclaredIdentifiers.empty())
7121 return;
7122
7123 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7124 IdentifierInfo *WeakId
7125 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7126 IdentifierInfo *AliasId
7127 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7128 SourceLocation Loc
7129 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7130 bool Used = WeakUndeclaredIdentifiers[I++];
7131 WeakInfo WI(AliasId, Loc);
7132 WI.setUsed(Used);
7133 WeakIDs.push_back(std::make_pair(WeakId, WI));
7134 }
7135 WeakUndeclaredIdentifiers.clear();
7136}
7137
7138void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7139 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7140 ExternalVTableUse VT;
7141 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7142 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7143 VT.DefinitionRequired = VTableUses[Idx++];
7144 VTables.push_back(VT);
7145 }
7146
7147 VTableUses.clear();
7148}
7149
7150void ASTReader::ReadPendingInstantiations(
7151 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7152 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7153 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7154 SourceLocation Loc
7155 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7156
7157 Pending.push_back(std::make_pair(D, Loc));
7158 }
7159 PendingInstantiations.clear();
7160}
7161
Richard Smithe40f2ba2013-08-07 21:41:30 +00007162void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007163 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007164 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7165 /* In loop */) {
7166 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7167
7168 LateParsedTemplate *LT = new LateParsedTemplate;
7169 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7170
7171 ModuleFile *F = getOwningModuleFile(LT->D);
7172 assert(F && "No module");
7173
7174 unsigned TokN = LateParsedTemplates[Idx++];
7175 LT->Toks.reserve(TokN);
7176 for (unsigned T = 0; T < TokN; ++T)
7177 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7178
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007179 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007180 }
7181
7182 LateParsedTemplates.clear();
7183}
7184
Guy Benyei11169dd2012-12-18 14:30:41 +00007185void ASTReader::LoadSelector(Selector Sel) {
7186 // It would be complicated to avoid reading the methods anyway. So don't.
7187 ReadMethodPool(Sel);
7188}
7189
7190void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7191 assert(ID && "Non-zero identifier ID required");
7192 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7193 IdentifiersLoaded[ID - 1] = II;
7194 if (DeserializationListener)
7195 DeserializationListener->IdentifierRead(ID, II);
7196}
7197
7198/// \brief Set the globally-visible declarations associated with the given
7199/// identifier.
7200///
7201/// If the AST reader is currently in a state where the given declaration IDs
7202/// cannot safely be resolved, they are queued until it is safe to resolve
7203/// them.
7204///
7205/// \param II an IdentifierInfo that refers to one or more globally-visible
7206/// declarations.
7207///
7208/// \param DeclIDs the set of declaration IDs with the name @p II that are
7209/// visible at global scope.
7210///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007211/// \param Decls if non-null, this vector will be populated with the set of
7212/// deserialized declarations. These declarations will not be pushed into
7213/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007214void
7215ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7216 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007217 SmallVectorImpl<Decl *> *Decls) {
7218 if (NumCurrentElementsDeserializing && !Decls) {
7219 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007220 return;
7221 }
7222
7223 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007224 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007225 // Queue this declaration so that it will be added to the
7226 // translation unit scope and identifier's declaration chain
7227 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007228 PreloadedDeclIDs.push_back(DeclIDs[I]);
7229 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007230 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007231
7232 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7233
7234 // If we're simply supposed to record the declarations, do so now.
7235 if (Decls) {
7236 Decls->push_back(D);
7237 continue;
7238 }
7239
7240 // Introduce this declaration into the translation-unit scope
7241 // and add it to the declaration chain for this identifier, so
7242 // that (unqualified) name lookup will find it.
7243 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007244 }
7245}
7246
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007247IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007248 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007249 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007250
7251 if (IdentifiersLoaded.empty()) {
7252 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007253 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007254 }
7255
7256 ID -= 1;
7257 if (!IdentifiersLoaded[ID]) {
7258 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7259 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7260 ModuleFile *M = I->second;
7261 unsigned Index = ID - M->BaseIdentifierID;
7262 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7263
7264 // All of the strings in the AST file are preceded by a 16-bit length.
7265 // Extract that 16-bit length to avoid having to execute strlen().
7266 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7267 // unsigned integers. This is important to avoid integer overflow when
7268 // we cast them to 'unsigned'.
7269 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7270 unsigned StrLen = (((unsigned) StrLenPtr[0])
7271 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007272 IdentifiersLoaded[ID]
7273 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007274 if (DeserializationListener)
7275 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7276 }
7277
7278 return IdentifiersLoaded[ID];
7279}
7280
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007281IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7282 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007283}
7284
7285IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7286 if (LocalID < NUM_PREDEF_IDENT_IDS)
7287 return LocalID;
7288
7289 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7290 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7291 assert(I != M.IdentifierRemap.end()
7292 && "Invalid index into identifier index remap");
7293
7294 return LocalID + I->second;
7295}
7296
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007297MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007298 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007299 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007300
7301 if (MacrosLoaded.empty()) {
7302 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007303 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007304 }
7305
7306 ID -= NUM_PREDEF_MACRO_IDS;
7307 if (!MacrosLoaded[ID]) {
7308 GlobalMacroMapType::iterator I
7309 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7310 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7311 ModuleFile *M = I->second;
7312 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007313 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7314
7315 if (DeserializationListener)
7316 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7317 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007318 }
7319
7320 return MacrosLoaded[ID];
7321}
7322
7323MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7324 if (LocalID < NUM_PREDEF_MACRO_IDS)
7325 return LocalID;
7326
7327 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7328 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7329 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7330
7331 return LocalID + I->second;
7332}
7333
7334serialization::SubmoduleID
7335ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7336 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7337 return LocalID;
7338
7339 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7340 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7341 assert(I != M.SubmoduleRemap.end()
7342 && "Invalid index into submodule index remap");
7343
7344 return LocalID + I->second;
7345}
7346
7347Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7348 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7349 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007350 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007351 }
7352
7353 if (GlobalID > SubmodulesLoaded.size()) {
7354 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007355 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007356 }
7357
7358 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7359}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007360
7361Module *ASTReader::getModule(unsigned ID) {
7362 return getSubmodule(ID);
7363}
7364
Guy Benyei11169dd2012-12-18 14:30:41 +00007365Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7366 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7367}
7368
7369Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7370 if (ID == 0)
7371 return Selector();
7372
7373 if (ID > SelectorsLoaded.size()) {
7374 Error("selector ID out of range in AST file");
7375 return Selector();
7376 }
7377
Craig Toppera13603a2014-05-22 05:54:18 +00007378 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007379 // Load this selector from the selector table.
7380 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7381 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7382 ModuleFile &M = *I->second;
7383 ASTSelectorLookupTrait Trait(*this, M);
7384 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7385 SelectorsLoaded[ID - 1] =
7386 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7387 if (DeserializationListener)
7388 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7389 }
7390
7391 return SelectorsLoaded[ID - 1];
7392}
7393
7394Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7395 return DecodeSelector(ID);
7396}
7397
7398uint32_t ASTReader::GetNumExternalSelectors() {
7399 // ID 0 (the null selector) is considered an external selector.
7400 return getTotalNumSelectors() + 1;
7401}
7402
7403serialization::SelectorID
7404ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7405 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7406 return LocalID;
7407
7408 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7409 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7410 assert(I != M.SelectorRemap.end()
7411 && "Invalid index into selector index remap");
7412
7413 return LocalID + I->second;
7414}
7415
7416DeclarationName
7417ASTReader::ReadDeclarationName(ModuleFile &F,
7418 const RecordData &Record, unsigned &Idx) {
7419 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7420 switch (Kind) {
7421 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007422 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007423
7424 case DeclarationName::ObjCZeroArgSelector:
7425 case DeclarationName::ObjCOneArgSelector:
7426 case DeclarationName::ObjCMultiArgSelector:
7427 return DeclarationName(ReadSelector(F, Record, Idx));
7428
7429 case DeclarationName::CXXConstructorName:
7430 return Context.DeclarationNames.getCXXConstructorName(
7431 Context.getCanonicalType(readType(F, Record, Idx)));
7432
7433 case DeclarationName::CXXDestructorName:
7434 return Context.DeclarationNames.getCXXDestructorName(
7435 Context.getCanonicalType(readType(F, Record, Idx)));
7436
7437 case DeclarationName::CXXConversionFunctionName:
7438 return Context.DeclarationNames.getCXXConversionFunctionName(
7439 Context.getCanonicalType(readType(F, Record, Idx)));
7440
7441 case DeclarationName::CXXOperatorName:
7442 return Context.DeclarationNames.getCXXOperatorName(
7443 (OverloadedOperatorKind)Record[Idx++]);
7444
7445 case DeclarationName::CXXLiteralOperatorName:
7446 return Context.DeclarationNames.getCXXLiteralOperatorName(
7447 GetIdentifierInfo(F, Record, Idx));
7448
7449 case DeclarationName::CXXUsingDirective:
7450 return DeclarationName::getUsingDirectiveName();
7451 }
7452
7453 llvm_unreachable("Invalid NameKind!");
7454}
7455
7456void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7457 DeclarationNameLoc &DNLoc,
7458 DeclarationName Name,
7459 const RecordData &Record, unsigned &Idx) {
7460 switch (Name.getNameKind()) {
7461 case DeclarationName::CXXConstructorName:
7462 case DeclarationName::CXXDestructorName:
7463 case DeclarationName::CXXConversionFunctionName:
7464 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7465 break;
7466
7467 case DeclarationName::CXXOperatorName:
7468 DNLoc.CXXOperatorName.BeginOpNameLoc
7469 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7470 DNLoc.CXXOperatorName.EndOpNameLoc
7471 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7472 break;
7473
7474 case DeclarationName::CXXLiteralOperatorName:
7475 DNLoc.CXXLiteralOperatorName.OpNameLoc
7476 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7477 break;
7478
7479 case DeclarationName::Identifier:
7480 case DeclarationName::ObjCZeroArgSelector:
7481 case DeclarationName::ObjCOneArgSelector:
7482 case DeclarationName::ObjCMultiArgSelector:
7483 case DeclarationName::CXXUsingDirective:
7484 break;
7485 }
7486}
7487
7488void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7489 DeclarationNameInfo &NameInfo,
7490 const RecordData &Record, unsigned &Idx) {
7491 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7492 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7493 DeclarationNameLoc DNLoc;
7494 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7495 NameInfo.setInfo(DNLoc);
7496}
7497
7498void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7499 const RecordData &Record, unsigned &Idx) {
7500 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7501 unsigned NumTPLists = Record[Idx++];
7502 Info.NumTemplParamLists = NumTPLists;
7503 if (NumTPLists) {
7504 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7505 for (unsigned i=0; i != NumTPLists; ++i)
7506 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7507 }
7508}
7509
7510TemplateName
7511ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7512 unsigned &Idx) {
7513 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7514 switch (Kind) {
7515 case TemplateName::Template:
7516 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7517
7518 case TemplateName::OverloadedTemplate: {
7519 unsigned size = Record[Idx++];
7520 UnresolvedSet<8> Decls;
7521 while (size--)
7522 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7523
7524 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7525 }
7526
7527 case TemplateName::QualifiedTemplate: {
7528 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7529 bool hasTemplKeyword = Record[Idx++];
7530 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7531 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7532 }
7533
7534 case TemplateName::DependentTemplate: {
7535 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7536 if (Record[Idx++]) // isIdentifier
7537 return Context.getDependentTemplateName(NNS,
7538 GetIdentifierInfo(F, Record,
7539 Idx));
7540 return Context.getDependentTemplateName(NNS,
7541 (OverloadedOperatorKind)Record[Idx++]);
7542 }
7543
7544 case TemplateName::SubstTemplateTemplateParm: {
7545 TemplateTemplateParmDecl *param
7546 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7547 if (!param) return TemplateName();
7548 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7549 return Context.getSubstTemplateTemplateParm(param, replacement);
7550 }
7551
7552 case TemplateName::SubstTemplateTemplateParmPack: {
7553 TemplateTemplateParmDecl *Param
7554 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7555 if (!Param)
7556 return TemplateName();
7557
7558 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7559 if (ArgPack.getKind() != TemplateArgument::Pack)
7560 return TemplateName();
7561
7562 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7563 }
7564 }
7565
7566 llvm_unreachable("Unhandled template name kind!");
7567}
7568
7569TemplateArgument
7570ASTReader::ReadTemplateArgument(ModuleFile &F,
7571 const RecordData &Record, unsigned &Idx) {
7572 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7573 switch (Kind) {
7574 case TemplateArgument::Null:
7575 return TemplateArgument();
7576 case TemplateArgument::Type:
7577 return TemplateArgument(readType(F, Record, Idx));
7578 case TemplateArgument::Declaration: {
7579 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007580 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007581 }
7582 case TemplateArgument::NullPtr:
7583 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7584 case TemplateArgument::Integral: {
7585 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7586 QualType T = readType(F, Record, Idx);
7587 return TemplateArgument(Context, Value, T);
7588 }
7589 case TemplateArgument::Template:
7590 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7591 case TemplateArgument::TemplateExpansion: {
7592 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007593 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007594 if (unsigned NumExpansions = Record[Idx++])
7595 NumTemplateExpansions = NumExpansions - 1;
7596 return TemplateArgument(Name, NumTemplateExpansions);
7597 }
7598 case TemplateArgument::Expression:
7599 return TemplateArgument(ReadExpr(F));
7600 case TemplateArgument::Pack: {
7601 unsigned NumArgs = Record[Idx++];
7602 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7603 for (unsigned I = 0; I != NumArgs; ++I)
7604 Args[I] = ReadTemplateArgument(F, Record, Idx);
7605 return TemplateArgument(Args, NumArgs);
7606 }
7607 }
7608
7609 llvm_unreachable("Unhandled template argument kind!");
7610}
7611
7612TemplateParameterList *
7613ASTReader::ReadTemplateParameterList(ModuleFile &F,
7614 const RecordData &Record, unsigned &Idx) {
7615 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7616 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7617 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7618
7619 unsigned NumParams = Record[Idx++];
7620 SmallVector<NamedDecl *, 16> Params;
7621 Params.reserve(NumParams);
7622 while (NumParams--)
7623 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7624
7625 TemplateParameterList* TemplateParams =
7626 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7627 Params.data(), Params.size(), RAngleLoc);
7628 return TemplateParams;
7629}
7630
7631void
7632ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007633ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007634 ModuleFile &F, const RecordData &Record,
7635 unsigned &Idx) {
7636 unsigned NumTemplateArgs = Record[Idx++];
7637 TemplArgs.reserve(NumTemplateArgs);
7638 while (NumTemplateArgs--)
7639 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7640}
7641
7642/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007643void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007644 const RecordData &Record, unsigned &Idx) {
7645 unsigned NumDecls = Record[Idx++];
7646 Set.reserve(Context, NumDecls);
7647 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007648 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007649 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007650 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007651 }
7652}
7653
7654CXXBaseSpecifier
7655ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7656 const RecordData &Record, unsigned &Idx) {
7657 bool isVirtual = static_cast<bool>(Record[Idx++]);
7658 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7659 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7660 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7661 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7662 SourceRange Range = ReadSourceRange(F, Record, Idx);
7663 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7664 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7665 EllipsisLoc);
7666 Result.setInheritConstructors(inheritConstructors);
7667 return Result;
7668}
7669
Richard Smithc2bb8182015-03-24 06:36:48 +00007670CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007671ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7672 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007673 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007674 assert(NumInitializers && "wrote ctor initializers but have no inits");
7675 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7676 for (unsigned i = 0; i != NumInitializers; ++i) {
7677 TypeSourceInfo *TInfo = nullptr;
7678 bool IsBaseVirtual = false;
7679 FieldDecl *Member = nullptr;
7680 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007681
Richard Smithc2bb8182015-03-24 06:36:48 +00007682 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7683 switch (Type) {
7684 case CTOR_INITIALIZER_BASE:
7685 TInfo = GetTypeSourceInfo(F, Record, Idx);
7686 IsBaseVirtual = Record[Idx++];
7687 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007688
Richard Smithc2bb8182015-03-24 06:36:48 +00007689 case CTOR_INITIALIZER_DELEGATING:
7690 TInfo = GetTypeSourceInfo(F, Record, Idx);
7691 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007692
Richard Smithc2bb8182015-03-24 06:36:48 +00007693 case CTOR_INITIALIZER_MEMBER:
7694 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7695 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007696
Richard Smithc2bb8182015-03-24 06:36:48 +00007697 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7698 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7699 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007700 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007701
7702 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7703 Expr *Init = ReadExpr(F);
7704 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7705 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7706 bool IsWritten = Record[Idx++];
7707 unsigned SourceOrderOrNumArrayIndices;
7708 SmallVector<VarDecl *, 8> Indices;
7709 if (IsWritten) {
7710 SourceOrderOrNumArrayIndices = Record[Idx++];
7711 } else {
7712 SourceOrderOrNumArrayIndices = Record[Idx++];
7713 Indices.reserve(SourceOrderOrNumArrayIndices);
7714 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7715 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7716 }
7717
7718 CXXCtorInitializer *BOMInit;
7719 if (Type == CTOR_INITIALIZER_BASE) {
7720 BOMInit = new (Context)
7721 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7722 RParenLoc, MemberOrEllipsisLoc);
7723 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7724 BOMInit = new (Context)
7725 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7726 } else if (IsWritten) {
7727 if (Member)
7728 BOMInit = new (Context) CXXCtorInitializer(
7729 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7730 else
7731 BOMInit = new (Context)
7732 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7733 LParenLoc, Init, RParenLoc);
7734 } else {
7735 if (IndirectMember) {
7736 assert(Indices.empty() && "Indirect field improperly initialized");
7737 BOMInit = new (Context)
7738 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7739 LParenLoc, Init, RParenLoc);
7740 } else {
7741 BOMInit = CXXCtorInitializer::Create(
7742 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7743 Indices.data(), Indices.size());
7744 }
7745 }
7746
7747 if (IsWritten)
7748 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7749 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007750 }
7751
Richard Smithc2bb8182015-03-24 06:36:48 +00007752 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007753}
7754
7755NestedNameSpecifier *
7756ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7757 const RecordData &Record, unsigned &Idx) {
7758 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007759 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007760 for (unsigned I = 0; I != N; ++I) {
7761 NestedNameSpecifier::SpecifierKind Kind
7762 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7763 switch (Kind) {
7764 case NestedNameSpecifier::Identifier: {
7765 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7766 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7767 break;
7768 }
7769
7770 case NestedNameSpecifier::Namespace: {
7771 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7772 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7773 break;
7774 }
7775
7776 case NestedNameSpecifier::NamespaceAlias: {
7777 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7778 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7779 break;
7780 }
7781
7782 case NestedNameSpecifier::TypeSpec:
7783 case NestedNameSpecifier::TypeSpecWithTemplate: {
7784 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7785 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007786 return nullptr;
7787
Guy Benyei11169dd2012-12-18 14:30:41 +00007788 bool Template = Record[Idx++];
7789 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7790 break;
7791 }
7792
7793 case NestedNameSpecifier::Global: {
7794 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7795 // No associated value, and there can't be a prefix.
7796 break;
7797 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007798
7799 case NestedNameSpecifier::Super: {
7800 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7801 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7802 break;
7803 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007804 }
7805 Prev = NNS;
7806 }
7807 return NNS;
7808}
7809
7810NestedNameSpecifierLoc
7811ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7812 unsigned &Idx) {
7813 unsigned N = Record[Idx++];
7814 NestedNameSpecifierLocBuilder Builder;
7815 for (unsigned I = 0; I != N; ++I) {
7816 NestedNameSpecifier::SpecifierKind Kind
7817 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7818 switch (Kind) {
7819 case NestedNameSpecifier::Identifier: {
7820 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7821 SourceRange Range = ReadSourceRange(F, Record, Idx);
7822 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7823 break;
7824 }
7825
7826 case NestedNameSpecifier::Namespace: {
7827 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7828 SourceRange Range = ReadSourceRange(F, Record, Idx);
7829 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7830 break;
7831 }
7832
7833 case NestedNameSpecifier::NamespaceAlias: {
7834 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7835 SourceRange Range = ReadSourceRange(F, Record, Idx);
7836 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7837 break;
7838 }
7839
7840 case NestedNameSpecifier::TypeSpec:
7841 case NestedNameSpecifier::TypeSpecWithTemplate: {
7842 bool Template = Record[Idx++];
7843 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7844 if (!T)
7845 return NestedNameSpecifierLoc();
7846 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7847
7848 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7849 Builder.Extend(Context,
7850 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7851 T->getTypeLoc(), ColonColonLoc);
7852 break;
7853 }
7854
7855 case NestedNameSpecifier::Global: {
7856 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7857 Builder.MakeGlobal(Context, ColonColonLoc);
7858 break;
7859 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007860
7861 case NestedNameSpecifier::Super: {
7862 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7863 SourceRange Range = ReadSourceRange(F, Record, Idx);
7864 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
7865 break;
7866 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007867 }
7868 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007869
Guy Benyei11169dd2012-12-18 14:30:41 +00007870 return Builder.getWithLocInContext(Context);
7871}
7872
7873SourceRange
7874ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7875 unsigned &Idx) {
7876 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7877 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7878 return SourceRange(beg, end);
7879}
7880
7881/// \brief Read an integral value
7882llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7883 unsigned BitWidth = Record[Idx++];
7884 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7885 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7886 Idx += NumWords;
7887 return Result;
7888}
7889
7890/// \brief Read a signed integral value
7891llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7892 bool isUnsigned = Record[Idx++];
7893 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7894}
7895
7896/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007897llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7898 const llvm::fltSemantics &Sem,
7899 unsigned &Idx) {
7900 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007901}
7902
7903// \brief Read a string
7904std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7905 unsigned Len = Record[Idx++];
7906 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7907 Idx += Len;
7908 return Result;
7909}
7910
Richard Smith7ed1bc92014-12-05 22:42:13 +00007911std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
7912 unsigned &Idx) {
7913 std::string Filename = ReadString(Record, Idx);
7914 ResolveImportedPath(F, Filename);
7915 return Filename;
7916}
7917
Guy Benyei11169dd2012-12-18 14:30:41 +00007918VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7919 unsigned &Idx) {
7920 unsigned Major = Record[Idx++];
7921 unsigned Minor = Record[Idx++];
7922 unsigned Subminor = Record[Idx++];
7923 if (Minor == 0)
7924 return VersionTuple(Major);
7925 if (Subminor == 0)
7926 return VersionTuple(Major, Minor - 1);
7927 return VersionTuple(Major, Minor - 1, Subminor - 1);
7928}
7929
7930CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7931 const RecordData &Record,
7932 unsigned &Idx) {
7933 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7934 return CXXTemporary::Create(Context, Decl);
7935}
7936
7937DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007938 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007939}
7940
7941DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7942 return Diags.Report(Loc, DiagID);
7943}
7944
7945/// \brief Retrieve the identifier table associated with the
7946/// preprocessor.
7947IdentifierTable &ASTReader::getIdentifierTable() {
7948 return PP.getIdentifierTable();
7949}
7950
7951/// \brief Record that the given ID maps to the given switch-case
7952/// statement.
7953void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007954 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007955 "Already have a SwitchCase with this ID");
7956 (*CurrSwitchCaseStmts)[ID] = SC;
7957}
7958
7959/// \brief Retrieve the switch-case statement with the given ID.
7960SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007961 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00007962 return (*CurrSwitchCaseStmts)[ID];
7963}
7964
7965void ASTReader::ClearSwitchCaseIDs() {
7966 CurrSwitchCaseStmts->clear();
7967}
7968
7969void ASTReader::ReadComments() {
7970 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007971 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007972 serialization::ModuleFile *> >::iterator
7973 I = CommentsCursors.begin(),
7974 E = CommentsCursors.end();
7975 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007976 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007977 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007978 serialization::ModuleFile &F = *I->second;
7979 SavedStreamPosition SavedPosition(Cursor);
7980
7981 RecordData Record;
7982 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007983 llvm::BitstreamEntry Entry =
7984 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007985
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007986 switch (Entry.Kind) {
7987 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7988 case llvm::BitstreamEntry::Error:
7989 Error("malformed block record in AST file");
7990 return;
7991 case llvm::BitstreamEntry::EndBlock:
7992 goto NextCursor;
7993 case llvm::BitstreamEntry::Record:
7994 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00007995 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007996 }
7997
7998 // Read a record.
7999 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008000 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008001 case COMMENTS_RAW_COMMENT: {
8002 unsigned Idx = 0;
8003 SourceRange SR = ReadSourceRange(F, Record, Idx);
8004 RawComment::CommentKind Kind =
8005 (RawComment::CommentKind) Record[Idx++];
8006 bool IsTrailingComment = Record[Idx++];
8007 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008008 Comments.push_back(new (Context) RawComment(
8009 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8010 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008011 break;
8012 }
8013 }
8014 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008015 NextCursor:
8016 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008017 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008018}
8019
Argyrios Kyrtzidis1bde1172014-11-18 05:24:18 +00008020void ASTReader::getInputFiles(ModuleFile &F,
8021 SmallVectorImpl<serialization::InputFile> &Files) {
8022 for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
8023 unsigned ID = I+1;
8024 Files.push_back(getInputFile(F, ID));
8025 }
8026}
8027
Richard Smithcd45dbc2014-04-19 03:48:30 +00008028std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8029 // If we know the owning module, use it.
8030 if (Module *M = D->getOwningModule())
8031 return M->getFullModuleName();
8032
8033 // Otherwise, use the name of the top-level module the decl is within.
8034 if (ModuleFile *M = getOwningModuleFile(D))
8035 return M->ModuleName;
8036
8037 // Not from a module.
8038 return "";
8039}
8040
Guy Benyei11169dd2012-12-18 14:30:41 +00008041void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008042 while (!PendingIdentifierInfos.empty() ||
8043 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008044 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008045 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008046 // If any identifiers with corresponding top-level declarations have
8047 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008048 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8049 TopLevelDeclsMap;
8050 TopLevelDeclsMap TopLevelDecls;
8051
Guy Benyei11169dd2012-12-18 14:30:41 +00008052 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008053 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008054 SmallVector<uint32_t, 4> DeclIDs =
8055 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008056 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008057
8058 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008059 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008060
Richard Smith851072e2014-05-19 20:59:20 +00008061 // For each decl chain that we wanted to complete while deserializing, mark
8062 // it as "still needs to be completed".
8063 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8064 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8065 }
8066 PendingIncompleteDeclChains.clear();
8067
Guy Benyei11169dd2012-12-18 14:30:41 +00008068 // Load pending declaration chains.
Richard Smithfe620d22015-03-05 23:24:12 +00008069 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
Richard Smithfe620d22015-03-05 23:24:12 +00008070 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
Richard Smithe687bf82015-03-16 20:54:07 +00008071 loadPendingDeclChain(PendingDeclChains[I]);
Richard Smithfe620d22015-03-05 23:24:12 +00008072 }
8073 assert(PendingDeclChainsKnown.empty());
Guy Benyei11169dd2012-12-18 14:30:41 +00008074 PendingDeclChains.clear();
8075
Douglas Gregor6168bd22013-02-18 15:53:43 +00008076 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008077 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8078 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008079 IdentifierInfo *II = TLD->first;
8080 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008081 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008082 }
8083 }
8084
Guy Benyei11169dd2012-12-18 14:30:41 +00008085 // Load any pending macro definitions.
8086 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008087 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8088 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8089 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8090 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008091 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008092 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008093 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008094 if (Info.M->Kind != MK_ImplicitModule &&
8095 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008096 resolvePendingMacro(II, Info);
8097 }
8098 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008099 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008100 ++IDIdx) {
8101 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008102 if (Info.M->Kind == MK_ImplicitModule ||
8103 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008104 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008105 }
8106 }
8107 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008108
8109 // Wire up the DeclContexts for Decls that we delayed setting until
8110 // recursive loading is completed.
8111 while (!PendingDeclContextInfos.empty()) {
8112 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8113 PendingDeclContextInfos.pop_front();
8114 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8115 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8116 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8117 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008118
Richard Smithd1c46742014-04-30 02:24:17 +00008119 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008120 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008121 auto Update = PendingUpdateRecords.pop_back_val();
8122 ReadingKindTracker ReadingKind(Read_Decl, *this);
8123 loadDeclUpdateRecords(Update.first, Update.second);
8124 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008125 }
Richard Smith8a639892015-01-24 01:07:20 +00008126
8127 // At this point, all update records for loaded decls are in place, so any
8128 // fake class definitions should have become real.
8129 assert(PendingFakeDefinitionData.empty() &&
8130 "faked up a class definition but never saw the real one");
8131
Guy Benyei11169dd2012-12-18 14:30:41 +00008132 // If we deserialized any C++ or Objective-C class definitions, any
8133 // Objective-C protocol definitions, or any redeclarable templates, make sure
8134 // that all redeclarations point to the definitions. Note that this can only
8135 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008136 for (Decl *D : PendingDefinitions) {
8137 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008138 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008139 // Make sure that the TagType points at the definition.
8140 const_cast<TagType*>(TagT)->decl = TD;
8141 }
Richard Smith8ce51082015-03-11 01:44:51 +00008142
Craig Topperc6914d02014-08-25 04:15:02 +00008143 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008144 for (auto *R = getMostRecentExistingDecl(RD); R;
8145 R = R->getPreviousDecl()) {
8146 assert((R == D) ==
8147 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008148 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008149 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008150 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008151 }
8152
8153 continue;
8154 }
Richard Smith8ce51082015-03-11 01:44:51 +00008155
Craig Topperc6914d02014-08-25 04:15:02 +00008156 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008157 // Make sure that the ObjCInterfaceType points at the definition.
8158 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8159 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008160
8161 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8162 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8163
Guy Benyei11169dd2012-12-18 14:30:41 +00008164 continue;
8165 }
Richard Smith8ce51082015-03-11 01:44:51 +00008166
Craig Topperc6914d02014-08-25 04:15:02 +00008167 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008168 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8169 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8170
Guy Benyei11169dd2012-12-18 14:30:41 +00008171 continue;
8172 }
Richard Smith8ce51082015-03-11 01:44:51 +00008173
Craig Topperc6914d02014-08-25 04:15:02 +00008174 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008175 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8176 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008177 }
8178 PendingDefinitions.clear();
8179
8180 // Load the bodies of any functions or methods we've encountered. We do
8181 // this now (delayed) so that we can be sure that the declaration chains
8182 // have been fully wired up.
Richard Smith8ce51082015-03-11 01:44:51 +00008183 // FIXME: There seems to be no point in delaying this, it does not depend
8184 // on the redecl chains having been wired up.
Guy Benyei11169dd2012-12-18 14:30:41 +00008185 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8186 PBEnd = PendingBodies.end();
8187 PB != PBEnd; ++PB) {
8188 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8189 // FIXME: Check for =delete/=default?
8190 // FIXME: Complain about ODR violations here?
8191 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8192 FD->setLazyBody(PB->second);
8193 continue;
8194 }
8195
8196 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8197 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8198 MD->setLazyBody(PB->second);
8199 }
8200 PendingBodies.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008201}
8202
8203void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008204 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8205 return;
8206
Richard Smitha0ce9c42014-07-29 23:23:27 +00008207 // Trigger the import of the full definition of each class that had any
8208 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008209 // These updates may in turn find and diagnose some ODR failures, so take
8210 // ownership of the set first.
8211 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8212 PendingOdrMergeFailures.clear();
8213 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008214 Merge.first->buildLookup();
8215 Merge.first->decls_begin();
8216 Merge.first->bases_begin();
8217 Merge.first->vbases_begin();
8218 for (auto *RD : Merge.second) {
8219 RD->decls_begin();
8220 RD->bases_begin();
8221 RD->vbases_begin();
8222 }
8223 }
8224
8225 // For each declaration from a merged context, check that the canonical
8226 // definition of that context also contains a declaration of the same
8227 // entity.
8228 //
8229 // Caution: this loop does things that might invalidate iterators into
8230 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8231 while (!PendingOdrMergeChecks.empty()) {
8232 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8233
8234 // FIXME: Skip over implicit declarations for now. This matters for things
8235 // like implicitly-declared special member functions. This isn't entirely
8236 // correct; we can end up with multiple unmerged declarations of the same
8237 // implicit entity.
8238 if (D->isImplicit())
8239 continue;
8240
8241 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008242
8243 bool Found = false;
8244 const Decl *DCanon = D->getCanonicalDecl();
8245
Richard Smith01bdb7a2014-08-28 05:44:07 +00008246 for (auto RI : D->redecls()) {
8247 if (RI->getLexicalDeclContext() == CanonDef) {
8248 Found = true;
8249 break;
8250 }
8251 }
8252 if (Found)
8253 continue;
8254
Richard Smitha0ce9c42014-07-29 23:23:27 +00008255 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith01bdb7a2014-08-28 05:44:07 +00008256 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
Richard Smitha0ce9c42014-07-29 23:23:27 +00008257 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8258 !Found && I != E; ++I) {
8259 for (auto RI : (*I)->redecls()) {
8260 if (RI->getLexicalDeclContext() == CanonDef) {
8261 // This declaration is present in the canonical definition. If it's
8262 // in the same redecl chain, it's the one we're looking for.
8263 if (RI->getCanonicalDecl() == DCanon)
8264 Found = true;
8265 else
8266 Candidates.push_back(cast<NamedDecl>(RI));
8267 break;
8268 }
8269 }
8270 }
8271
8272 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008273 // The AST doesn't like TagDecls becoming invalid after they've been
8274 // completed. We only really need to mark FieldDecls as invalid here.
8275 if (!isa<TagDecl>(D))
8276 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008277
8278 // Ensure we don't accidentally recursively enter deserialization while
8279 // we're producing our diagnostic.
8280 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008281
8282 std::string CanonDefModule =
8283 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8284 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8285 << D << getOwningModuleNameForDiagnostic(D)
8286 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8287
8288 if (Candidates.empty())
8289 Diag(cast<Decl>(CanonDef)->getLocation(),
8290 diag::note_module_odr_violation_no_possible_decls) << D;
8291 else {
8292 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8293 Diag(Candidates[I]->getLocation(),
8294 diag::note_module_odr_violation_possible_decl)
8295 << Candidates[I];
8296 }
8297
8298 DiagnosedOdrMergeFailures.insert(CanonDef);
8299 }
8300 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008301
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008302 if (OdrMergeFailures.empty())
8303 return;
8304
8305 // Ensure we don't accidentally recursively enter deserialization while
8306 // we're producing our diagnostics.
8307 Deserializing RecursionGuard(this);
8308
Richard Smithcd45dbc2014-04-19 03:48:30 +00008309 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008310 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008311 // If we've already pointed out a specific problem with this class, don't
8312 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008313 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008314 continue;
8315
8316 bool Diagnosed = false;
8317 for (auto *RD : Merge.second) {
8318 // Multiple different declarations got merged together; tell the user
8319 // where they came from.
8320 if (Merge.first != RD) {
8321 // FIXME: Walk the definition, figure out what's different,
8322 // and diagnose that.
8323 if (!Diagnosed) {
8324 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8325 Diag(Merge.first->getLocation(),
8326 diag::err_module_odr_violation_different_definitions)
8327 << Merge.first << Module.empty() << Module;
8328 Diagnosed = true;
8329 }
8330
8331 Diag(RD->getLocation(),
8332 diag::note_module_odr_violation_different_definitions)
8333 << getOwningModuleNameForDiagnostic(RD);
8334 }
8335 }
8336
8337 if (!Diagnosed) {
8338 // All definitions are updates to the same declaration. This happens if a
8339 // module instantiates the declaration of a class template specialization
8340 // and two or more other modules instantiate its definition.
8341 //
8342 // FIXME: Indicate which modules had instantiations of this definition.
8343 // FIXME: How can this even happen?
8344 Diag(Merge.first->getLocation(),
8345 diag::err_module_odr_violation_different_instantiations)
8346 << Merge.first;
8347 }
8348 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008349}
8350
8351void ASTReader::FinishedDeserializing() {
8352 assert(NumCurrentElementsDeserializing &&
8353 "FinishedDeserializing not paired with StartedDeserializing");
8354 if (NumCurrentElementsDeserializing == 1) {
8355 // We decrease NumCurrentElementsDeserializing only after pending actions
8356 // are finished, to avoid recursively re-calling finishPendingActions().
8357 finishPendingActions();
8358 }
8359 --NumCurrentElementsDeserializing;
8360
Richard Smitha0ce9c42014-07-29 23:23:27 +00008361 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008362 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008363 while (!PendingExceptionSpecUpdates.empty()) {
8364 auto Updates = std::move(PendingExceptionSpecUpdates);
8365 PendingExceptionSpecUpdates.clear();
8366 for (auto Update : Updates) {
8367 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8368 SemaObj->UpdateExceptionSpec(Update.second,
8369 FPT->getExtProtoInfo().ExceptionSpec);
8370 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008371 }
8372
Richard Smitha0ce9c42014-07-29 23:23:27 +00008373 diagnoseOdrViolations();
8374
Richard Smith04d05b52014-03-23 00:27:18 +00008375 // We are not in recursive loading, so it's safe to pass the "interesting"
8376 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008377 if (Consumer)
8378 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008379 }
8380}
8381
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008382void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008383 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8384 // Remove any fake results before adding any real ones.
8385 auto It = PendingFakeLookupResults.find(II);
8386 if (It != PendingFakeLookupResults.end()) {
8387 for (auto *ND : PendingFakeLookupResults[II])
8388 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008389 // FIXME: this works around module+PCH performance issue.
8390 // Rather than erase the result from the map, which is O(n), just clear
8391 // the vector of NamedDecls.
8392 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008393 }
8394 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008395
8396 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8397 SemaObj->TUScope->AddDecl(D);
8398 } else if (SemaObj->TUScope) {
8399 // Adding the decl to IdResolver may have failed because it was already in
8400 // (even though it was not added in scope). If it is already in, make sure
8401 // it gets in the scope as well.
8402 if (std::find(SemaObj->IdResolver.begin(Name),
8403 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8404 SemaObj->TUScope->AddDecl(D);
8405 }
8406}
8407
Nico Weber824285e2014-05-08 04:26:47 +00008408ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8409 bool DisableValidation, bool AllowASTWithCompilerErrors,
8410 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008411 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008412 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008413 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Craig Toppera13603a2014-05-22 05:54:18 +00008414 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
8415 SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
8416 ModuleMgr(PP.getFileManager()), isysroot(isysroot),
8417 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008418 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8419 AllowConfigurationMismatch(AllowConfigurationMismatch),
8420 ValidateSystemInputs(ValidateSystemInputs),
8421 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Richard Smith053f6c62014-05-16 23:01:30 +00008422 CurrSwitchCaseStmts(&SwitchCaseStmts),
Nico Weber824285e2014-05-08 04:26:47 +00008423 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8424 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8425 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8426 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8427 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8428 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8429 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8430 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8431 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008432 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008433 SourceMgr.setExternalSLocEntrySource(this);
8434}
8435
8436ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008437 if (OwnsDeserializationListener)
8438 delete DeserializationListener;
8439
Guy Benyei11169dd2012-12-18 14:30:41 +00008440 for (DeclContextVisibleUpdatesPending::iterator
8441 I = PendingVisibleUpdates.begin(),
8442 E = PendingVisibleUpdates.end();
8443 I != E; ++I) {
8444 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8445 F = I->second.end();
8446 J != F; ++J)
8447 delete J->first;
8448 }
8449}