blob: 248e10d598b9c3f6cc72fbfef6020a43eebc2570 [file] [log] [blame]
Richard Smith9e2341d2015-03-23 03:25:59 +00001//===-- ASTReader.cpp - AST File Reader ----------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the ASTReader class, which reads AST files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Serialization/ASTReader.h"
15#include "ASTCommon.h"
16#include "ASTReaderInternals.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/NestedNameSpecifier.h"
23#include "clang/AST/Type.h"
24#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000025#include "clang/Basic/DiagnosticOptions.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000026#include "clang/Basic/FileManager.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000027#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/SourceManagerInternals.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Basic/TargetOptions.h"
31#include "clang/Basic/Version.h"
32#include "clang/Basic/VersionTuple.h"
Ben Langmuirb92de022014-04-29 16:25:26 +000033#include "clang/Frontend/Utils.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000034#include "clang/Lex/HeaderSearch.h"
35#include "clang/Lex/HeaderSearchOptions.h"
36#include "clang/Lex/MacroInfo.h"
37#include "clang/Lex/PreprocessingRecord.h"
38#include "clang/Lex/Preprocessor.h"
39#include "clang/Lex/PreprocessorOptions.h"
40#include "clang/Sema/Scope.h"
41#include "clang/Sema/Sema.h"
42#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000043#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000044#include "clang/Serialization/ModuleManager.h"
45#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000046#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000047#include "llvm/ADT/StringExtras.h"
48#include "llvm/Bitcode/BitstreamReader.h"
49#include "llvm/Support/ErrorHandling.h"
50#include "llvm/Support/FileSystem.h"
51#include "llvm/Support/MemoryBuffer.h"
52#include "llvm/Support/Path.h"
53#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000054#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000055#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000056#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000057#include <iterator>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000058#include <system_error>
Guy Benyei11169dd2012-12-18 14:30:41 +000059
60using namespace clang;
61using namespace clang::serialization;
62using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000063using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000064
Ben Langmuircb69b572014-03-07 06:40:32 +000065
66//===----------------------------------------------------------------------===//
67// ChainedASTReaderListener implementation
68//===----------------------------------------------------------------------===//
69
70bool
71ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
72 return First->ReadFullVersionInformation(FullVersion) ||
73 Second->ReadFullVersionInformation(FullVersion);
74}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000075void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
76 First->ReadModuleName(ModuleName);
77 Second->ReadModuleName(ModuleName);
78}
79void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
80 First->ReadModuleMapFile(ModuleMapPath);
81 Second->ReadModuleMapFile(ModuleMapPath);
82}
Richard Smith1e2cf0d2014-10-31 02:28:58 +000083bool
84ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
85 bool Complain,
86 bool AllowCompatibleDifferences) {
87 return First->ReadLanguageOptions(LangOpts, Complain,
88 AllowCompatibleDifferences) ||
89 Second->ReadLanguageOptions(LangOpts, Complain,
90 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000091}
Chandler Carruth0d745bc2015-03-14 04:47:43 +000092bool ChainedASTReaderListener::ReadTargetOptions(
93 const TargetOptions &TargetOpts, bool Complain,
94 bool AllowCompatibleDifferences) {
95 return First->ReadTargetOptions(TargetOpts, Complain,
96 AllowCompatibleDifferences) ||
97 Second->ReadTargetOptions(TargetOpts, Complain,
98 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000099}
100bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000101 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000102 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
103 Second->ReadDiagnosticOptions(DiagOpts, Complain);
104}
105bool
106ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
107 bool Complain) {
108 return First->ReadFileSystemOptions(FSOpts, Complain) ||
109 Second->ReadFileSystemOptions(FSOpts, Complain);
110}
111
112bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000113 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
114 bool Complain) {
115 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
116 Complain) ||
117 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
118 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000119}
120bool ChainedASTReaderListener::ReadPreprocessorOptions(
121 const PreprocessorOptions &PPOpts, bool Complain,
122 std::string &SuggestedPredefines) {
123 return First->ReadPreprocessorOptions(PPOpts, Complain,
124 SuggestedPredefines) ||
125 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
126}
127void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
128 unsigned Value) {
129 First->ReadCounter(M, Value);
130 Second->ReadCounter(M, Value);
131}
132bool ChainedASTReaderListener::needsInputFileVisitation() {
133 return First->needsInputFileVisitation() ||
134 Second->needsInputFileVisitation();
135}
136bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
137 return First->needsSystemInputFileVisitation() ||
138 Second->needsSystemInputFileVisitation();
139}
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000140void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
141 First->visitModuleFile(Filename);
142 Second->visitModuleFile(Filename);
143}
Ben Langmuircb69b572014-03-07 06:40:32 +0000144bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000145 bool isSystem,
146 bool isOverridden) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000147 bool Continue = false;
148 if (First->needsInputFileVisitation() &&
149 (!isSystem || First->needsSystemInputFileVisitation()))
150 Continue |= First->visitInputFile(Filename, isSystem, isOverridden);
151 if (Second->needsInputFileVisitation() &&
152 (!isSystem || Second->needsSystemInputFileVisitation()))
153 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden);
154 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000155}
156
Guy Benyei11169dd2012-12-18 14:30:41 +0000157//===----------------------------------------------------------------------===//
158// PCH validator implementation
159//===----------------------------------------------------------------------===//
160
161ASTReaderListener::~ASTReaderListener() {}
162
163/// \brief Compare the given set of language options against an existing set of
164/// language options.
165///
166/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000167/// \param AllowCompatibleDifferences If true, differences between compatible
168/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000169///
170/// \returns true if the languagae options mis-match, false otherwise.
171static bool checkLanguageOptions(const LangOptions &LangOpts,
172 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000173 DiagnosticsEngine *Diags,
174 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000175#define LANGOPT(Name, Bits, Default, Description) \
176 if (ExistingLangOpts.Name != LangOpts.Name) { \
177 if (Diags) \
178 Diags->Report(diag::err_pch_langopt_mismatch) \
179 << Description << LangOpts.Name << ExistingLangOpts.Name; \
180 return true; \
181 }
182
183#define VALUE_LANGOPT(Name, Bits, Default, Description) \
184 if (ExistingLangOpts.Name != LangOpts.Name) { \
185 if (Diags) \
186 Diags->Report(diag::err_pch_langopt_value_mismatch) \
187 << Description; \
188 return true; \
189 }
190
191#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
192 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
193 if (Diags) \
194 Diags->Report(diag::err_pch_langopt_value_mismatch) \
195 << Description; \
196 return true; \
197 }
198
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000199#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
200 if (!AllowCompatibleDifferences) \
201 LANGOPT(Name, Bits, Default, Description)
202
203#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
204 if (!AllowCompatibleDifferences) \
205 ENUM_LANGOPT(Name, Bits, Default, Description)
206
Guy Benyei11169dd2012-12-18 14:30:41 +0000207#define BENIGN_LANGOPT(Name, Bits, Default, Description)
208#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
209#include "clang/Basic/LangOptions.def"
210
211 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
212 if (Diags)
213 Diags->Report(diag::err_pch_langopt_value_mismatch)
214 << "target Objective-C runtime";
215 return true;
216 }
217
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000218 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
219 LangOpts.CommentOpts.BlockCommandNames) {
220 if (Diags)
221 Diags->Report(diag::err_pch_langopt_value_mismatch)
222 << "block command names";
223 return true;
224 }
225
Guy Benyei11169dd2012-12-18 14:30:41 +0000226 return false;
227}
228
229/// \brief Compare the given set of target options against an existing set of
230/// target options.
231///
232/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
233///
234/// \returns true if the target options mis-match, false otherwise.
235static bool checkTargetOptions(const TargetOptions &TargetOpts,
236 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000237 DiagnosticsEngine *Diags,
238 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000239#define CHECK_TARGET_OPT(Field, Name) \
240 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
241 if (Diags) \
242 Diags->Report(diag::err_pch_targetopt_mismatch) \
243 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
244 return true; \
245 }
246
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000247 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000248 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000249 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000250
251 // We can tolerate different CPUs in many cases, notably when one CPU
252 // supports a strict superset of another. When allowing compatible
253 // differences skip this check.
254 if (!AllowCompatibleDifferences)
255 CHECK_TARGET_OPT(CPU, "target CPU");
256
Guy Benyei11169dd2012-12-18 14:30:41 +0000257#undef CHECK_TARGET_OPT
258
259 // Compare feature sets.
260 SmallVector<StringRef, 4> ExistingFeatures(
261 ExistingTargetOpts.FeaturesAsWritten.begin(),
262 ExistingTargetOpts.FeaturesAsWritten.end());
263 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
264 TargetOpts.FeaturesAsWritten.end());
265 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
266 std::sort(ReadFeatures.begin(), ReadFeatures.end());
267
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000268 // We compute the set difference in both directions explicitly so that we can
269 // diagnose the differences differently.
270 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
271 std::set_difference(
272 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
273 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
274 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
275 ExistingFeatures.begin(), ExistingFeatures.end(),
276 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000277
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000278 // If we are allowing compatible differences and the read feature set is
279 // a strict subset of the existing feature set, there is nothing to diagnose.
280 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
281 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000282
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000283 if (Diags) {
284 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000285 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000286 << /* is-existing-feature */ false << Feature;
287 for (StringRef Feature : UnmatchedExistingFeatures)
288 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
289 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000290 }
291
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000292 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000293}
294
295bool
296PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000297 bool Complain,
298 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000299 const LangOptions &ExistingLangOpts = PP.getLangOpts();
300 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000301 Complain ? &Reader.Diags : nullptr,
302 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000303}
304
305bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000306 bool Complain,
307 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000308 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
309 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000310 Complain ? &Reader.Diags : nullptr,
311 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000312}
313
314namespace {
315 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
316 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000317 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
318 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000319}
320
Ben Langmuirb92de022014-04-29 16:25:26 +0000321static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
322 DiagnosticsEngine &Diags,
323 bool Complain) {
324 typedef DiagnosticsEngine::Level Level;
325
326 // Check current mappings for new -Werror mappings, and the stored mappings
327 // for cases that were explicitly mapped to *not* be errors that are now
328 // errors because of options like -Werror.
329 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
330
331 for (DiagnosticsEngine *MappingSource : MappingSources) {
332 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
333 diag::kind DiagID = DiagIDMappingPair.first;
334 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
335 if (CurLevel < DiagnosticsEngine::Error)
336 continue; // not significant
337 Level StoredLevel =
338 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
339 if (StoredLevel < DiagnosticsEngine::Error) {
340 if (Complain)
341 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
342 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
343 return true;
344 }
345 }
346 }
347
348 return false;
349}
350
Alp Tokerac4e8e52014-06-22 21:58:33 +0000351static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
352 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
353 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
354 return true;
355 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000356}
357
358static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
359 DiagnosticsEngine &Diags,
360 bool IsSystem, bool Complain) {
361 // Top-level options
362 if (IsSystem) {
363 if (Diags.getSuppressSystemWarnings())
364 return false;
365 // If -Wsystem-headers was not enabled before, be conservative
366 if (StoredDiags.getSuppressSystemWarnings()) {
367 if (Complain)
368 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
369 return true;
370 }
371 }
372
373 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
374 if (Complain)
375 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
376 return true;
377 }
378
379 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
380 !StoredDiags.getEnableAllWarnings()) {
381 if (Complain)
382 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
383 return true;
384 }
385
386 if (isExtHandlingFromDiagsError(Diags) &&
387 !isExtHandlingFromDiagsError(StoredDiags)) {
388 if (Complain)
389 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
390 return true;
391 }
392
393 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
394}
395
396bool PCHValidator::ReadDiagnosticOptions(
397 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
398 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
399 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
400 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000401 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000402 // This should never fail, because we would have processed these options
403 // before writing them to an ASTFile.
404 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
405
406 ModuleManager &ModuleMgr = Reader.getModuleManager();
407 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
408
409 // If the original import came from a file explicitly generated by the user,
410 // don't check the diagnostic mappings.
411 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000412 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000413 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
414 // the transitive closure of its imports, since unrelated modules cannot be
415 // imported until after this module finishes validation.
416 ModuleFile *TopImport = *ModuleMgr.rbegin();
417 while (!TopImport->ImportedBy.empty())
418 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000419 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000420 return false;
421
422 StringRef ModuleName = TopImport->ModuleName;
423 assert(!ModuleName.empty() && "diagnostic options read before module name");
424
425 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
426 assert(M && "missing module");
427
428 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
429 // contains the union of their flags.
430 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
431}
432
Guy Benyei11169dd2012-12-18 14:30:41 +0000433/// \brief Collect the macro definitions provided by the given preprocessor
434/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000435static void
436collectMacroDefinitions(const PreprocessorOptions &PPOpts,
437 MacroDefinitionsMap &Macros,
438 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000439 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
440 StringRef Macro = PPOpts.Macros[I].first;
441 bool IsUndef = PPOpts.Macros[I].second;
442
443 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
444 StringRef MacroName = MacroPair.first;
445 StringRef MacroBody = MacroPair.second;
446
447 // For an #undef'd macro, we only care about the name.
448 if (IsUndef) {
449 if (MacroNames && !Macros.count(MacroName))
450 MacroNames->push_back(MacroName);
451
452 Macros[MacroName] = std::make_pair("", true);
453 continue;
454 }
455
456 // For a #define'd macro, figure out the actual definition.
457 if (MacroName.size() == Macro.size())
458 MacroBody = "1";
459 else {
460 // Note: GCC drops anything following an end-of-line character.
461 StringRef::size_type End = MacroBody.find_first_of("\n\r");
462 MacroBody = MacroBody.substr(0, End);
463 }
464
465 if (MacroNames && !Macros.count(MacroName))
466 MacroNames->push_back(MacroName);
467 Macros[MacroName] = std::make_pair(MacroBody, false);
468 }
469}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000470
Guy Benyei11169dd2012-12-18 14:30:41 +0000471/// \brief Check the preprocessor options deserialized from the control block
472/// against the preprocessor options in an existing preprocessor.
473///
474/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
475static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
476 const PreprocessorOptions &ExistingPPOpts,
477 DiagnosticsEngine *Diags,
478 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000479 std::string &SuggestedPredefines,
480 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000481 // Check macro definitions.
482 MacroDefinitionsMap ASTFileMacros;
483 collectMacroDefinitions(PPOpts, ASTFileMacros);
484 MacroDefinitionsMap ExistingMacros;
485 SmallVector<StringRef, 4> ExistingMacroNames;
486 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
487
488 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
489 // Dig out the macro definition in the existing preprocessor options.
490 StringRef MacroName = ExistingMacroNames[I];
491 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
492
493 // Check whether we know anything about this macro name or not.
494 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
495 = ASTFileMacros.find(MacroName);
496 if (Known == ASTFileMacros.end()) {
497 // FIXME: Check whether this identifier was referenced anywhere in the
498 // AST file. If so, we should reject the AST file. Unfortunately, this
499 // information isn't in the control block. What shall we do about it?
500
501 if (Existing.second) {
502 SuggestedPredefines += "#undef ";
503 SuggestedPredefines += MacroName.str();
504 SuggestedPredefines += '\n';
505 } else {
506 SuggestedPredefines += "#define ";
507 SuggestedPredefines += MacroName.str();
508 SuggestedPredefines += ' ';
509 SuggestedPredefines += Existing.first.str();
510 SuggestedPredefines += '\n';
511 }
512 continue;
513 }
514
515 // If the macro was defined in one but undef'd in the other, we have a
516 // conflict.
517 if (Existing.second != Known->second.second) {
518 if (Diags) {
519 Diags->Report(diag::err_pch_macro_def_undef)
520 << MacroName << Known->second.second;
521 }
522 return true;
523 }
524
525 // If the macro was #undef'd in both, or if the macro bodies are identical,
526 // it's fine.
527 if (Existing.second || Existing.first == Known->second.first)
528 continue;
529
530 // The macro bodies differ; complain.
531 if (Diags) {
532 Diags->Report(diag::err_pch_macro_def_conflict)
533 << MacroName << Known->second.first << Existing.first;
534 }
535 return true;
536 }
537
538 // Check whether we're using predefines.
539 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
540 if (Diags) {
541 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
542 }
543 return true;
544 }
545
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000546 // Detailed record is important since it is used for the module cache hash.
547 if (LangOpts.Modules &&
548 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
549 if (Diags) {
550 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
551 }
552 return true;
553 }
554
Guy Benyei11169dd2012-12-18 14:30:41 +0000555 // Compute the #include and #include_macros lines we need.
556 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
557 StringRef File = ExistingPPOpts.Includes[I];
558 if (File == ExistingPPOpts.ImplicitPCHInclude)
559 continue;
560
561 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
562 != PPOpts.Includes.end())
563 continue;
564
565 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000566 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000567 SuggestedPredefines += "\"\n";
568 }
569
570 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
571 StringRef File = ExistingPPOpts.MacroIncludes[I];
572 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
573 File)
574 != PPOpts.MacroIncludes.end())
575 continue;
576
577 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000578 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000579 SuggestedPredefines += "\"\n##\n";
580 }
581
582 return false;
583}
584
585bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
586 bool Complain,
587 std::string &SuggestedPredefines) {
588 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
589
590 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000591 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000592 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000593 SuggestedPredefines,
594 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000595}
596
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000597/// Check the header search options deserialized from the control block
598/// against the header search options in an existing preprocessor.
599///
600/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
601static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
602 StringRef SpecificModuleCachePath,
603 StringRef ExistingModuleCachePath,
604 DiagnosticsEngine *Diags,
605 const LangOptions &LangOpts) {
606 if (LangOpts.Modules) {
607 if (SpecificModuleCachePath != ExistingModuleCachePath) {
608 if (Diags)
609 Diags->Report(diag::err_pch_modulecache_mismatch)
610 << SpecificModuleCachePath << ExistingModuleCachePath;
611 return true;
612 }
613 }
614
615 return false;
616}
617
618bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
619 StringRef SpecificModuleCachePath,
620 bool Complain) {
621 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
622 PP.getHeaderSearchInfo().getModuleCachePath(),
623 Complain ? &Reader.Diags : nullptr,
624 PP.getLangOpts());
625}
626
Guy Benyei11169dd2012-12-18 14:30:41 +0000627void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
628 PP.setCounterValue(Value);
629}
630
631//===----------------------------------------------------------------------===//
632// AST reader implementation
633//===----------------------------------------------------------------------===//
634
Nico Weber824285e2014-05-08 04:26:47 +0000635void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
636 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000637 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000638 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000639}
640
641
642
643unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
644 return serialization::ComputeHash(Sel);
645}
646
647
648std::pair<unsigned, unsigned>
649ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000650 using namespace llvm::support;
651 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
652 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000653 return std::make_pair(KeyLen, DataLen);
654}
655
656ASTSelectorLookupTrait::internal_key_type
657ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000658 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000659 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000660 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
661 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
662 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000663 if (N == 0)
664 return SelTable.getNullarySelector(FirstII);
665 else if (N == 1)
666 return SelTable.getUnarySelector(FirstII);
667
668 SmallVector<IdentifierInfo *, 16> Args;
669 Args.push_back(FirstII);
670 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000671 Args.push_back(Reader.getLocalIdentifier(
672 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000673
674 return SelTable.getSelector(N, Args.data());
675}
676
677ASTSelectorLookupTrait::data_type
678ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
679 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000680 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000681
682 data_type Result;
683
Justin Bogner57ba0b22014-03-28 22:03:24 +0000684 Result.ID = Reader.getGlobalSelectorID(
685 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000686 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
687 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
688 Result.InstanceBits = FullInstanceBits & 0x3;
689 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
690 Result.FactoryBits = FullFactoryBits & 0x3;
691 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
692 unsigned NumInstanceMethods = FullInstanceBits >> 3;
693 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000694
695 // Load instance methods
696 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000697 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
698 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000699 Result.Instance.push_back(Method);
700 }
701
702 // Load factory methods
703 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000704 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
705 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000706 Result.Factory.push_back(Method);
707 }
708
709 return Result;
710}
711
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000712unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
713 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000714}
715
716std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000717ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000718 using namespace llvm::support;
719 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
720 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000721 return std::make_pair(KeyLen, DataLen);
722}
723
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000724ASTIdentifierLookupTraitBase::internal_key_type
725ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000726 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000727 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000728}
729
Douglas Gregordcf25082013-02-11 18:16:18 +0000730/// \brief Whether the given identifier is "interesting".
731static bool isInterestingIdentifier(IdentifierInfo &II) {
732 return II.isPoisoned() ||
733 II.isExtensionToken() ||
734 II.getObjCOrBuiltinID() ||
735 II.hasRevertedTokenIDToIdentifier() ||
736 II.hadMacroDefinition() ||
737 II.getFETokenInfo<void>();
738}
739
Guy Benyei11169dd2012-12-18 14:30:41 +0000740IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
741 const unsigned char* d,
742 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000743 using namespace llvm::support;
744 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000745 bool IsInteresting = RawID & 0x01;
746
747 // Wipe out the "is interesting" bit.
748 RawID = RawID >> 1;
749
750 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
751 if (!IsInteresting) {
752 // For uninteresting identifiers, just build the IdentifierInfo
753 // and associate it with the persistent ID.
754 IdentifierInfo *II = KnownII;
755 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000756 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000757 KnownII = II;
758 }
759 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000760 if (!II->isFromAST()) {
761 bool WasInteresting = isInterestingIdentifier(*II);
762 II->setIsFromAST();
763 if (WasInteresting)
764 II->setChangedSinceDeserialization();
765 }
766 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000767 return II;
768 }
769
Justin Bogner57ba0b22014-03-28 22:03:24 +0000770 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
771 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000772 bool CPlusPlusOperatorKeyword = Bits & 0x01;
773 Bits >>= 1;
774 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
775 Bits >>= 1;
776 bool Poisoned = Bits & 0x01;
777 Bits >>= 1;
778 bool ExtensionToken = Bits & 0x01;
779 Bits >>= 1;
780 bool hadMacroDefinition = Bits & 0x01;
781 Bits >>= 1;
782
783 assert(Bits == 0 && "Extra bits in the identifier?");
784 DataLen -= 8;
785
786 // Build the IdentifierInfo itself and link the identifier ID with
787 // the new IdentifierInfo.
788 IdentifierInfo *II = KnownII;
789 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000790 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000791 KnownII = II;
792 }
793 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000794 if (!II->isFromAST()) {
795 bool WasInteresting = isInterestingIdentifier(*II);
796 II->setIsFromAST();
797 if (WasInteresting)
798 II->setChangedSinceDeserialization();
799 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000800
801 // Set or check the various bits in the IdentifierInfo structure.
802 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000803 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000804 II->RevertTokenIDToIdentifier();
805 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
806 assert(II->isExtensionToken() == ExtensionToken &&
807 "Incorrect extension token flag");
808 (void)ExtensionToken;
809 if (Poisoned)
810 II->setIsPoisoned(true);
811 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
812 "Incorrect C++ operator keyword flag");
813 (void)CPlusPlusOperatorKeyword;
814
815 // If this identifier is a macro, deserialize the macro
816 // definition.
817 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000818 uint32_t MacroDirectivesOffset =
819 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000820 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000821
Richard Smithd7329392015-04-21 21:46:32 +0000822 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000823 }
824
825 Reader.SetIdentifierInfo(ID, II);
826
827 // Read all of the declarations visible at global scope with this
828 // name.
829 if (DataLen > 0) {
830 SmallVector<uint32_t, 4> DeclIDs;
831 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000832 DeclIDs.push_back(Reader.getGlobalDeclID(
833 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000834 Reader.SetGloballyVisibleDecls(II, DeclIDs);
835 }
836
837 return II;
838}
839
840unsigned
841ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
842 llvm::FoldingSetNodeID ID;
843 ID.AddInteger(Key.Kind);
844
845 switch (Key.Kind) {
846 case DeclarationName::Identifier:
847 case DeclarationName::CXXLiteralOperatorName:
848 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
849 break;
850 case DeclarationName::ObjCZeroArgSelector:
851 case DeclarationName::ObjCOneArgSelector:
852 case DeclarationName::ObjCMultiArgSelector:
853 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
854 break;
855 case DeclarationName::CXXOperatorName:
856 ID.AddInteger((OverloadedOperatorKind)Key.Data);
857 break;
858 case DeclarationName::CXXConstructorName:
859 case DeclarationName::CXXDestructorName:
860 case DeclarationName::CXXConversionFunctionName:
861 case DeclarationName::CXXUsingDirective:
862 break;
863 }
864
865 return ID.ComputeHash();
866}
867
868ASTDeclContextNameLookupTrait::internal_key_type
869ASTDeclContextNameLookupTrait::GetInternalKey(
870 const external_key_type& Name) const {
871 DeclNameKey Key;
872 Key.Kind = Name.getNameKind();
873 switch (Name.getNameKind()) {
874 case DeclarationName::Identifier:
875 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
876 break;
877 case DeclarationName::ObjCZeroArgSelector:
878 case DeclarationName::ObjCOneArgSelector:
879 case DeclarationName::ObjCMultiArgSelector:
880 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
881 break;
882 case DeclarationName::CXXOperatorName:
883 Key.Data = Name.getCXXOverloadedOperator();
884 break;
885 case DeclarationName::CXXLiteralOperatorName:
886 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
887 break;
888 case DeclarationName::CXXConstructorName:
889 case DeclarationName::CXXDestructorName:
890 case DeclarationName::CXXConversionFunctionName:
891 case DeclarationName::CXXUsingDirective:
892 Key.Data = 0;
893 break;
894 }
895
896 return Key;
897}
898
899std::pair<unsigned, unsigned>
900ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000901 using namespace llvm::support;
902 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
903 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000904 return std::make_pair(KeyLen, DataLen);
905}
906
907ASTDeclContextNameLookupTrait::internal_key_type
908ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000909 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000910
911 DeclNameKey Key;
912 Key.Kind = (DeclarationName::NameKind)*d++;
913 switch (Key.Kind) {
914 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000915 Key.Data = (uint64_t)Reader.getLocalIdentifier(
916 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000917 break;
918 case DeclarationName::ObjCZeroArgSelector:
919 case DeclarationName::ObjCOneArgSelector:
920 case DeclarationName::ObjCMultiArgSelector:
921 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000922 (uint64_t)Reader.getLocalSelector(
923 F, endian::readNext<uint32_t, little, unaligned>(
924 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000925 break;
926 case DeclarationName::CXXOperatorName:
927 Key.Data = *d++; // OverloadedOperatorKind
928 break;
929 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000930 Key.Data = (uint64_t)Reader.getLocalIdentifier(
931 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000932 break;
933 case DeclarationName::CXXConstructorName:
934 case DeclarationName::CXXDestructorName:
935 case DeclarationName::CXXConversionFunctionName:
936 case DeclarationName::CXXUsingDirective:
937 Key.Data = 0;
938 break;
939 }
940
941 return Key;
942}
943
944ASTDeclContextNameLookupTrait::data_type
945ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
946 const unsigned char* d,
947 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000948 using namespace llvm::support;
949 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000950 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
951 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000952 return std::make_pair(Start, Start + NumDecls);
953}
954
955bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000956 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000957 const std::pair<uint64_t, uint64_t> &Offsets,
958 DeclContextInfo &Info) {
959 SavedStreamPosition SavedPosition(Cursor);
960 // First the lexical decls.
961 if (Offsets.first != 0) {
962 Cursor.JumpToBit(Offsets.first);
963
964 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000965 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000966 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000967 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000968 if (RecCode != DECL_CONTEXT_LEXICAL) {
969 Error("Expected lexical block");
970 return true;
971 }
972
Chris Lattner0e6c9402013-01-20 02:38:54 +0000973 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
974 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000975 }
976
977 // Now the lookup table.
978 if (Offsets.second != 0) {
979 Cursor.JumpToBit(Offsets.second);
980
981 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000982 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000983 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000984 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000985 if (RecCode != DECL_CONTEXT_VISIBLE) {
986 Error("Expected visible lookup table block");
987 return true;
988 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000989 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
990 (const unsigned char *)Blob.data() + Record[0],
991 (const unsigned char *)Blob.data() + sizeof(uint32_t),
992 (const unsigned char *)Blob.data(),
993 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +0000994 }
995
996 return false;
997}
998
999void ASTReader::Error(StringRef Msg) {
1000 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +00001001 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
1002 Diag(diag::note_module_cache_path)
1003 << PP.getHeaderSearchInfo().getModuleCachePath();
1004 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001005}
1006
1007void ASTReader::Error(unsigned DiagID,
1008 StringRef Arg1, StringRef Arg2) {
1009 if (Diags.isDiagnosticInFlight())
1010 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1011 else
1012 Diag(DiagID) << Arg1 << Arg2;
1013}
1014
1015//===----------------------------------------------------------------------===//
1016// Source Manager Deserialization
1017//===----------------------------------------------------------------------===//
1018
1019/// \brief Read the line table in the source manager block.
1020/// \returns true if there was an error.
1021bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001022 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001023 unsigned Idx = 0;
1024 LineTableInfo &LineTable = SourceMgr.getLineTable();
1025
1026 // Parse the file names
1027 std::map<int, int> FileIDs;
1028 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1029 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001030 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001031 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1032 }
1033
1034 // Parse the line entries
1035 std::vector<LineEntry> Entries;
1036 while (Idx < Record.size()) {
1037 int FID = Record[Idx++];
1038 assert(FID >= 0 && "Serialized line entries for non-local file.");
1039 // Remap FileID from 1-based old view.
1040 FID += F.SLocEntryBaseID - 1;
1041
1042 // Extract the line entries
1043 unsigned NumEntries = Record[Idx++];
1044 assert(NumEntries && "Numentries is 00000");
1045 Entries.clear();
1046 Entries.reserve(NumEntries);
1047 for (unsigned I = 0; I != NumEntries; ++I) {
1048 unsigned FileOffset = Record[Idx++];
1049 unsigned LineNo = Record[Idx++];
1050 int FilenameID = FileIDs[Record[Idx++]];
1051 SrcMgr::CharacteristicKind FileKind
1052 = (SrcMgr::CharacteristicKind)Record[Idx++];
1053 unsigned IncludeOffset = Record[Idx++];
1054 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1055 FileKind, IncludeOffset));
1056 }
1057 LineTable.AddEntry(FileID::get(FID), Entries);
1058 }
1059
1060 return false;
1061}
1062
1063/// \brief Read a source manager block
1064bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1065 using namespace SrcMgr;
1066
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001067 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001068
1069 // Set the source-location entry cursor to the current position in
1070 // the stream. This cursor will be used to read the contents of the
1071 // source manager block initially, and then lazily read
1072 // source-location entries as needed.
1073 SLocEntryCursor = F.Stream;
1074
1075 // The stream itself is going to skip over the source manager block.
1076 if (F.Stream.SkipBlock()) {
1077 Error("malformed block record in AST file");
1078 return true;
1079 }
1080
1081 // Enter the source manager block.
1082 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1083 Error("malformed source manager block record in AST file");
1084 return true;
1085 }
1086
1087 RecordData Record;
1088 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001089 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1090
1091 switch (E.Kind) {
1092 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1093 case llvm::BitstreamEntry::Error:
1094 Error("malformed block record in AST file");
1095 return true;
1096 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001097 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001098 case llvm::BitstreamEntry::Record:
1099 // The interesting case.
1100 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001101 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001102
Guy Benyei11169dd2012-12-18 14:30:41 +00001103 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001104 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001105 StringRef Blob;
1106 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001107 default: // Default behavior: ignore.
1108 break;
1109
1110 case SM_SLOC_FILE_ENTRY:
1111 case SM_SLOC_BUFFER_ENTRY:
1112 case SM_SLOC_EXPANSION_ENTRY:
1113 // Once we hit one of the source location entries, we're done.
1114 return false;
1115 }
1116 }
1117}
1118
1119/// \brief If a header file is not found at the path that we expect it to be
1120/// and the PCH file was moved from its original location, try to resolve the
1121/// file by assuming that header+PCH were moved together and the header is in
1122/// the same place relative to the PCH.
1123static std::string
1124resolveFileRelativeToOriginalDir(const std::string &Filename,
1125 const std::string &OriginalDir,
1126 const std::string &CurrDir) {
1127 assert(OriginalDir != CurrDir &&
1128 "No point trying to resolve the file if the PCH dir didn't change");
1129 using namespace llvm::sys;
1130 SmallString<128> filePath(Filename);
1131 fs::make_absolute(filePath);
1132 assert(path::is_absolute(OriginalDir));
1133 SmallString<128> currPCHPath(CurrDir);
1134
1135 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1136 fileDirE = path::end(path::parent_path(filePath));
1137 path::const_iterator origDirI = path::begin(OriginalDir),
1138 origDirE = path::end(OriginalDir);
1139 // Skip the common path components from filePath and OriginalDir.
1140 while (fileDirI != fileDirE && origDirI != origDirE &&
1141 *fileDirI == *origDirI) {
1142 ++fileDirI;
1143 ++origDirI;
1144 }
1145 for (; origDirI != origDirE; ++origDirI)
1146 path::append(currPCHPath, "..");
1147 path::append(currPCHPath, fileDirI, fileDirE);
1148 path::append(currPCHPath, path::filename(Filename));
1149 return currPCHPath.str();
1150}
1151
1152bool ASTReader::ReadSLocEntry(int ID) {
1153 if (ID == 0)
1154 return false;
1155
1156 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1157 Error("source location entry ID out-of-range for AST file");
1158 return true;
1159 }
1160
1161 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1162 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001163 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001164 unsigned BaseOffset = F->SLocEntryBaseOffset;
1165
1166 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001167 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1168 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001169 Error("incorrectly-formatted source location entry in AST file");
1170 return true;
1171 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001172
Guy Benyei11169dd2012-12-18 14:30:41 +00001173 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001174 StringRef Blob;
1175 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001176 default:
1177 Error("incorrectly-formatted source location entry in AST file");
1178 return true;
1179
1180 case SM_SLOC_FILE_ENTRY: {
1181 // We will detect whether a file changed and return 'Failure' for it, but
1182 // we will also try to fail gracefully by setting up the SLocEntry.
1183 unsigned InputID = Record[4];
1184 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001185 const FileEntry *File = IF.getFile();
1186 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001187
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001188 // Note that we only check if a File was returned. If it was out-of-date
1189 // we have complained but we will continue creating a FileID to recover
1190 // gracefully.
1191 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001192 return true;
1193
1194 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1195 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1196 // This is the module's main file.
1197 IncludeLoc = getImportLocation(F);
1198 }
1199 SrcMgr::CharacteristicKind
1200 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1201 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1202 ID, BaseOffset + Record[0]);
1203 SrcMgr::FileInfo &FileInfo =
1204 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1205 FileInfo.NumCreatedFIDs = Record[5];
1206 if (Record[3])
1207 FileInfo.setHasLineDirectives();
1208
1209 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1210 unsigned NumFileDecls = Record[7];
1211 if (NumFileDecls) {
1212 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1213 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1214 NumFileDecls));
1215 }
1216
1217 const SrcMgr::ContentCache *ContentCache
1218 = SourceMgr.getOrCreateContentCache(File,
1219 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1220 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1221 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1222 unsigned Code = SLocEntryCursor.ReadCode();
1223 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001224 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001225
1226 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1227 Error("AST record has invalid code");
1228 return true;
1229 }
1230
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001231 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001232 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001233 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001234 }
1235
1236 break;
1237 }
1238
1239 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001240 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001241 unsigned Offset = Record[0];
1242 SrcMgr::CharacteristicKind
1243 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1244 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001245 if (IncludeLoc.isInvalid() &&
1246 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001247 IncludeLoc = getImportLocation(F);
1248 }
1249 unsigned Code = SLocEntryCursor.ReadCode();
1250 Record.clear();
1251 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001252 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001253
1254 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1255 Error("AST record has invalid code");
1256 return true;
1257 }
1258
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001259 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1260 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001261 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001262 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001263 break;
1264 }
1265
1266 case SM_SLOC_EXPANSION_ENTRY: {
1267 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1268 SourceMgr.createExpansionLoc(SpellingLoc,
1269 ReadSourceLocation(*F, Record[2]),
1270 ReadSourceLocation(*F, Record[3]),
1271 Record[4],
1272 ID,
1273 BaseOffset + Record[0]);
1274 break;
1275 }
1276 }
1277
1278 return false;
1279}
1280
1281std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1282 if (ID == 0)
1283 return std::make_pair(SourceLocation(), "");
1284
1285 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1286 Error("source location entry ID out-of-range for AST file");
1287 return std::make_pair(SourceLocation(), "");
1288 }
1289
1290 // Find which module file this entry lands in.
1291 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001292 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001293 return std::make_pair(SourceLocation(), "");
1294
1295 // FIXME: Can we map this down to a particular submodule? That would be
1296 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001297 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001298}
1299
1300/// \brief Find the location where the module F is imported.
1301SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1302 if (F->ImportLoc.isValid())
1303 return F->ImportLoc;
1304
1305 // Otherwise we have a PCH. It's considered to be "imported" at the first
1306 // location of its includer.
1307 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001308 // Main file is the importer.
1309 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1310 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001311 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001312 return F->ImportedBy[0]->FirstLoc;
1313}
1314
1315/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1316/// specified cursor. Read the abbreviations that are at the top of the block
1317/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001318bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001319 if (Cursor.EnterSubBlock(BlockID)) {
1320 Error("malformed block record in AST file");
1321 return Failure;
1322 }
1323
1324 while (true) {
1325 uint64_t Offset = Cursor.GetCurrentBitNo();
1326 unsigned Code = Cursor.ReadCode();
1327
1328 // We expect all abbrevs to be at the start of the block.
1329 if (Code != llvm::bitc::DEFINE_ABBREV) {
1330 Cursor.JumpToBit(Offset);
1331 return false;
1332 }
1333 Cursor.ReadAbbrevRecord();
1334 }
1335}
1336
Richard Smithe40f2ba2013-08-07 21:41:30 +00001337Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001338 unsigned &Idx) {
1339 Token Tok;
1340 Tok.startToken();
1341 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1342 Tok.setLength(Record[Idx++]);
1343 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1344 Tok.setIdentifierInfo(II);
1345 Tok.setKind((tok::TokenKind)Record[Idx++]);
1346 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1347 return Tok;
1348}
1349
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001350MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001351 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001352
1353 // Keep track of where we are in the stream, then jump back there
1354 // after reading this macro.
1355 SavedStreamPosition SavedPosition(Stream);
1356
1357 Stream.JumpToBit(Offset);
1358 RecordData Record;
1359 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001360 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001361
Guy Benyei11169dd2012-12-18 14:30:41 +00001362 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001363 // Advance to the next record, but if we get to the end of the block, don't
1364 // pop it (removing all the abbreviations from the cursor) since we want to
1365 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001366 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001367 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1368
1369 switch (Entry.Kind) {
1370 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1371 case llvm::BitstreamEntry::Error:
1372 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001373 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001374 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001375 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001376 case llvm::BitstreamEntry::Record:
1377 // The interesting case.
1378 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001379 }
1380
1381 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001382 Record.clear();
1383 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001384 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001385 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001386 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001387 case PP_MACRO_DIRECTIVE_HISTORY:
1388 return Macro;
1389
Guy Benyei11169dd2012-12-18 14:30:41 +00001390 case PP_MACRO_OBJECT_LIKE:
1391 case PP_MACRO_FUNCTION_LIKE: {
1392 // If we already have a macro, that means that we've hit the end
1393 // of the definition of the macro we were looking for. We're
1394 // done.
1395 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001396 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001397
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001398 unsigned NextIndex = 1; // Skip identifier ID.
1399 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001400 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001401 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001402 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001403 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001404 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001405
Guy Benyei11169dd2012-12-18 14:30:41 +00001406 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1407 // Decode function-like macro info.
1408 bool isC99VarArgs = Record[NextIndex++];
1409 bool isGNUVarArgs = Record[NextIndex++];
1410 bool hasCommaPasting = Record[NextIndex++];
1411 MacroArgs.clear();
1412 unsigned NumArgs = Record[NextIndex++];
1413 for (unsigned i = 0; i != NumArgs; ++i)
1414 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1415
1416 // Install function-like macro info.
1417 MI->setIsFunctionLike();
1418 if (isC99VarArgs) MI->setIsC99Varargs();
1419 if (isGNUVarArgs) MI->setIsGNUVarargs();
1420 if (hasCommaPasting) MI->setHasCommaPasting();
1421 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1422 PP.getPreprocessorAllocator());
1423 }
1424
Guy Benyei11169dd2012-12-18 14:30:41 +00001425 // Remember that we saw this macro last so that we add the tokens that
1426 // form its body to it.
1427 Macro = MI;
1428
1429 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1430 Record[NextIndex]) {
1431 // We have a macro definition. Register the association
1432 PreprocessedEntityID
1433 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1434 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001435 PreprocessingRecord::PPEntityID
1436 PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1437 MacroDefinition *PPDef =
1438 cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1439 if (PPDef)
1440 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001441 }
1442
1443 ++NumMacrosRead;
1444 break;
1445 }
1446
1447 case PP_TOKEN: {
1448 // If we see a TOKEN before a PP_MACRO_*, then the file is
1449 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001450 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001451
John McCallf413f5e2013-05-03 00:10:13 +00001452 unsigned Idx = 0;
1453 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001454 Macro->AddTokenToBody(Tok);
1455 break;
1456 }
1457 }
1458 }
1459}
1460
1461PreprocessedEntityID
1462ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1463 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1464 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1465 assert(I != M.PreprocessedEntityRemap.end()
1466 && "Invalid index into preprocessed entity index remap");
1467
1468 return LocalID + I->second;
1469}
1470
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001471unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1472 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001473}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001474
Guy Benyei11169dd2012-12-18 14:30:41 +00001475HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001476HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1477 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
Richard Smith7ed1bc92014-12-05 22:42:13 +00001478 FE->getName(), /*Imported*/false };
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001479 return ikey;
1480}
Guy Benyei11169dd2012-12-18 14:30:41 +00001481
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001482bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1483 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001484 return false;
1485
Richard Smith7ed1bc92014-12-05 22:42:13 +00001486 if (llvm::sys::path::is_absolute(a.Filename) &&
1487 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001488 return true;
1489
Guy Benyei11169dd2012-12-18 14:30:41 +00001490 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001491 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001492 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1493 if (!Key.Imported)
1494 return FileMgr.getFile(Key.Filename);
1495
1496 std::string Resolved = Key.Filename;
1497 Reader.ResolveImportedPath(M, Resolved);
1498 return FileMgr.getFile(Resolved);
1499 };
1500
1501 const FileEntry *FEA = GetFile(a);
1502 const FileEntry *FEB = GetFile(b);
1503 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001504}
1505
1506std::pair<unsigned, unsigned>
1507HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001508 using namespace llvm::support;
1509 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001510 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001511 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001512}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001513
1514HeaderFileInfoTrait::internal_key_type
1515HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001516 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001517 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001518 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1519 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001520 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001521 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001522 return ikey;
1523}
1524
Guy Benyei11169dd2012-12-18 14:30:41 +00001525HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001526HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001527 unsigned DataLen) {
1528 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001529 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001530 HeaderFileInfo HFI;
1531 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001532 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1533 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001534 HFI.isImport = (Flags >> 5) & 0x01;
1535 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1536 HFI.DirInfo = (Flags >> 2) & 0x03;
1537 HFI.Resolved = (Flags >> 1) & 0x01;
1538 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001539 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1540 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1541 M, endian::readNext<uint32_t, little, unaligned>(d));
1542 if (unsigned FrameworkOffset =
1543 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001544 // The framework offset is 1 greater than the actual offset,
1545 // since 0 is used as an indicator for "no framework name".
1546 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1547 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1548 }
1549
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001550 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001551 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001552 if (LocalSMID) {
1553 // This header is part of a module. Associate it with the module to enable
1554 // implicit module import.
1555 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1556 Module *Mod = Reader.getSubmodule(GlobalSMID);
1557 HFI.isModuleHeader = true;
1558 FileManager &FileMgr = Reader.getFileManager();
1559 ModuleMap &ModMap =
1560 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001561 // FIXME: This information should be propagated through the
1562 // SUBMODULE_HEADER etc records rather than from here.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001563 // FIXME: We don't ever mark excluded headers.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001564 std::string Filename = key.Filename;
1565 if (key.Imported)
1566 Reader.ResolveImportedPath(M, Filename);
1567 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Hans Wennborg0101b542014-12-02 02:13:09 +00001568 ModMap.addHeader(Mod, H, HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001569 }
1570 }
1571
Guy Benyei11169dd2012-12-18 14:30:41 +00001572 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1573 (void)End;
1574
1575 // This HeaderFileInfo was externally loaded.
1576 HFI.External = true;
1577 return HFI;
1578}
1579
Richard Smithd7329392015-04-21 21:46:32 +00001580void ASTReader::addPendingMacro(IdentifierInfo *II,
1581 ModuleFile *M,
1582 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001583 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1584 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001585}
1586
1587void ASTReader::ReadDefinedMacros() {
1588 // Note that we are loading defined macros.
1589 Deserializing Macros(this);
1590
1591 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1592 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001593 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001594
1595 // If there was no preprocessor block, skip this file.
1596 if (!MacroCursor.getBitStreamReader())
1597 continue;
1598
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001599 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001600 Cursor.JumpToBit((*I)->MacroStartOffset);
1601
1602 RecordData Record;
1603 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001604 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1605
1606 switch (E.Kind) {
1607 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1608 case llvm::BitstreamEntry::Error:
1609 Error("malformed block record in AST file");
1610 return;
1611 case llvm::BitstreamEntry::EndBlock:
1612 goto NextCursor;
1613
1614 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001615 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001616 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001617 default: // Default behavior: ignore.
1618 break;
1619
1620 case PP_MACRO_OBJECT_LIKE:
1621 case PP_MACRO_FUNCTION_LIKE:
1622 getLocalIdentifier(**I, Record[0]);
1623 break;
1624
1625 case PP_TOKEN:
1626 // Ignore tokens.
1627 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001628 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001629 break;
1630 }
1631 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001632 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001633 }
1634}
1635
1636namespace {
1637 /// \brief Visitor class used to look up identifirs in an AST file.
1638 class IdentifierLookupVisitor {
1639 StringRef Name;
1640 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001641 unsigned &NumIdentifierLookups;
1642 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001643 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001644
Guy Benyei11169dd2012-12-18 14:30:41 +00001645 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001646 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1647 unsigned &NumIdentifierLookups,
1648 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001649 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001650 NumIdentifierLookups(NumIdentifierLookups),
1651 NumIdentifierLookupHits(NumIdentifierLookupHits),
1652 Found()
1653 {
1654 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001655
1656 static bool visit(ModuleFile &M, void *UserData) {
1657 IdentifierLookupVisitor *This
1658 = static_cast<IdentifierLookupVisitor *>(UserData);
1659
1660 // If we've already searched this module file, skip it now.
1661 if (M.Generation <= This->PriorGeneration)
1662 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001663
Guy Benyei11169dd2012-12-18 14:30:41 +00001664 ASTIdentifierLookupTable *IdTable
1665 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1666 if (!IdTable)
1667 return false;
1668
1669 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1670 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001671 ++This->NumIdentifierLookups;
1672 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001673 if (Pos == IdTable->end())
1674 return false;
1675
1676 // Dereferencing the iterator has the effect of building the
1677 // IdentifierInfo node and populating it with the various
1678 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001679 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001680 This->Found = *Pos;
1681 return true;
1682 }
1683
1684 // \brief Retrieve the identifier info found within the module
1685 // files.
1686 IdentifierInfo *getIdentifierInfo() const { return Found; }
1687 };
1688}
1689
1690void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1691 // Note that we are loading an identifier.
1692 Deserializing AnIdentifier(this);
1693
1694 unsigned PriorGeneration = 0;
1695 if (getContext().getLangOpts().Modules)
1696 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001697
1698 // If there is a global index, look there first to determine which modules
1699 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001700 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001701 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001702 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001703 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1704 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001705 }
1706 }
1707
Douglas Gregor7211ac12013-01-25 23:32:03 +00001708 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001709 NumIdentifierLookups,
1710 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001711 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001712 markIdentifierUpToDate(&II);
1713}
1714
1715void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1716 if (!II)
1717 return;
1718
1719 II->setOutOfDate(false);
1720
1721 // Update the generation for this identifier.
1722 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001723 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001724}
1725
Richard Smith49f906a2014-03-01 00:08:04 +00001726struct ASTReader::ModuleMacroInfo {
1727 SubmoduleID SubModID;
1728 MacroInfo *MI;
Richard Smithd7329392015-04-21 21:46:32 +00001729 ArrayRef<SubmoduleID> Overrides;
Richard Smith49f906a2014-03-01 00:08:04 +00001730 // FIXME: Remove this.
1731 ModuleFile *F;
1732
1733 bool isDefine() const { return MI; }
1734
1735 SubmoduleID getSubmoduleID() const { return SubModID; }
1736
Richard Smithd7329392015-04-21 21:46:32 +00001737 ArrayRef<SubmoduleID> getOverriddenSubmodules() const { return Overrides; }
Richard Smith49f906a2014-03-01 00:08:04 +00001738
Richard Smithdaa69e02014-07-25 04:40:03 +00001739 MacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
Richard Smith49f906a2014-03-01 00:08:04 +00001740 if (!MI)
Richard Smithdaa69e02014-07-25 04:40:03 +00001741 return PP.AllocateUndefMacroDirective(ImportLoc, SubModID,
1742 getOverriddenSubmodules());
1743 return PP.AllocateDefMacroDirective(MI, ImportLoc, SubModID,
1744 getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00001745 }
1746};
1747
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001748void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1749 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001750 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001751
1752 BitstreamCursor &Cursor = M.MacroCursor;
1753 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001754 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001755
Richard Smithd7329392015-04-21 21:46:32 +00001756 llvm::SmallVector<ModuleMacroInfo *, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001757
Richard Smithd7329392015-04-21 21:46:32 +00001758 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1759 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1760 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001761 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001762 while (true) {
1763 llvm::BitstreamEntry Entry =
1764 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1765 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1766 Error("malformed block record in AST file");
1767 return;
1768 }
1769
1770 Record.clear();
1771 switch (PreprocessorRecordTypes RecType =
1772 (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
1773 case PP_MACRO_DIRECTIVE_HISTORY:
1774 break;
1775
1776 case PP_MODULE_MACRO: {
1777 auto SubModID = getGlobalSubmoduleID(M, Record[0]);
1778 auto MacID = getGlobalMacroID(M, Record[1]);
1779
1780 // Check whether we've already loaded this module macro.
1781 // FIXME: The MacrosLoaded check is wrong: multiple macro definitions can
1782 // have the same MacroInfo (and the same MacID) due to #pragma pop_macro.
1783 if (MacID ? (bool)MacrosLoaded[MacID - NUM_PREDEF_MACRO_IDS]
1784 : !LoadedUndefs.insert(std::make_pair(II, SubModID)).second)
1785 continue;
1786
1787 ModuleMacroInfo Info;
1788 Info.SubModID = SubModID;
1789 Info.MI = getMacro(MacID);
1790 Info.F = &M;
1791
1792 if (Record.size() > 2) {
1793 auto *Overrides = new (Context) SubmoduleID[Record.size() - 2];
1794 for (int I = 2, N = Record.size(); I != N; ++I)
1795 Overrides[I - 2] = getGlobalSubmoduleID(M, Record[I]);
1796 Info.Overrides =
1797 llvm::makeArrayRef(Overrides, Overrides + Record.size() - 2);
1798 }
1799
1800 ModuleMacros.push_back(new (Context) ModuleMacroInfo(Info));
1801 continue;
1802 }
1803
1804 default:
1805 Error("malformed block record in AST file");
1806 return;
1807 }
1808
1809 // We found the macro directive history; that's the last record
1810 // for this macro.
1811 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001812 }
1813
Richard Smithd7329392015-04-21 21:46:32 +00001814 // Module macros are listed in reverse dependency order.
1815 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
1816 for (auto *MMI : ModuleMacros) {
1817 Module *Owner = getSubmodule(MMI->getSubmoduleID());
1818 if (Owner && Owner->NameVisibility == Module::Hidden) {
1819 // Macros in the owning module are hidden. Just remember this macro to
1820 // install if we make this module visible.
1821 HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1822 } else {
1823 installImportedMacro(II, MMI, Owner);
1824 }
1825 }
1826
1827 // Don't read the directive history for a module; we don't have anywhere
1828 // to put it.
1829 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1830 return;
1831
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001832 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001833 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001834 unsigned Idx = 0, N = Record.size();
1835 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001836 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001837 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001838 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1839 switch (K) {
1840 case MacroDirective::MD_Define: {
1841 GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1842 MacroInfo *MI = getMacro(GMacID);
Richard Smithd7329392015-04-21 21:46:32 +00001843 SubmoduleID ImportedFrom = getGlobalSubmoduleID(M, Record[Idx++]);
Richard Smithdaa69e02014-07-25 04:40:03 +00001844 bool IsAmbiguous = Record[Idx++];
1845 llvm::SmallVector<unsigned, 4> Overrides;
1846 if (ImportedFrom) {
1847 Overrides.insert(Overrides.end(),
1848 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
Richard Smithd7329392015-04-21 21:46:32 +00001849 for (auto &ID : Overrides)
1850 ID = getGlobalSubmoduleID(M, ID);
Richard Smithdaa69e02014-07-25 04:40:03 +00001851 Idx += Overrides.size() + 1;
1852 }
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001853 DefMacroDirective *DefMD =
Richard Smithdaa69e02014-07-25 04:40:03 +00001854 PP.AllocateDefMacroDirective(MI, Loc, ImportedFrom, Overrides);
1855 DefMD->setAmbiguous(IsAmbiguous);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001856 MD = DefMD;
1857 break;
1858 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001859 case MacroDirective::MD_Undefine: {
Richard Smithd7329392015-04-21 21:46:32 +00001860 SubmoduleID ImportedFrom = getGlobalSubmoduleID(M, Record[Idx++]);
Richard Smithdaa69e02014-07-25 04:40:03 +00001861 llvm::SmallVector<unsigned, 4> Overrides;
1862 if (ImportedFrom) {
1863 Overrides.insert(Overrides.end(),
1864 &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
Richard Smithd7329392015-04-21 21:46:32 +00001865 for (auto &ID : Overrides)
1866 ID = getGlobalSubmoduleID(M, ID);
Richard Smithdaa69e02014-07-25 04:40:03 +00001867 Idx += Overrides.size() + 1;
1868 }
1869 MD = PP.AllocateUndefMacroDirective(Loc, ImportedFrom, Overrides);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001870 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001871 }
1872 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001873 bool isPublic = Record[Idx++];
1874 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1875 break;
1876 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001877
1878 if (!Latest)
1879 Latest = MD;
1880 if (Earliest)
1881 Earliest->setPrevious(MD);
1882 Earliest = MD;
1883 }
1884
1885 PP.setLoadedMacroDirective(II, Latest);
1886}
1887
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001888/// \brief For the given macro definitions, check if they are both in system
Douglas Gregor0b202052013-04-12 21:00:54 +00001889/// modules.
1890static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
Douglas Gregor5e461192013-06-07 22:56:11 +00001891 Module *NewOwner, ASTReader &Reader) {
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001892 assert(PrevMI && NewMI);
Craig Toppera13603a2014-05-22 05:54:18 +00001893 Module *PrevOwner = nullptr;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001894 if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1895 PrevOwner = Reader.getSubmodule(PrevModID);
Douglas Gregor5e461192013-06-07 22:56:11 +00001896 if (PrevOwner && PrevOwner == NewOwner)
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001897 return false;
Chandler Carruthc2132d82015-03-13 08:29:54 +00001898 SourceManager &SrcMgr = Reader.getSourceManager();
1899 bool PrevInSystem = (PrevOwner && PrevOwner->IsSystem) ||
1900 SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1901 bool NewInSystem = (NewOwner && NewOwner->IsSystem) ||
1902 SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
Douglas Gregor5e461192013-06-07 22:56:11 +00001903 return PrevInSystem && NewInSystem;
Argyrios Kyrtzidis3a9c42c2013-03-27 01:25:34 +00001904}
1905
Richard Smith49f906a2014-03-01 00:08:04 +00001906void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001907 SourceLocation ImportLoc,
Richard Smith49f906a2014-03-01 00:08:04 +00001908 AmbiguousMacros &Ambig,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001909 ArrayRef<SubmoduleID> Overrides) {
Richard Smith49f906a2014-03-01 00:08:04 +00001910 for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1911 SubmoduleID OwnerID = Overrides[OI];
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001912
Richard Smith49f906a2014-03-01 00:08:04 +00001913 // If this macro is not yet visible, remove it from the hidden names list.
Richard Smithbb853c72014-08-13 01:23:33 +00001914 // It won't be there if we're in the middle of making the owner visible.
Richard Smith49f906a2014-03-01 00:08:04 +00001915 Module *Owner = getSubmodule(OwnerID);
Richard Smithbb853c72014-08-13 01:23:33 +00001916 auto HiddenIt = HiddenNamesMap.find(Owner);
1917 if (HiddenIt != HiddenNamesMap.end()) {
1918 HiddenNames &Hidden = HiddenIt->second;
1919 HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1920 if (HI != Hidden.HiddenMacros.end()) {
1921 // Register the macro now so we don't lose it when we re-export.
1922 PP.appendMacroDirective(II, HI->second->import(PP, ImportLoc));
Richard Smithdaa69e02014-07-25 04:40:03 +00001923
Richard Smithbb853c72014-08-13 01:23:33 +00001924 auto SubOverrides = HI->second->getOverriddenSubmodules();
1925 Hidden.HiddenMacros.erase(HI);
1926 removeOverriddenMacros(II, ImportLoc, Ambig, SubOverrides);
1927 }
Richard Smith49f906a2014-03-01 00:08:04 +00001928 }
1929
1930 // If this macro is already in our list of conflicts, remove it from there.
Richard Smithbb29e512014-03-06 00:33:23 +00001931 Ambig.erase(
1932 std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1933 return MD->getInfo()->getOwningModuleID() == OwnerID;
1934 }),
1935 Ambig.end());
Richard Smith49f906a2014-03-01 00:08:04 +00001936 }
1937}
1938
1939ASTReader::AmbiguousMacros *
1940ASTReader::removeOverriddenMacros(IdentifierInfo *II,
Richard Smithdaa69e02014-07-25 04:40:03 +00001941 SourceLocation ImportLoc,
Craig Topper00bbdcf2014-06-28 23:22:23 +00001942 ArrayRef<SubmoduleID> Overrides) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001943 MacroDirective *Prev = PP.getMacroDirective(II);
Richard Smith49f906a2014-03-01 00:08:04 +00001944 if (!Prev && Overrides.empty())
Craig Toppera13603a2014-05-22 05:54:18 +00001945 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001946
Craig Toppera13603a2014-05-22 05:54:18 +00001947 DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective()
1948 : nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001949 if (PrevDef && PrevDef->isAmbiguous()) {
1950 // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1951 AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1952 Ambig.push_back(PrevDef);
1953
Richard Smithdaa69e02014-07-25 04:40:03 +00001954 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001955
1956 if (!Ambig.empty())
1957 return &Ambig;
1958
1959 AmbiguousMacroDefs.erase(II);
1960 } else {
1961 // There's no ambiguity yet. Maybe we're introducing one.
Benjamin Kramer834652a2014-05-03 18:44:26 +00001962 AmbiguousMacros Ambig;
Richard Smith49f906a2014-03-01 00:08:04 +00001963 if (PrevDef)
1964 Ambig.push_back(PrevDef);
1965
Richard Smithdaa69e02014-07-25 04:40:03 +00001966 removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
Richard Smith49f906a2014-03-01 00:08:04 +00001967
1968 if (!Ambig.empty()) {
1969 AmbiguousMacros &Result = AmbiguousMacroDefs[II];
Benjamin Kramer834652a2014-05-03 18:44:26 +00001970 std::swap(Result, Ambig);
Richard Smith49f906a2014-03-01 00:08:04 +00001971 return &Result;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001972 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001973 }
Richard Smith49f906a2014-03-01 00:08:04 +00001974
1975 // We ended up with no ambiguity.
Craig Toppera13603a2014-05-22 05:54:18 +00001976 return nullptr;
Richard Smith49f906a2014-03-01 00:08:04 +00001977}
1978
1979void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
Richard Smithdaa69e02014-07-25 04:40:03 +00001980 Module *Owner) {
Richard Smith49f906a2014-03-01 00:08:04 +00001981 assert(II && Owner);
1982
1983 SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
Richard Smithdaa69e02014-07-25 04:40:03 +00001984 if (ImportLoc.isInvalid()) {
Richard Smith49f906a2014-03-01 00:08:04 +00001985 // FIXME: If we made macros from this module visible but didn't provide a
1986 // source location for the import, we don't have a location for the macro.
1987 // Use the location at which the containing module file was first imported
1988 // for now.
1989 ImportLoc = MMI->F->DirectImportLoc;
Richard Smith56be7542014-03-21 00:33:59 +00001990 assert(ImportLoc.isValid() && "no import location for a visible macro?");
Richard Smith49f906a2014-03-01 00:08:04 +00001991 }
1992
Benjamin Kramer834652a2014-05-03 18:44:26 +00001993 AmbiguousMacros *Prev =
Richard Smithdaa69e02014-07-25 04:40:03 +00001994 removeOverriddenMacros(II, ImportLoc, MMI->getOverriddenSubmodules());
Richard Smith49f906a2014-03-01 00:08:04 +00001995
Richard Smith49f906a2014-03-01 00:08:04 +00001996 // Create a synthetic macro definition corresponding to the import (or null
1997 // if this was an undefinition of the macro).
Richard Smithdaa69e02014-07-25 04:40:03 +00001998 MacroDirective *Imported = MMI->import(PP, ImportLoc);
1999 DefMacroDirective *MD = dyn_cast<DefMacroDirective>(Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002000
2001 // If there's no ambiguity, just install the macro.
2002 if (!Prev) {
Richard Smithdaa69e02014-07-25 04:40:03 +00002003 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002004 return;
2005 }
2006 assert(!Prev->empty());
2007
2008 if (!MD) {
2009 // We imported a #undef that didn't remove all prior definitions. The most
2010 // recent prior definition remains, and we install it in the place of the
Richard Smithdaa69e02014-07-25 04:40:03 +00002011 // imported directive, as if by a local #pragma pop_macro.
Richard Smith49f906a2014-03-01 00:08:04 +00002012 MacroInfo *NewMI = Prev->back()->getInfo();
2013 Prev->pop_back();
Richard Smithdaa69e02014-07-25 04:40:03 +00002014 MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc);
2015
2016 // Install our #undef first so that we don't lose track of it. We'll replace
2017 // this with whichever macro definition ends up winning.
2018 PP.appendMacroDirective(II, Imported);
Richard Smith49f906a2014-03-01 00:08:04 +00002019 }
2020
2021 // We're introducing a macro definition that creates or adds to an ambiguity.
2022 // We can resolve that ambiguity if this macro is token-for-token identical to
2023 // all of the existing definitions.
2024 MacroInfo *NewMI = MD->getInfo();
2025 assert(NewMI && "macro definition with no MacroInfo?");
2026 while (!Prev->empty()) {
2027 MacroInfo *PrevMI = Prev->back()->getInfo();
2028 assert(PrevMI && "macro definition with no MacroInfo?");
2029
2030 // Before marking the macros as ambiguous, check if this is a case where
2031 // both macros are in system headers. If so, we trust that the system
2032 // did not get it wrong. This also handles cases where Clang's own
2033 // headers have a different spelling of certain system macros:
2034 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
2035 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
2036 //
2037 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
2038 // overrides the system limits.h's macros, so there's no conflict here.
2039 if (NewMI != PrevMI &&
2040 !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
2041 !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
2042 break;
2043
2044 // The previous definition is the same as this one (or both are defined in
2045 // system modules so we can assume they're equivalent); we don't need to
2046 // track it any more.
2047 Prev->pop_back();
2048 }
2049
2050 if (!Prev->empty())
2051 MD->setAmbiguous(true);
2052
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002053 PP.appendMacroDirective(II, MD);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002054}
2055
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002056ASTReader::InputFileInfo
2057ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002058 // Go find this input file.
2059 BitstreamCursor &Cursor = F.InputFilesCursor;
2060 SavedStreamPosition SavedPosition(Cursor);
2061 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2062
2063 unsigned Code = Cursor.ReadCode();
2064 RecordData Record;
2065 StringRef Blob;
2066
2067 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2068 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2069 "invalid record type for input file");
2070 (void)Result;
2071
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002072 std::string Filename;
2073 off_t StoredSize;
2074 time_t StoredTime;
2075 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002076
Ben Langmuir198c1682014-03-07 07:27:49 +00002077 assert(Record[0] == ID && "Bogus stored ID or offset");
2078 StoredSize = static_cast<off_t>(Record[1]);
2079 StoredTime = static_cast<time_t>(Record[2]);
2080 Overridden = static_cast<bool>(Record[3]);
2081 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002082 ResolveImportedPath(F, Filename);
2083
Hans Wennborg73945142014-03-14 17:45:06 +00002084 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
2085 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002086}
2087
2088std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002089 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00002090}
2091
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002092InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002093 // If this ID is bogus, just return an empty input file.
2094 if (ID == 0 || ID > F.InputFilesLoaded.size())
2095 return InputFile();
2096
2097 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002098 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002099 return F.InputFilesLoaded[ID-1];
2100
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002101 if (F.InputFilesLoaded[ID-1].isNotFound())
2102 return InputFile();
2103
Guy Benyei11169dd2012-12-18 14:30:41 +00002104 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002105 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002106 SavedStreamPosition SavedPosition(Cursor);
2107 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2108
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002109 InputFileInfo FI = readInputFileInfo(F, ID);
2110 off_t StoredSize = FI.StoredSize;
2111 time_t StoredTime = FI.StoredTime;
2112 bool Overridden = FI.Overridden;
2113 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002114
Ben Langmuir198c1682014-03-07 07:27:49 +00002115 const FileEntry *File
2116 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
2117 : FileMgr.getFile(Filename, /*OpenFile=*/false);
2118
2119 // If we didn't find the file, resolve it relative to the
2120 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002121 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002122 F.OriginalDir != CurrentDir) {
2123 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2124 F.OriginalDir,
2125 CurrentDir);
2126 if (!Resolved.empty())
2127 File = FileMgr.getFile(Resolved);
2128 }
2129
2130 // For an overridden file, create a virtual file with the stored
2131 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00002132 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002133 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2134 }
2135
Craig Toppera13603a2014-05-22 05:54:18 +00002136 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002137 if (Complain) {
2138 std::string ErrorStr = "could not find file '";
2139 ErrorStr += Filename;
2140 ErrorStr += "' referenced by AST file";
2141 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00002142 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002143 // Record that we didn't find the file.
2144 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2145 return InputFile();
2146 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002147
Ben Langmuir198c1682014-03-07 07:27:49 +00002148 // Check if there was a request to override the contents of the file
2149 // that was part of the precompiled header. Overridding such a file
2150 // can lead to problems when lexing using the source locations from the
2151 // PCH.
2152 SourceManager &SM = getSourceManager();
2153 if (!Overridden && SM.isFileOverridden(File)) {
2154 if (Complain)
2155 Error(diag::err_fe_pch_file_overridden, Filename);
2156 // After emitting the diagnostic, recover by disabling the override so
2157 // that the original file will be used.
2158 SM.disableFileContentsOverride(File);
2159 // The FileEntry is a virtual file entry with the size of the contents
2160 // that would override the original contents. Set it to the original's
2161 // size/time.
2162 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2163 StoredSize, StoredTime);
2164 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002165
Ben Langmuir198c1682014-03-07 07:27:49 +00002166 bool IsOutOfDate = false;
2167
2168 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002169 if (!Overridden && //
2170 (StoredSize != File->getSize() ||
2171#if defined(LLVM_ON_WIN32)
2172 false
2173#else
Ben Langmuir198c1682014-03-07 07:27:49 +00002174 // In our regression testing, the Windows file system seems to
2175 // have inconsistent modification times that sometimes
2176 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00002177 //
2178 // This also happens in networked file systems, so disable this
2179 // check if validation is disabled or if we have an explicitly
2180 // built PCM file.
2181 //
2182 // FIXME: Should we also do this for PCH files? They could also
2183 // reasonably get shared across a network during a distributed build.
2184 (StoredTime != File->getModificationTime() && !DisableValidation &&
2185 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00002186#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00002187 )) {
2188 if (Complain) {
2189 // Build a list of the PCH imports that got us here (in reverse).
2190 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2191 while (ImportStack.back()->ImportedBy.size() > 0)
2192 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002193
Ben Langmuir198c1682014-03-07 07:27:49 +00002194 // The top-level PCH is stale.
2195 StringRef TopLevelPCHName(ImportStack.back()->FileName);
2196 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002197
Ben Langmuir198c1682014-03-07 07:27:49 +00002198 // Print the import stack.
2199 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2200 Diag(diag::note_pch_required_by)
2201 << Filename << ImportStack[0]->FileName;
2202 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002203 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002204 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002205 }
2206
Ben Langmuir198c1682014-03-07 07:27:49 +00002207 if (!Diags.isDiagnosticInFlight())
2208 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002209 }
2210
Ben Langmuir198c1682014-03-07 07:27:49 +00002211 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002212 }
2213
Ben Langmuir198c1682014-03-07 07:27:49 +00002214 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2215
2216 // Note that we've loaded this input file.
2217 F.InputFilesLoaded[ID-1] = IF;
2218 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002219}
2220
Richard Smith7ed1bc92014-12-05 22:42:13 +00002221/// \brief If we are loading a relocatable PCH or module file, and the filename
2222/// is not an absolute path, add the system or module root to the beginning of
2223/// the file name.
2224void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2225 // Resolve relative to the base directory, if we have one.
2226 if (!M.BaseDirectory.empty())
2227 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002228}
2229
Richard Smith7ed1bc92014-12-05 22:42:13 +00002230void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002231 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2232 return;
2233
Richard Smith7ed1bc92014-12-05 22:42:13 +00002234 SmallString<128> Buffer;
2235 llvm::sys::path::append(Buffer, Prefix, Filename);
2236 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002237}
2238
2239ASTReader::ASTReadResult
2240ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002241 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002242 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002243 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002244 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002245
2246 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2247 Error("malformed block record in AST file");
2248 return Failure;
2249 }
2250
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002251 // Should we allow the configuration of the module file to differ from the
2252 // configuration of the current translation unit in a compatible way?
2253 //
2254 // FIXME: Allow this for files explicitly specified with -include-pch too.
2255 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2256
Guy Benyei11169dd2012-12-18 14:30:41 +00002257 // Read all of the records and blocks in the control block.
2258 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002259 unsigned NumInputs = 0;
2260 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002261 while (1) {
2262 llvm::BitstreamEntry Entry = Stream.advance();
2263
2264 switch (Entry.Kind) {
2265 case llvm::BitstreamEntry::Error:
2266 Error("malformed block record in AST file");
2267 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002268 case llvm::BitstreamEntry::EndBlock: {
2269 // Validate input files.
2270 const HeaderSearchOptions &HSOpts =
2271 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002272
Richard Smitha1825302014-10-23 22:18:29 +00002273 // All user input files reside at the index range [0, NumUserInputs), and
2274 // system input files reside at [NumUserInputs, NumInputs).
Ben Langmuiracb803e2014-11-10 22:13:10 +00002275 if (!DisableValidation) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002276 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002277
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002278 // If we are reading a module, we will create a verification timestamp,
2279 // so we verify all input files. Otherwise, verify only user input
2280 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002281
2282 unsigned N = NumUserInputs;
2283 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002284 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002285 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002286 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002287 N = NumInputs;
2288
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002289 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002290 InputFile IF = getInputFile(F, I+1, Complain);
2291 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002292 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002293 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002294 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002295
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002296 if (Listener)
2297 Listener->visitModuleFile(F.FileName);
2298
Ben Langmuircb69b572014-03-07 06:40:32 +00002299 if (Listener && Listener->needsInputFileVisitation()) {
2300 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2301 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002302 for (unsigned I = 0; I < N; ++I) {
2303 bool IsSystem = I >= NumUserInputs;
2304 InputFileInfo FI = readInputFileInfo(F, I+1);
2305 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2306 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002307 }
2308
Guy Benyei11169dd2012-12-18 14:30:41 +00002309 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002310 }
2311
Chris Lattnere7b154b2013-01-19 21:39:22 +00002312 case llvm::BitstreamEntry::SubBlock:
2313 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002314 case INPUT_FILES_BLOCK_ID:
2315 F.InputFilesCursor = Stream;
2316 if (Stream.SkipBlock() || // Skip with the main cursor
2317 // Read the abbreviations
2318 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2319 Error("malformed block record in AST file");
2320 return Failure;
2321 }
2322 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002323
Guy Benyei11169dd2012-12-18 14:30:41 +00002324 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002325 if (Stream.SkipBlock()) {
2326 Error("malformed block record in AST file");
2327 return Failure;
2328 }
2329 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002330 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002331
2332 case llvm::BitstreamEntry::Record:
2333 // The interesting case.
2334 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002335 }
2336
2337 // Read and process a record.
2338 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002339 StringRef Blob;
2340 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002341 case METADATA: {
2342 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2343 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002344 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2345 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002346 return VersionMismatch;
2347 }
2348
2349 bool hasErrors = Record[5];
2350 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2351 Diag(diag::err_pch_with_compiler_errors);
2352 return HadErrors;
2353 }
2354
2355 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002356 // Relative paths in a relocatable PCH are relative to our sysroot.
2357 if (F.RelocatablePCH)
2358 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002359
2360 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002361 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002362 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2363 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002364 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002365 return VersionMismatch;
2366 }
2367 break;
2368 }
2369
Ben Langmuir487ea142014-10-23 18:05:36 +00002370 case SIGNATURE:
2371 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2372 F.Signature = Record[0];
2373 break;
2374
Guy Benyei11169dd2012-12-18 14:30:41 +00002375 case IMPORTS: {
2376 // Load each of the imported PCH files.
2377 unsigned Idx = 0, N = Record.size();
2378 while (Idx < N) {
2379 // Read information about the AST file.
2380 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2381 // The import location will be the local one for now; we will adjust
2382 // all import locations of module imports after the global source
2383 // location info are setup.
2384 SourceLocation ImportLoc =
2385 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002386 off_t StoredSize = (off_t)Record[Idx++];
2387 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002388 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002389 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002390
2391 // Load the AST file.
2392 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00002393 StoredSize, StoredModTime, StoredSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00002394 ClientLoadCapabilities)) {
2395 case Failure: return Failure;
2396 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002397 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002398 case OutOfDate: return OutOfDate;
2399 case VersionMismatch: return VersionMismatch;
2400 case ConfigurationMismatch: return ConfigurationMismatch;
2401 case HadErrors: return HadErrors;
2402 case Success: break;
2403 }
2404 }
2405 break;
2406 }
2407
Richard Smith7f330cd2015-03-18 01:42:29 +00002408 case KNOWN_MODULE_FILES:
2409 break;
2410
Guy Benyei11169dd2012-12-18 14:30:41 +00002411 case LANGUAGE_OPTIONS: {
2412 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002413 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002414 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002415 ParseLanguageOptions(Record, Complain, *Listener,
2416 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002417 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002418 return ConfigurationMismatch;
2419 break;
2420 }
2421
2422 case TARGET_OPTIONS: {
2423 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2424 if (Listener && &F == *ModuleMgr.begin() &&
Chandler Carruth0d745bc2015-03-14 04:47:43 +00002425 ParseTargetOptions(Record, Complain, *Listener,
2426 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002427 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002428 return ConfigurationMismatch;
2429 break;
2430 }
2431
2432 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002433 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002434 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002435 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002436 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002437 !DisableValidation)
2438 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002439 break;
2440 }
2441
2442 case FILE_SYSTEM_OPTIONS: {
2443 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2444 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002445 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002446 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002447 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002448 return ConfigurationMismatch;
2449 break;
2450 }
2451
2452 case HEADER_SEARCH_OPTIONS: {
2453 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2454 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002455 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002456 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002457 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002458 return ConfigurationMismatch;
2459 break;
2460 }
2461
2462 case PREPROCESSOR_OPTIONS: {
2463 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2464 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002465 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002466 ParsePreprocessorOptions(Record, Complain, *Listener,
2467 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002468 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002469 return ConfigurationMismatch;
2470 break;
2471 }
2472
2473 case ORIGINAL_FILE:
2474 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002475 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002476 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002477 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002478 break;
2479
2480 case ORIGINAL_FILE_ID:
2481 F.OriginalSourceFileID = FileID::get(Record[0]);
2482 break;
2483
2484 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002485 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 break;
2487
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002488 case MODULE_NAME:
2489 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002490 if (Listener)
2491 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002492 break;
2493
Richard Smith223d3f22014-12-06 03:21:08 +00002494 case MODULE_DIRECTORY: {
2495 assert(!F.ModuleName.empty() &&
2496 "MODULE_DIRECTORY found before MODULE_NAME");
2497 // If we've already loaded a module map file covering this module, we may
2498 // have a better path for it (relative to the current build).
2499 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2500 if (M && M->Directory) {
2501 // If we're implicitly loading a module, the base directory can't
2502 // change between the build and use.
2503 if (F.Kind != MK_ExplicitModule) {
2504 const DirectoryEntry *BuildDir =
2505 PP.getFileManager().getDirectory(Blob);
2506 if (!BuildDir || BuildDir != M->Directory) {
2507 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2508 Diag(diag::err_imported_module_relocated)
2509 << F.ModuleName << Blob << M->Directory->getName();
2510 return OutOfDate;
2511 }
2512 }
2513 F.BaseDirectory = M->Directory->getName();
2514 } else {
2515 F.BaseDirectory = Blob;
2516 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002517 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002518 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002519
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002520 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002521 if (ASTReadResult Result =
2522 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2523 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002524 break;
2525
Guy Benyei11169dd2012-12-18 14:30:41 +00002526 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002527 NumInputs = Record[0];
2528 NumUserInputs = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00002529 F.InputFileOffsets = (const uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002530 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002531 break;
2532 }
2533 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002534}
2535
Ben Langmuir2c9af442014-04-10 17:57:43 +00002536ASTReader::ASTReadResult
2537ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002538 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002539
2540 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2541 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002542 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002543 }
2544
2545 // Read all of the records and blocks for the AST file.
2546 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002547 while (1) {
2548 llvm::BitstreamEntry Entry = Stream.advance();
2549
2550 switch (Entry.Kind) {
2551 case llvm::BitstreamEntry::Error:
2552 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002553 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002554 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002555 // Outside of C++, we do not store a lookup map for the translation unit.
2556 // Instead, mark it as needing a lookup map to be built if this module
2557 // contains any declarations lexically within it (which it always does!).
2558 // This usually has no cost, since we very rarely need the lookup map for
2559 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002560 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002561 if (DC->hasExternalLexicalStorage() &&
2562 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002563 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002564
Ben Langmuir2c9af442014-04-10 17:57:43 +00002565 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002566 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002567 case llvm::BitstreamEntry::SubBlock:
2568 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002569 case DECLTYPES_BLOCK_ID:
2570 // We lazily load the decls block, but we want to set up the
2571 // DeclsCursor cursor to point into it. Clone our current bitcode
2572 // cursor to it, enter the block and read the abbrevs in that block.
2573 // With the main cursor, we just skip over it.
2574 F.DeclsCursor = Stream;
2575 if (Stream.SkipBlock() || // Skip with the main cursor.
2576 // Read the abbrevs.
2577 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2578 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002579 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002580 }
2581 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002582
Guy Benyei11169dd2012-12-18 14:30:41 +00002583 case PREPROCESSOR_BLOCK_ID:
2584 F.MacroCursor = Stream;
2585 if (!PP.getExternalSource())
2586 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002587
Guy Benyei11169dd2012-12-18 14:30:41 +00002588 if (Stream.SkipBlock() ||
2589 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2590 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002591 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002592 }
2593 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2594 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002595
Guy Benyei11169dd2012-12-18 14:30:41 +00002596 case PREPROCESSOR_DETAIL_BLOCK_ID:
2597 F.PreprocessorDetailCursor = Stream;
2598 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002599 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002601 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002602 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002603 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002604 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002605 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2606
Guy Benyei11169dd2012-12-18 14:30:41 +00002607 if (!PP.getPreprocessingRecord())
2608 PP.createPreprocessingRecord();
2609 if (!PP.getPreprocessingRecord()->getExternalSource())
2610 PP.getPreprocessingRecord()->SetExternalSource(*this);
2611 break;
2612
2613 case SOURCE_MANAGER_BLOCK_ID:
2614 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002615 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002616 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002617
Guy Benyei11169dd2012-12-18 14:30:41 +00002618 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002619 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2620 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002621 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002622
Guy Benyei11169dd2012-12-18 14:30:41 +00002623 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002624 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002625 if (Stream.SkipBlock() ||
2626 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2627 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002628 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002629 }
2630 CommentsCursors.push_back(std::make_pair(C, &F));
2631 break;
2632 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002633
Guy Benyei11169dd2012-12-18 14:30:41 +00002634 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002635 if (Stream.SkipBlock()) {
2636 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002637 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002638 }
2639 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002640 }
2641 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002642
2643 case llvm::BitstreamEntry::Record:
2644 // The interesting case.
2645 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002646 }
2647
2648 // Read and process a record.
2649 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002650 StringRef Blob;
2651 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002652 default: // Default behavior: ignore.
2653 break;
2654
2655 case TYPE_OFFSET: {
2656 if (F.LocalNumTypes != 0) {
2657 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002658 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002659 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002660 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 F.LocalNumTypes = Record[0];
2662 unsigned LocalBaseTypeIndex = Record[1];
2663 F.BaseTypeIndex = getTotalNumTypes();
2664
2665 if (F.LocalNumTypes > 0) {
2666 // Introduce the global -> local mapping for types within this module.
2667 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2668
2669 // Introduce the local -> global mapping for types within this module.
2670 F.TypeRemap.insertOrReplace(
2671 std::make_pair(LocalBaseTypeIndex,
2672 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002673
2674 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002675 }
2676 break;
2677 }
2678
2679 case DECL_OFFSET: {
2680 if (F.LocalNumDecls != 0) {
2681 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002682 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002683 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002684 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002685 F.LocalNumDecls = Record[0];
2686 unsigned LocalBaseDeclID = Record[1];
2687 F.BaseDeclID = getTotalNumDecls();
2688
2689 if (F.LocalNumDecls > 0) {
2690 // Introduce the global -> local mapping for declarations within this
2691 // module.
2692 GlobalDeclMap.insert(
2693 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2694
2695 // Introduce the local -> global mapping for declarations within this
2696 // module.
2697 F.DeclRemap.insertOrReplace(
2698 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2699
2700 // Introduce the global -> local mapping for declarations within this
2701 // module.
2702 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002703
Ben Langmuir52ca6782014-10-20 16:27:32 +00002704 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2705 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002706 break;
2707 }
2708
2709 case TU_UPDATE_LEXICAL: {
2710 DeclContext *TU = Context.getTranslationUnitDecl();
2711 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002712 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002713 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002714 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002715 TU->setHasExternalLexicalStorage(true);
2716 break;
2717 }
2718
2719 case UPDATE_VISIBLE: {
2720 unsigned Idx = 0;
2721 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2722 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002723 ASTDeclContextNameLookupTable::Create(
2724 (const unsigned char *)Blob.data() + Record[Idx++],
2725 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2726 (const unsigned char *)Blob.data(),
2727 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002728 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002729 auto *DC = cast<DeclContext>(D);
2730 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002731 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2732 delete LookupTable;
2733 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002734 } else
2735 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2736 break;
2737 }
2738
2739 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002740 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002741 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002742 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2743 (const unsigned char *)F.IdentifierTableData + Record[0],
2744 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2745 (const unsigned char *)F.IdentifierTableData,
2746 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002747
2748 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2749 }
2750 break;
2751
2752 case IDENTIFIER_OFFSET: {
2753 if (F.LocalNumIdentifiers != 0) {
2754 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002755 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002756 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002757 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002758 F.LocalNumIdentifiers = Record[0];
2759 unsigned LocalBaseIdentifierID = Record[1];
2760 F.BaseIdentifierID = getTotalNumIdentifiers();
2761
2762 if (F.LocalNumIdentifiers > 0) {
2763 // Introduce the global -> local mapping for identifiers within this
2764 // module.
2765 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2766 &F));
2767
2768 // Introduce the local -> global mapping for identifiers within this
2769 // module.
2770 F.IdentifierRemap.insertOrReplace(
2771 std::make_pair(LocalBaseIdentifierID,
2772 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002773
Ben Langmuir52ca6782014-10-20 16:27:32 +00002774 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2775 + F.LocalNumIdentifiers);
2776 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002777 break;
2778 }
2779
Ben Langmuir332aafe2014-01-31 01:06:56 +00002780 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002781 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2782 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002783 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002784 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002785 break;
2786
2787 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002788 if (SpecialTypes.empty()) {
2789 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2790 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2791 break;
2792 }
2793
2794 if (SpecialTypes.size() != Record.size()) {
2795 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002796 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002797 }
2798
2799 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2800 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2801 if (!SpecialTypes[I])
2802 SpecialTypes[I] = ID;
2803 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2804 // merge step?
2805 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002806 break;
2807
2808 case STATISTICS:
2809 TotalNumStatements += Record[0];
2810 TotalNumMacros += Record[1];
2811 TotalLexicalDeclContexts += Record[2];
2812 TotalVisibleDeclContexts += Record[3];
2813 break;
2814
2815 case UNUSED_FILESCOPED_DECLS:
2816 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2817 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2818 break;
2819
2820 case DELEGATING_CTORS:
2821 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2822 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2823 break;
2824
2825 case WEAK_UNDECLARED_IDENTIFIERS:
2826 if (Record.size() % 4 != 0) {
2827 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002828 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002829 }
2830
2831 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2832 // files. This isn't the way to do it :)
2833 WeakUndeclaredIdentifiers.clear();
2834
2835 // Translate the weak, undeclared identifiers into global IDs.
2836 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2837 WeakUndeclaredIdentifiers.push_back(
2838 getGlobalIdentifierID(F, Record[I++]));
2839 WeakUndeclaredIdentifiers.push_back(
2840 getGlobalIdentifierID(F, Record[I++]));
2841 WeakUndeclaredIdentifiers.push_back(
2842 ReadSourceLocation(F, Record, I).getRawEncoding());
2843 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2844 }
2845 break;
2846
Guy Benyei11169dd2012-12-18 14:30:41 +00002847 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002848 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002849 F.LocalNumSelectors = Record[0];
2850 unsigned LocalBaseSelectorID = Record[1];
2851 F.BaseSelectorID = getTotalNumSelectors();
2852
2853 if (F.LocalNumSelectors > 0) {
2854 // Introduce the global -> local mapping for selectors within this
2855 // module.
2856 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2857
2858 // Introduce the local -> global mapping for selectors within this
2859 // module.
2860 F.SelectorRemap.insertOrReplace(
2861 std::make_pair(LocalBaseSelectorID,
2862 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002863
2864 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002865 }
2866 break;
2867 }
2868
2869 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002870 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002871 if (Record[0])
2872 F.SelectorLookupTable
2873 = ASTSelectorLookupTable::Create(
2874 F.SelectorLookupTableData + Record[0],
2875 F.SelectorLookupTableData,
2876 ASTSelectorLookupTrait(*this, F));
2877 TotalNumMethodPoolEntries += Record[1];
2878 break;
2879
2880 case REFERENCED_SELECTOR_POOL:
2881 if (!Record.empty()) {
2882 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2883 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2884 Record[Idx++]));
2885 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2886 getRawEncoding());
2887 }
2888 }
2889 break;
2890
2891 case PP_COUNTER_VALUE:
2892 if (!Record.empty() && Listener)
2893 Listener->ReadCounter(F, Record[0]);
2894 break;
2895
2896 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002897 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002898 F.NumFileSortedDecls = Record[0];
2899 break;
2900
2901 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002902 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002903 F.LocalNumSLocEntries = Record[0];
2904 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002905 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002906 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002907 SLocSpaceSize);
2908 // Make our entry in the range map. BaseID is negative and growing, so
2909 // we invert it. Because we invert it, though, we need the other end of
2910 // the range.
2911 unsigned RangeStart =
2912 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2913 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2914 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2915
2916 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2917 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2918 GlobalSLocOffsetMap.insert(
2919 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2920 - SLocSpaceSize,&F));
2921
2922 // Initialize the remapping table.
2923 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002924 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002925 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002926 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002927 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2928
2929 TotalNumSLocEntries += F.LocalNumSLocEntries;
2930 break;
2931 }
2932
2933 case MODULE_OFFSET_MAP: {
2934 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002935 const unsigned char *Data = (const unsigned char*)Blob.data();
2936 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002937
2938 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2939 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2940 F.SLocRemap.insert(std::make_pair(0U, 0));
2941 F.SLocRemap.insert(std::make_pair(2U, 1));
2942 }
2943
Guy Benyei11169dd2012-12-18 14:30:41 +00002944 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002945 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2946 RemapBuilder;
2947 RemapBuilder SLocRemap(F.SLocRemap);
2948 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2949 RemapBuilder MacroRemap(F.MacroRemap);
2950 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2951 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2952 RemapBuilder SelectorRemap(F.SelectorRemap);
2953 RemapBuilder DeclRemap(F.DeclRemap);
2954 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002955
2956 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002957 using namespace llvm::support;
2958 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002959 StringRef Name = StringRef((const char*)Data, Len);
2960 Data += Len;
2961 ModuleFile *OM = ModuleMgr.lookup(Name);
2962 if (!OM) {
2963 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002964 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002965 }
2966
Justin Bogner57ba0b22014-03-28 22:03:24 +00002967 uint32_t SLocOffset =
2968 endian::readNext<uint32_t, little, unaligned>(Data);
2969 uint32_t IdentifierIDOffset =
2970 endian::readNext<uint32_t, little, unaligned>(Data);
2971 uint32_t MacroIDOffset =
2972 endian::readNext<uint32_t, little, unaligned>(Data);
2973 uint32_t PreprocessedEntityIDOffset =
2974 endian::readNext<uint32_t, little, unaligned>(Data);
2975 uint32_t SubmoduleIDOffset =
2976 endian::readNext<uint32_t, little, unaligned>(Data);
2977 uint32_t SelectorIDOffset =
2978 endian::readNext<uint32_t, little, unaligned>(Data);
2979 uint32_t DeclIDOffset =
2980 endian::readNext<uint32_t, little, unaligned>(Data);
2981 uint32_t TypeIndexOffset =
2982 endian::readNext<uint32_t, little, unaligned>(Data);
2983
Ben Langmuir785180e2014-10-20 16:27:30 +00002984 uint32_t None = std::numeric_limits<uint32_t>::max();
2985
2986 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2987 RemapBuilder &Remap) {
2988 if (Offset != None)
2989 Remap.insert(std::make_pair(Offset,
2990 static_cast<int>(BaseOffset - Offset)));
2991 };
2992 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2993 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2994 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2995 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2996 PreprocessedEntityRemap);
2997 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2998 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2999 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3000 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00003001
3002 // Global -> local mappings.
3003 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3004 }
3005 break;
3006 }
3007
3008 case SOURCE_MANAGER_LINE_TABLE:
3009 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003010 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003011 break;
3012
3013 case SOURCE_LOCATION_PRELOADS: {
3014 // Need to transform from the local view (1-based IDs) to the global view,
3015 // which is based off F.SLocEntryBaseID.
3016 if (!F.PreloadSLocEntries.empty()) {
3017 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003018 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003019 }
3020
3021 F.PreloadSLocEntries.swap(Record);
3022 break;
3023 }
3024
3025 case EXT_VECTOR_DECLS:
3026 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3027 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3028 break;
3029
3030 case VTABLE_USES:
3031 if (Record.size() % 3 != 0) {
3032 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003033 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003034 }
3035
3036 // Later tables overwrite earlier ones.
3037 // FIXME: Modules will have some trouble with this. This is clearly not
3038 // the right way to do this.
3039 VTableUses.clear();
3040
3041 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3042 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3043 VTableUses.push_back(
3044 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3045 VTableUses.push_back(Record[Idx++]);
3046 }
3047 break;
3048
Guy Benyei11169dd2012-12-18 14:30:41 +00003049 case PENDING_IMPLICIT_INSTANTIATIONS:
3050 if (PendingInstantiations.size() % 2 != 0) {
3051 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003052 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003053 }
3054
3055 if (Record.size() % 2 != 0) {
3056 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003057 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003058 }
3059
3060 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3061 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3062 PendingInstantiations.push_back(
3063 ReadSourceLocation(F, Record, I).getRawEncoding());
3064 }
3065 break;
3066
3067 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00003068 if (Record.size() != 2) {
3069 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003070 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003071 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003072 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3073 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3074 break;
3075
3076 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003077 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3078 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3079 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003080
3081 unsigned LocalBasePreprocessedEntityID = Record[0];
3082
3083 unsigned StartingID;
3084 if (!PP.getPreprocessingRecord())
3085 PP.createPreprocessingRecord();
3086 if (!PP.getPreprocessingRecord()->getExternalSource())
3087 PP.getPreprocessingRecord()->SetExternalSource(*this);
3088 StartingID
3089 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003090 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003091 F.BasePreprocessedEntityID = StartingID;
3092
3093 if (F.NumPreprocessedEntities > 0) {
3094 // Introduce the global -> local mapping for preprocessed entities in
3095 // this module.
3096 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3097
3098 // Introduce the local -> global mapping for preprocessed entities in
3099 // this module.
3100 F.PreprocessedEntityRemap.insertOrReplace(
3101 std::make_pair(LocalBasePreprocessedEntityID,
3102 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3103 }
3104
3105 break;
3106 }
3107
3108 case DECL_UPDATE_OFFSETS: {
3109 if (Record.size() % 2 != 0) {
3110 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003111 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003112 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003113 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3114 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3115 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3116
3117 // If we've already loaded the decl, perform the updates when we finish
3118 // loading this block.
3119 if (Decl *D = GetExistingDecl(ID))
3120 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3121 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003122 break;
3123 }
3124
3125 case DECL_REPLACEMENTS: {
3126 if (Record.size() % 3 != 0) {
3127 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003128 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003129 }
3130 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
3131 ReplacedDecls[getGlobalDeclID(F, Record[I])]
3132 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
3133 break;
3134 }
3135
3136 case OBJC_CATEGORIES_MAP: {
3137 if (F.LocalNumObjCCategoriesInMap != 0) {
3138 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003139 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003140 }
3141
3142 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003143 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003144 break;
3145 }
3146
3147 case OBJC_CATEGORIES:
3148 F.ObjCCategories.swap(Record);
3149 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003150
Guy Benyei11169dd2012-12-18 14:30:41 +00003151 case CXX_BASE_SPECIFIER_OFFSETS: {
3152 if (F.LocalNumCXXBaseSpecifiers != 0) {
3153 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003154 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003155 }
Richard Smithc2bb8182015-03-24 06:36:48 +00003156
Guy Benyei11169dd2012-12-18 14:30:41 +00003157 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003158 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00003159 break;
3160 }
3161
3162 case CXX_CTOR_INITIALIZERS_OFFSETS: {
3163 if (F.LocalNumCXXCtorInitializers != 0) {
3164 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
3165 return Failure;
3166 }
3167
3168 F.LocalNumCXXCtorInitializers = Record[0];
3169 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003170 break;
3171 }
3172
3173 case DIAG_PRAGMA_MAPPINGS:
3174 if (F.PragmaDiagMappings.empty())
3175 F.PragmaDiagMappings.swap(Record);
3176 else
3177 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3178 Record.begin(), Record.end());
3179 break;
3180
3181 case CUDA_SPECIAL_DECL_REFS:
3182 // Later tables overwrite earlier ones.
3183 // FIXME: Modules will have trouble with this.
3184 CUDASpecialDeclRefs.clear();
3185 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3186 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3187 break;
3188
3189 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003190 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003191 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003192 if (Record[0]) {
3193 F.HeaderFileInfoTable
3194 = HeaderFileInfoLookupTable::Create(
3195 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3196 (const unsigned char *)F.HeaderFileInfoTableData,
3197 HeaderFileInfoTrait(*this, F,
3198 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003199 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003200
3201 PP.getHeaderSearchInfo().SetExternalSource(this);
3202 if (!PP.getHeaderSearchInfo().getExternalLookup())
3203 PP.getHeaderSearchInfo().SetExternalLookup(this);
3204 }
3205 break;
3206 }
3207
3208 case FP_PRAGMA_OPTIONS:
3209 // Later tables overwrite earlier ones.
3210 FPPragmaOptions.swap(Record);
3211 break;
3212
3213 case OPENCL_EXTENSIONS:
3214 // Later tables overwrite earlier ones.
3215 OpenCLExtensions.swap(Record);
3216 break;
3217
3218 case TENTATIVE_DEFINITIONS:
3219 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3220 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3221 break;
3222
3223 case KNOWN_NAMESPACES:
3224 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3225 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3226 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003227
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003228 case UNDEFINED_BUT_USED:
3229 if (UndefinedButUsed.size() % 2 != 0) {
3230 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003231 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003232 }
3233
3234 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003235 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003236 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003237 }
3238 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003239 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3240 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003241 ReadSourceLocation(F, Record, I).getRawEncoding());
3242 }
3243 break;
3244
Guy Benyei11169dd2012-12-18 14:30:41 +00003245 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003246 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003247 // If we aren't loading a module (which has its own exports), make
3248 // all of the imported modules visible.
3249 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003250 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3251 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3252 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3253 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003254 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003255 }
3256 }
3257 break;
3258 }
3259
3260 case LOCAL_REDECLARATIONS: {
3261 F.RedeclarationChains.swap(Record);
3262 break;
3263 }
3264
3265 case LOCAL_REDECLARATIONS_MAP: {
3266 if (F.LocalNumRedeclarationsInMap != 0) {
3267 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003268 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003269 }
3270
3271 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003272 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003273 break;
3274 }
3275
Guy Benyei11169dd2012-12-18 14:30:41 +00003276 case MACRO_OFFSET: {
3277 if (F.LocalNumMacros != 0) {
3278 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003279 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003280 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003281 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003282 F.LocalNumMacros = Record[0];
3283 unsigned LocalBaseMacroID = Record[1];
3284 F.BaseMacroID = getTotalNumMacros();
3285
3286 if (F.LocalNumMacros > 0) {
3287 // Introduce the global -> local mapping for macros within this module.
3288 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3289
3290 // Introduce the local -> global mapping for macros within this module.
3291 F.MacroRemap.insertOrReplace(
3292 std::make_pair(LocalBaseMacroID,
3293 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003294
3295 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003296 }
3297 break;
3298 }
3299
Richard Smithe40f2ba2013-08-07 21:41:30 +00003300 case LATE_PARSED_TEMPLATE: {
3301 LateParsedTemplates.append(Record.begin(), Record.end());
3302 break;
3303 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003304
3305 case OPTIMIZE_PRAGMA_OPTIONS:
3306 if (Record.size() != 1) {
3307 Error("invalid pragma optimize record");
3308 return Failure;
3309 }
3310 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3311 break;
Nico Weber72889432014-09-06 01:25:55 +00003312
3313 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3314 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3315 UnusedLocalTypedefNameCandidates.push_back(
3316 getGlobalDeclID(F, Record[I]));
3317 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003318 }
3319 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003320}
3321
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003322ASTReader::ASTReadResult
3323ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3324 const ModuleFile *ImportedBy,
3325 unsigned ClientLoadCapabilities) {
3326 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003327 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003328
Richard Smithe842a472014-10-22 02:05:46 +00003329 if (F.Kind == MK_ExplicitModule) {
3330 // For an explicitly-loaded module, we don't care whether the original
3331 // module map file exists or matches.
3332 return Success;
3333 }
3334
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003335 // Try to resolve ModuleName in the current header search context and
3336 // verify that it is found in the same module map file as we saved. If the
3337 // top-level AST file is a main file, skip this check because there is no
3338 // usable header search context.
3339 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003340 "MODULE_NAME should come before MODULE_MAP_FILE");
3341 if (F.Kind == MK_ImplicitModule &&
3342 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3343 // An implicitly-loaded module file should have its module listed in some
3344 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003345 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003346 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3347 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3348 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003349 assert(ImportedBy && "top-level import should be verified");
3350 if ((ClientLoadCapabilities & ARR_Missing) == 0)
Richard Smithe842a472014-10-22 02:05:46 +00003351 Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3352 << ImportedBy->FileName
3353 << F.ModuleMapPath;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003354 return Missing;
3355 }
3356
Richard Smithe842a472014-10-22 02:05:46 +00003357 assert(M->Name == F.ModuleName && "found module with different name");
3358
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003359 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003360 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003361 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3362 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003363 assert(ImportedBy && "top-level import should be verified");
3364 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3365 Diag(diag::err_imported_module_modmap_changed)
3366 << F.ModuleName << ImportedBy->FileName
3367 << ModMap->getName() << F.ModuleMapPath;
3368 return OutOfDate;
3369 }
3370
3371 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3372 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3373 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003374 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003375 const FileEntry *F =
3376 FileMgr.getFile(Filename, false, false);
3377 if (F == nullptr) {
3378 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3379 Error("could not find file '" + Filename +"' referenced by AST file");
3380 return OutOfDate;
3381 }
3382 AdditionalStoredMaps.insert(F);
3383 }
3384
3385 // Check any additional module map files (e.g. module.private.modulemap)
3386 // that are not in the pcm.
3387 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3388 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3389 // Remove files that match
3390 // Note: SmallPtrSet::erase is really remove
3391 if (!AdditionalStoredMaps.erase(ModMap)) {
3392 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3393 Diag(diag::err_module_different_modmap)
3394 << F.ModuleName << /*new*/0 << ModMap->getName();
3395 return OutOfDate;
3396 }
3397 }
3398 }
3399
3400 // Check any additional module map files that are in the pcm, but not
3401 // found in header search. Cases that match are already removed.
3402 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3403 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3404 Diag(diag::err_module_different_modmap)
3405 << F.ModuleName << /*not new*/1 << ModMap->getName();
3406 return OutOfDate;
3407 }
3408 }
3409
3410 if (Listener)
3411 Listener->ReadModuleMapFile(F.ModuleMapPath);
3412 return Success;
3413}
3414
3415
Douglas Gregorc1489562013-02-12 23:36:21 +00003416/// \brief Move the given method to the back of the global list of methods.
3417static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3418 // Find the entry for this selector in the method pool.
3419 Sema::GlobalMethodPool::iterator Known
3420 = S.MethodPool.find(Method->getSelector());
3421 if (Known == S.MethodPool.end())
3422 return;
3423
3424 // Retrieve the appropriate method list.
3425 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3426 : Known->second.second;
3427 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003428 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003429 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003430 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003431 Found = true;
3432 } else {
3433 // Keep searching.
3434 continue;
3435 }
3436 }
3437
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003438 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003439 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003440 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003441 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003442 }
3443}
3444
Richard Smithe657bbd2014-07-18 22:13:40 +00003445void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner,
3446 bool FromFinalization) {
3447 // FIXME: Only do this if Owner->NameVisibility == AllVisible.
Richard Smith57721ac2014-07-21 04:10:40 +00003448 for (Decl *D : Names.HiddenDecls) {
Richard Smith49f906a2014-03-01 00:08:04 +00003449 bool wasHidden = D->Hidden;
3450 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003451
Richard Smith49f906a2014-03-01 00:08:04 +00003452 if (wasHidden && SemaObj) {
3453 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3454 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003455 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003456 }
3457 }
Richard Smith49f906a2014-03-01 00:08:04 +00003458
Richard Smithe657bbd2014-07-18 22:13:40 +00003459 assert((FromFinalization || Owner->NameVisibility >= Module::MacrosVisible) &&
3460 "nothing to make visible?");
Richard Smithdaa69e02014-07-25 04:40:03 +00003461 for (const auto &Macro : Names.HiddenMacros) {
3462 if (FromFinalization)
3463 PP.appendMacroDirective(Macro.first,
3464 Macro.second->import(PP, SourceLocation()));
3465 else
3466 installImportedMacro(Macro.first, Macro.second, Owner);
3467 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003468}
3469
Richard Smith49f906a2014-03-01 00:08:04 +00003470void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003471 Module::NameVisibilityKind NameVisibility,
Douglas Gregorfb912652013-03-20 21:10:35 +00003472 SourceLocation ImportLoc,
3473 bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003474 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003475 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003476 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003477 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003478 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003479
3480 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003481 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003482 // there is nothing more to do.
3483 continue;
3484 }
Richard Smith49f906a2014-03-01 00:08:04 +00003485
Guy Benyei11169dd2012-12-18 14:30:41 +00003486 if (!Mod->isAvailable()) {
3487 // Modules that aren't available cannot be made visible.
3488 continue;
3489 }
3490
3491 // Update the module's name visibility.
Richard Smith49f906a2014-03-01 00:08:04 +00003492 if (NameVisibility >= Module::MacrosVisible &&
3493 Mod->NameVisibility < Module::MacrosVisible)
3494 Mod->MacroVisibilityLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003495 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003496
Guy Benyei11169dd2012-12-18 14:30:41 +00003497 // If we've already deserialized any names from this module,
3498 // mark them as visible.
3499 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3500 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003501 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003502 HiddenNamesMap.erase(Hidden);
Richard Smith57721ac2014-07-21 04:10:40 +00003503 makeNamesVisible(HiddenNames.second, HiddenNames.first,
3504 /*FromFinalization*/false);
3505 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3506 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003507 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003508
Guy Benyei11169dd2012-12-18 14:30:41 +00003509 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003510 SmallVector<Module *, 16> Exports;
3511 Mod->getExportedModules(Exports);
3512 for (SmallVectorImpl<Module *>::iterator
3513 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3514 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003515 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003516 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003517 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003518
3519 // Detect any conflicts.
3520 if (Complain) {
3521 assert(ImportLoc.isValid() && "Missing import location");
3522 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3523 if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3524 Diag(ImportLoc, diag::warn_module_conflict)
3525 << Mod->getFullModuleName()
3526 << Mod->Conflicts[I].Other->getFullModuleName()
3527 << Mod->Conflicts[I].Message;
3528 // FIXME: Need note where the other module was imported.
3529 }
3530 }
3531 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003532 }
3533}
3534
Douglas Gregore060e572013-01-25 01:03:03 +00003535bool ASTReader::loadGlobalIndex() {
3536 if (GlobalIndex)
3537 return false;
3538
3539 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3540 !Context.getLangOpts().Modules)
3541 return true;
3542
3543 // Try to load the global index.
3544 TriedLoadingGlobalIndex = true;
3545 StringRef ModuleCachePath
3546 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3547 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003548 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003549 if (!Result.first)
3550 return true;
3551
3552 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003553 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003554 return false;
3555}
3556
3557bool ASTReader::isGlobalIndexUnavailable() const {
3558 return Context.getLangOpts().Modules && UseGlobalIndex &&
3559 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3560}
3561
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003562static void updateModuleTimestamp(ModuleFile &MF) {
3563 // Overwrite the timestamp file contents so that file's mtime changes.
3564 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003565 std::error_code EC;
3566 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3567 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003568 return;
3569 OS << "Timestamp file\n";
3570}
3571
Guy Benyei11169dd2012-12-18 14:30:41 +00003572ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3573 ModuleKind Type,
3574 SourceLocation ImportLoc,
3575 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003576 llvm::SaveAndRestore<SourceLocation>
3577 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3578
Richard Smithd1c46742014-04-30 02:24:17 +00003579 // Defer any pending actions until we get to the end of reading the AST file.
3580 Deserializing AnASTFile(this);
3581
Guy Benyei11169dd2012-12-18 14:30:41 +00003582 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003583 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003584
3585 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003586 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003587 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003588 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003589 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003590 ClientLoadCapabilities)) {
3591 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003592 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003593 case OutOfDate:
3594 case VersionMismatch:
3595 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003596 case HadErrors: {
3597 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3598 for (const ImportedModule &IM : Loaded)
3599 LoadedSet.insert(IM.Mod);
3600
Douglas Gregor7029ce12013-03-19 00:28:20 +00003601 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003602 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003603 Context.getLangOpts().Modules
3604 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003605 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003606
3607 // If we find that any modules are unusable, the global index is going
3608 // to be out-of-date. Just remove it.
3609 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003610 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003611 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003612 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003613 case Success:
3614 break;
3615 }
3616
3617 // Here comes stuff that we only do once the entire chain is loaded.
3618
3619 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003620 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3621 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003622 M != MEnd; ++M) {
3623 ModuleFile &F = *M->Mod;
3624
3625 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003626 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3627 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003628
3629 // Once read, set the ModuleFile bit base offset and update the size in
3630 // bits of all files we've seen.
3631 F.GlobalBitOffset = TotalModulesSizeInBits;
3632 TotalModulesSizeInBits += F.SizeInBits;
3633 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3634
3635 // Preload SLocEntries.
3636 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3637 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3638 // Load it through the SourceManager and don't call ReadSLocEntry()
3639 // directly because the entry may have already been loaded in which case
3640 // calling ReadSLocEntry() directly would trigger an assertion in
3641 // SourceManager.
3642 SourceMgr.getLoadedSLocEntryByID(Index);
3643 }
3644 }
3645
Douglas Gregor603cd862013-03-22 18:50:14 +00003646 // Setup the import locations and notify the module manager that we've
3647 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003648 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3649 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003650 M != MEnd; ++M) {
3651 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003652
3653 ModuleMgr.moduleFileAccepted(&F);
3654
3655 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003656 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003657 if (!M->ImportedBy)
3658 F.ImportLoc = M->ImportLoc;
3659 else
3660 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3661 M->ImportLoc.getRawEncoding());
3662 }
3663
3664 // Mark all of the identifiers in the identifier table as being out of date,
3665 // so that various accessors know to check the loaded modules when the
3666 // identifier is used.
3667 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3668 IdEnd = PP.getIdentifierTable().end();
3669 Id != IdEnd; ++Id)
3670 Id->second->setOutOfDate(true);
3671
3672 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003673 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3674 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003675 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3676 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003677
3678 switch (Unresolved.Kind) {
3679 case UnresolvedModuleRef::Conflict:
3680 if (ResolvedMod) {
3681 Module::Conflict Conflict;
3682 Conflict.Other = ResolvedMod;
3683 Conflict.Message = Unresolved.String.str();
3684 Unresolved.Mod->Conflicts.push_back(Conflict);
3685 }
3686 continue;
3687
3688 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003689 if (ResolvedMod)
3690 Unresolved.Mod->Imports.push_back(ResolvedMod);
3691 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003692
Douglas Gregorfb912652013-03-20 21:10:35 +00003693 case UnresolvedModuleRef::Export:
3694 if (ResolvedMod || Unresolved.IsWildcard)
3695 Unresolved.Mod->Exports.push_back(
3696 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3697 continue;
3698 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003699 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003700 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003701
3702 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3703 // Might be unnecessary as use declarations are only used to build the
3704 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003705
3706 InitializeContext();
3707
Richard Smith3d8e97e2013-10-18 06:54:39 +00003708 if (SemaObj)
3709 UpdateSema();
3710
Guy Benyei11169dd2012-12-18 14:30:41 +00003711 if (DeserializationListener)
3712 DeserializationListener->ReaderInitialized(this);
3713
3714 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3715 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3716 PrimaryModule.OriginalSourceFileID
3717 = FileID::get(PrimaryModule.SLocEntryBaseID
3718 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3719
3720 // If this AST file is a precompiled preamble, then set the
3721 // preamble file ID of the source manager to the file source file
3722 // from which the preamble was built.
3723 if (Type == MK_Preamble) {
3724 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3725 } else if (Type == MK_MainFile) {
3726 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3727 }
3728 }
3729
3730 // For any Objective-C class definitions we have already loaded, make sure
3731 // that we load any additional categories.
3732 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3733 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3734 ObjCClassesLoaded[I],
3735 PreviousGeneration);
3736 }
Douglas Gregore060e572013-01-25 01:03:03 +00003737
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003738 if (PP.getHeaderSearchInfo()
3739 .getHeaderSearchOpts()
3740 .ModulesValidateOncePerBuildSession) {
3741 // Now we are certain that the module and all modules it depends on are
3742 // up to date. Create or update timestamp files for modules that are
3743 // located in the module cache (not for PCH files that could be anywhere
3744 // in the filesystem).
3745 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3746 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003747 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003748 updateModuleTimestamp(*M.Mod);
3749 }
3750 }
3751 }
3752
Guy Benyei11169dd2012-12-18 14:30:41 +00003753 return Success;
3754}
3755
Ben Langmuir487ea142014-10-23 18:05:36 +00003756static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3757
Ben Langmuir70a1b812015-03-24 04:43:52 +00003758/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3759static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3760 return Stream.Read(8) == 'C' &&
3761 Stream.Read(8) == 'P' &&
3762 Stream.Read(8) == 'C' &&
3763 Stream.Read(8) == 'H';
3764}
3765
Guy Benyei11169dd2012-12-18 14:30:41 +00003766ASTReader::ASTReadResult
3767ASTReader::ReadASTCore(StringRef FileName,
3768 ModuleKind Type,
3769 SourceLocation ImportLoc,
3770 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003771 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003772 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003773 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003774 unsigned ClientLoadCapabilities) {
3775 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003776 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003777 ModuleManager::AddModuleResult AddResult
3778 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003779 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003780 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003781 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003782
Douglas Gregor7029ce12013-03-19 00:28:20 +00003783 switch (AddResult) {
3784 case ModuleManager::AlreadyLoaded:
3785 return Success;
3786
3787 case ModuleManager::NewlyLoaded:
3788 // Load module file below.
3789 break;
3790
3791 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003792 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003793 // it.
3794 if (ClientLoadCapabilities & ARR_Missing)
3795 return Missing;
3796
3797 // Otherwise, return an error.
3798 {
3799 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3800 + ErrorStr;
3801 Error(Msg);
3802 }
3803 return Failure;
3804
3805 case ModuleManager::OutOfDate:
3806 // We couldn't load the module file because it is out-of-date. If the
3807 // client can handle out-of-date, return it.
3808 if (ClientLoadCapabilities & ARR_OutOfDate)
3809 return OutOfDate;
3810
3811 // Otherwise, return an error.
3812 {
3813 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3814 + ErrorStr;
3815 Error(Msg);
3816 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003817 return Failure;
3818 }
3819
Douglas Gregor7029ce12013-03-19 00:28:20 +00003820 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003821
3822 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3823 // module?
3824 if (FileName != "-") {
3825 CurrentDir = llvm::sys::path::parent_path(FileName);
3826 if (CurrentDir.empty()) CurrentDir = ".";
3827 }
3828
3829 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003830 BitstreamCursor &Stream = F.Stream;
Rafael Espindolafd832392014-11-12 14:48:44 +00003831 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003832 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3833
Guy Benyei11169dd2012-12-18 14:30:41 +00003834 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003835 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003836 Diag(diag::err_not_a_pch_file) << FileName;
3837 return Failure;
3838 }
3839
3840 // This is used for compatibility with older PCH formats.
3841 bool HaveReadControlBlock = false;
3842
Chris Lattnerefa77172013-01-20 00:00:22 +00003843 while (1) {
3844 llvm::BitstreamEntry Entry = Stream.advance();
3845
3846 switch (Entry.Kind) {
3847 case llvm::BitstreamEntry::Error:
3848 case llvm::BitstreamEntry::EndBlock:
3849 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003850 Error("invalid record at top-level of AST file");
3851 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003852
3853 case llvm::BitstreamEntry::SubBlock:
3854 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003855 }
3856
Guy Benyei11169dd2012-12-18 14:30:41 +00003857 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003858 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003859 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3860 if (Stream.ReadBlockInfoBlock()) {
3861 Error("malformed BlockInfoBlock in AST file");
3862 return Failure;
3863 }
3864 break;
3865 case CONTROL_BLOCK_ID:
3866 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003867 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003868 case Success:
3869 break;
3870
3871 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003872 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003873 case OutOfDate: return OutOfDate;
3874 case VersionMismatch: return VersionMismatch;
3875 case ConfigurationMismatch: return ConfigurationMismatch;
3876 case HadErrors: return HadErrors;
3877 }
3878 break;
3879 case AST_BLOCK_ID:
3880 if (!HaveReadControlBlock) {
3881 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003882 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003883 return VersionMismatch;
3884 }
3885
3886 // Record that we've loaded this module.
3887 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3888 return Success;
3889
3890 default:
3891 if (Stream.SkipBlock()) {
3892 Error("malformed block record in AST file");
3893 return Failure;
3894 }
3895 break;
3896 }
3897 }
3898
3899 return Success;
3900}
3901
3902void ASTReader::InitializeContext() {
3903 // If there's a listener, notify them that we "read" the translation unit.
3904 if (DeserializationListener)
3905 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3906 Context.getTranslationUnitDecl());
3907
Guy Benyei11169dd2012-12-18 14:30:41 +00003908 // FIXME: Find a better way to deal with collisions between these
3909 // built-in types. Right now, we just ignore the problem.
3910
3911 // Load the special types.
3912 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3913 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3914 if (!Context.CFConstantStringTypeDecl)
3915 Context.setCFConstantStringType(GetType(String));
3916 }
3917
3918 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3919 QualType FileType = GetType(File);
3920 if (FileType.isNull()) {
3921 Error("FILE type is NULL");
3922 return;
3923 }
3924
3925 if (!Context.FILEDecl) {
3926 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3927 Context.setFILEDecl(Typedef->getDecl());
3928 else {
3929 const TagType *Tag = FileType->getAs<TagType>();
3930 if (!Tag) {
3931 Error("Invalid FILE type in AST file");
3932 return;
3933 }
3934 Context.setFILEDecl(Tag->getDecl());
3935 }
3936 }
3937 }
3938
3939 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3940 QualType Jmp_bufType = GetType(Jmp_buf);
3941 if (Jmp_bufType.isNull()) {
3942 Error("jmp_buf type is NULL");
3943 return;
3944 }
3945
3946 if (!Context.jmp_bufDecl) {
3947 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3948 Context.setjmp_bufDecl(Typedef->getDecl());
3949 else {
3950 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3951 if (!Tag) {
3952 Error("Invalid jmp_buf type in AST file");
3953 return;
3954 }
3955 Context.setjmp_bufDecl(Tag->getDecl());
3956 }
3957 }
3958 }
3959
3960 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3961 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3962 if (Sigjmp_bufType.isNull()) {
3963 Error("sigjmp_buf type is NULL");
3964 return;
3965 }
3966
3967 if (!Context.sigjmp_bufDecl) {
3968 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3969 Context.setsigjmp_bufDecl(Typedef->getDecl());
3970 else {
3971 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3972 assert(Tag && "Invalid sigjmp_buf type in AST file");
3973 Context.setsigjmp_bufDecl(Tag->getDecl());
3974 }
3975 }
3976 }
3977
3978 if (unsigned ObjCIdRedef
3979 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3980 if (Context.ObjCIdRedefinitionType.isNull())
3981 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3982 }
3983
3984 if (unsigned ObjCClassRedef
3985 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3986 if (Context.ObjCClassRedefinitionType.isNull())
3987 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3988 }
3989
3990 if (unsigned ObjCSelRedef
3991 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3992 if (Context.ObjCSelRedefinitionType.isNull())
3993 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3994 }
3995
3996 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3997 QualType Ucontext_tType = GetType(Ucontext_t);
3998 if (Ucontext_tType.isNull()) {
3999 Error("ucontext_t type is NULL");
4000 return;
4001 }
4002
4003 if (!Context.ucontext_tDecl) {
4004 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4005 Context.setucontext_tDecl(Typedef->getDecl());
4006 else {
4007 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4008 assert(Tag && "Invalid ucontext_t type in AST file");
4009 Context.setucontext_tDecl(Tag->getDecl());
4010 }
4011 }
4012 }
4013 }
4014
4015 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4016
4017 // If there were any CUDA special declarations, deserialize them.
4018 if (!CUDASpecialDeclRefs.empty()) {
4019 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4020 Context.setcudaConfigureCallDecl(
4021 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4022 }
Richard Smith56be7542014-03-21 00:33:59 +00004023
Guy Benyei11169dd2012-12-18 14:30:41 +00004024 // Re-export any modules that were imported by a non-module AST file.
Richard Smith56be7542014-03-21 00:33:59 +00004025 // FIXME: This does not make macro-only imports visible again. It also doesn't
4026 // make #includes mapped to module imports visible.
4027 for (auto &Import : ImportedModules) {
4028 if (Module *Imported = getSubmodule(Import.ID))
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004029 makeModuleVisible(Imported, Module::AllVisible,
Richard Smith56be7542014-03-21 00:33:59 +00004030 /*ImportLoc=*/Import.ImportLoc,
Douglas Gregorfb912652013-03-20 21:10:35 +00004031 /*Complain=*/false);
Guy Benyei11169dd2012-12-18 14:30:41 +00004032 }
4033 ImportedModules.clear();
4034}
4035
4036void ASTReader::finalizeForWriting() {
Richard Smith57721ac2014-07-21 04:10:40 +00004037 while (!HiddenNamesMap.empty()) {
4038 auto HiddenNames = std::move(*HiddenNamesMap.begin());
4039 HiddenNamesMap.erase(HiddenNamesMap.begin());
4040 makeNamesVisible(HiddenNames.second, HiddenNames.first,
4041 /*FromFinalization*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004042 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004043}
4044
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004045/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
4046/// cursor into the start of the given block ID, returning false on success and
4047/// true on failure.
4048static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004049 while (1) {
4050 llvm::BitstreamEntry Entry = Cursor.advance();
4051 switch (Entry.Kind) {
4052 case llvm::BitstreamEntry::Error:
4053 case llvm::BitstreamEntry::EndBlock:
4054 return true;
4055
4056 case llvm::BitstreamEntry::Record:
4057 // Ignore top-level records.
4058 Cursor.skipRecord(Entry.ID);
4059 break;
4060
4061 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004062 if (Entry.ID == BlockID) {
4063 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004064 return true;
4065 // Found it!
4066 return false;
4067 }
4068
4069 if (Cursor.SkipBlock())
4070 return true;
4071 }
4072 }
4073}
4074
Ben Langmuir70a1b812015-03-24 04:43:52 +00004075/// \brief Reads and return the signature record from \p StreamFile's control
4076/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00004077static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
4078 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004079 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00004080 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00004081
4082 // Scan for the CONTROL_BLOCK_ID block.
4083 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4084 return 0;
4085
4086 // Scan for SIGNATURE inside the control block.
4087 ASTReader::RecordData Record;
4088 while (1) {
4089 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4090 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
4091 Entry.Kind != llvm::BitstreamEntry::Record)
4092 return 0;
4093
4094 Record.clear();
4095 StringRef Blob;
4096 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4097 return Record[0];
4098 }
4099}
4100
Guy Benyei11169dd2012-12-18 14:30:41 +00004101/// \brief Retrieve the name of the original source file name
4102/// directly from the AST file, without actually loading the AST
4103/// file.
4104std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
4105 FileManager &FileMgr,
4106 DiagnosticsEngine &Diags) {
4107 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004108 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004109 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004110 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4111 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004112 return std::string();
4113 }
4114
4115 // Initialize the stream
4116 llvm::BitstreamReader StreamFile;
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004117 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
4118 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004119 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004120
4121 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004122 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004123 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4124 return std::string();
4125 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004126
Chris Lattnere7b154b2013-01-19 21:39:22 +00004127 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004128 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004129 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4130 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004131 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004132
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004133 // Scan for ORIGINAL_FILE inside the control block.
4134 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00004135 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004136 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004137 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4138 return std::string();
4139
4140 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4141 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4142 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004143 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004144
Guy Benyei11169dd2012-12-18 14:30:41 +00004145 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004146 StringRef Blob;
4147 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4148 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004149 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004150}
4151
4152namespace {
4153 class SimplePCHValidator : public ASTReaderListener {
4154 const LangOptions &ExistingLangOpts;
4155 const TargetOptions &ExistingTargetOpts;
4156 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004157 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004158 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004159
Guy Benyei11169dd2012-12-18 14:30:41 +00004160 public:
4161 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4162 const TargetOptions &ExistingTargetOpts,
4163 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004164 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004165 FileManager &FileMgr)
4166 : ExistingLangOpts(ExistingLangOpts),
4167 ExistingTargetOpts(ExistingTargetOpts),
4168 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004169 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004170 FileMgr(FileMgr)
4171 {
4172 }
4173
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004174 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4175 bool AllowCompatibleDifferences) override {
4176 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4177 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004178 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004179 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4180 bool AllowCompatibleDifferences) override {
4181 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4182 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004183 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004184 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4185 StringRef SpecificModuleCachePath,
4186 bool Complain) override {
4187 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4188 ExistingModuleCachePath,
4189 nullptr, ExistingLangOpts);
4190 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004191 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4192 bool Complain,
4193 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004194 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004195 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004196 }
4197 };
4198}
4199
4200bool ASTReader::readASTFileControlBlock(StringRef Filename,
4201 FileManager &FileMgr,
4202 ASTReaderListener &Listener) {
4203 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004204 // FIXME: This allows use of the VFS; we do not allow use of the
4205 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004206 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004207 if (!Buffer) {
4208 return true;
4209 }
4210
4211 // Initialize the stream
4212 llvm::BitstreamReader StreamFile;
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004213 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
4214 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004215 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004216
4217 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004218 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004219 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004220
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004221 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004222 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004223 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004224
4225 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004226 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004227 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004228 BitstreamCursor InputFilesCursor;
4229 if (NeedsInputFiles) {
4230 InputFilesCursor = Stream;
4231 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4232 return true;
4233
4234 // Read the abbreviations
4235 while (true) {
4236 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4237 unsigned Code = InputFilesCursor.ReadCode();
4238
4239 // We expect all abbrevs to be at the start of the block.
4240 if (Code != llvm::bitc::DEFINE_ABBREV) {
4241 InputFilesCursor.JumpToBit(Offset);
4242 break;
4243 }
4244 InputFilesCursor.ReadAbbrevRecord();
4245 }
4246 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004247
4248 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004249 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004250 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004251 while (1) {
4252 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4253 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4254 return false;
4255
4256 if (Entry.Kind != llvm::BitstreamEntry::Record)
4257 return true;
4258
Guy Benyei11169dd2012-12-18 14:30:41 +00004259 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004260 StringRef Blob;
4261 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004262 switch ((ControlRecordTypes)RecCode) {
4263 case METADATA: {
4264 if (Record[0] != VERSION_MAJOR)
4265 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004266
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004267 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004268 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004269
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004270 break;
4271 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004272 case MODULE_NAME:
4273 Listener.ReadModuleName(Blob);
4274 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004275 case MODULE_DIRECTORY:
4276 ModuleDir = Blob;
4277 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004278 case MODULE_MAP_FILE: {
4279 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004280 auto Path = ReadString(Record, Idx);
4281 ResolveImportedPath(Path, ModuleDir);
4282 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004283 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004284 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004285 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004286 if (ParseLanguageOptions(Record, false, Listener,
4287 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004288 return true;
4289 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004290
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004291 case TARGET_OPTIONS:
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004292 if (ParseTargetOptions(Record, false, Listener,
4293 /*AllowCompatibleConfigurationMismatch*/ false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004294 return true;
4295 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004296
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004297 case DIAGNOSTIC_OPTIONS:
4298 if (ParseDiagnosticOptions(Record, false, Listener))
4299 return true;
4300 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004301
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004302 case FILE_SYSTEM_OPTIONS:
4303 if (ParseFileSystemOptions(Record, false, Listener))
4304 return true;
4305 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004306
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004307 case HEADER_SEARCH_OPTIONS:
4308 if (ParseHeaderSearchOptions(Record, false, Listener))
4309 return true;
4310 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004311
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004312 case PREPROCESSOR_OPTIONS: {
4313 std::string IgnoredSuggestedPredefines;
4314 if (ParsePreprocessorOptions(Record, false, Listener,
4315 IgnoredSuggestedPredefines))
4316 return true;
4317 break;
4318 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004319
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004320 case INPUT_FILE_OFFSETS: {
4321 if (!NeedsInputFiles)
4322 break;
4323
4324 unsigned NumInputFiles = Record[0];
4325 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004326 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004327 for (unsigned I = 0; I != NumInputFiles; ++I) {
4328 // Go find this input file.
4329 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004330
4331 if (isSystemFile && !NeedsSystemInputFiles)
4332 break; // the rest are system input files
4333
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004334 BitstreamCursor &Cursor = InputFilesCursor;
4335 SavedStreamPosition SavedPosition(Cursor);
4336 Cursor.JumpToBit(InputFileOffs[I]);
4337
4338 unsigned Code = Cursor.ReadCode();
4339 RecordData Record;
4340 StringRef Blob;
4341 bool shouldContinue = false;
4342 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4343 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004344 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004345 std::string Filename = Blob;
4346 ResolveImportedPath(Filename, ModuleDir);
4347 shouldContinue =
4348 Listener.visitInputFile(Filename, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004349 break;
4350 }
4351 if (!shouldContinue)
4352 break;
4353 }
4354 break;
4355 }
4356
Richard Smithd4b230b2014-10-27 23:01:16 +00004357 case IMPORTS: {
4358 if (!NeedsImports)
4359 break;
4360
4361 unsigned Idx = 0, N = Record.size();
4362 while (Idx < N) {
4363 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004364 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004365 std::string Filename = ReadString(Record, Idx);
4366 ResolveImportedPath(Filename, ModuleDir);
4367 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004368 }
4369 break;
4370 }
4371
Richard Smith7f330cd2015-03-18 01:42:29 +00004372 case KNOWN_MODULE_FILES: {
4373 // Known-but-not-technically-used module files are treated as imports.
4374 if (!NeedsImports)
4375 break;
4376
4377 unsigned Idx = 0, N = Record.size();
4378 while (Idx < N) {
4379 std::string Filename = ReadString(Record, Idx);
4380 ResolveImportedPath(Filename, ModuleDir);
4381 Listener.visitImport(Filename);
4382 }
4383 break;
4384 }
4385
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004386 default:
4387 // No other validation to perform.
4388 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004389 }
4390 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004391}
4392
4393
4394bool ASTReader::isAcceptableASTFile(StringRef Filename,
4395 FileManager &FileMgr,
4396 const LangOptions &LangOpts,
4397 const TargetOptions &TargetOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004398 const PreprocessorOptions &PPOpts,
4399 std::string ExistingModuleCachePath) {
4400 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4401 ExistingModuleCachePath, FileMgr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004402 return !readASTFileControlBlock(Filename, FileMgr, validator);
4403}
4404
Ben Langmuir2c9af442014-04-10 17:57:43 +00004405ASTReader::ASTReadResult
4406ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004407 // Enter the submodule block.
4408 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4409 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004410 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004411 }
4412
4413 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4414 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004415 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004416 RecordData Record;
4417 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004418 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4419
4420 switch (Entry.Kind) {
4421 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4422 case llvm::BitstreamEntry::Error:
4423 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004424 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004425 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004426 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004427 case llvm::BitstreamEntry::Record:
4428 // The interesting case.
4429 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004430 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004431
Guy Benyei11169dd2012-12-18 14:30:41 +00004432 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004433 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004434 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004435 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4436
4437 if ((Kind == SUBMODULE_METADATA) != First) {
4438 Error("submodule metadata record should be at beginning of block");
4439 return Failure;
4440 }
4441 First = false;
4442
4443 // Submodule information is only valid if we have a current module.
4444 // FIXME: Should we error on these cases?
4445 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4446 Kind != SUBMODULE_DEFINITION)
4447 continue;
4448
4449 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004450 default: // Default behavior: ignore.
4451 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004452
Richard Smith03478d92014-10-23 22:12:14 +00004453 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004454 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004455 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004456 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004457 }
Richard Smith03478d92014-10-23 22:12:14 +00004458
Chris Lattner0e6c9402013-01-20 02:38:54 +00004459 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004460 unsigned Idx = 0;
4461 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4462 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4463 bool IsFramework = Record[Idx++];
4464 bool IsExplicit = Record[Idx++];
4465 bool IsSystem = Record[Idx++];
4466 bool IsExternC = Record[Idx++];
4467 bool InferSubmodules = Record[Idx++];
4468 bool InferExplicitSubmodules = Record[Idx++];
4469 bool InferExportWildcard = Record[Idx++];
4470 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004471
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004472 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004473 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004474 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004475
Guy Benyei11169dd2012-12-18 14:30:41 +00004476 // Retrieve this (sub)module from the module map, creating it if
4477 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004478 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004479 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004480
4481 // FIXME: set the definition loc for CurrentModule, or call
4482 // ModMap.setInferredModuleAllowedBy()
4483
Guy Benyei11169dd2012-12-18 14:30:41 +00004484 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4485 if (GlobalIndex >= SubmodulesLoaded.size() ||
4486 SubmodulesLoaded[GlobalIndex]) {
4487 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004488 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004489 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004490
Douglas Gregor7029ce12013-03-19 00:28:20 +00004491 if (!ParentModule) {
4492 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4493 if (CurFile != F.File) {
4494 if (!Diags.isDiagnosticInFlight()) {
4495 Diag(diag::err_module_file_conflict)
4496 << CurrentModule->getTopLevelModuleName()
4497 << CurFile->getName()
4498 << F.File->getName();
4499 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004500 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004501 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004502 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004503
4504 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004505 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004506
Guy Benyei11169dd2012-12-18 14:30:41 +00004507 CurrentModule->IsFromModuleFile = true;
4508 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004509 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004510 CurrentModule->InferSubmodules = InferSubmodules;
4511 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4512 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004513 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004514 if (DeserializationListener)
4515 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4516
4517 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004518
Douglas Gregorfb912652013-03-20 21:10:35 +00004519 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004520 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004521 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004522 CurrentModule->UnresolvedConflicts.clear();
4523 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004524 break;
4525 }
4526
4527 case SUBMODULE_UMBRELLA_HEADER: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004528 if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004529 if (!CurrentModule->getUmbrellaHeader())
4530 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4531 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004532 // This can be a spurious difference caused by changing the VFS to
4533 // point to a different copy of the file, and it is too late to
4534 // to rebuild safely.
4535 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4536 // after input file validation only real problems would remain and we
4537 // could just error. For now, assume it's okay.
4538 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004539 }
4540 }
4541 break;
4542 }
4543
Richard Smith202210b2014-10-24 20:23:01 +00004544 case SUBMODULE_HEADER:
4545 case SUBMODULE_EXCLUDED_HEADER:
4546 case SUBMODULE_PRIVATE_HEADER:
4547 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004548 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4549 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004550 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004551
Richard Smith202210b2014-10-24 20:23:01 +00004552 case SUBMODULE_TEXTUAL_HEADER:
4553 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4554 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4555 // them here.
4556 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004557
Guy Benyei11169dd2012-12-18 14:30:41 +00004558 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004559 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004560 break;
4561 }
4562
4563 case SUBMODULE_UMBRELLA_DIR: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004564 if (const DirectoryEntry *Umbrella
Chris Lattner0e6c9402013-01-20 02:38:54 +00004565 = PP.getFileManager().getDirectory(Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004566 if (!CurrentModule->getUmbrellaDir())
4567 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4568 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004569 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4570 Error("mismatched umbrella directories in submodule");
4571 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004572 }
4573 }
4574 break;
4575 }
4576
4577 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004578 F.BaseSubmoduleID = getTotalNumSubmodules();
4579 F.LocalNumSubmodules = Record[0];
4580 unsigned LocalBaseSubmoduleID = Record[1];
4581 if (F.LocalNumSubmodules > 0) {
4582 // Introduce the global -> local mapping for submodules within this
4583 // module.
4584 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4585
4586 // Introduce the local -> global mapping for submodules within this
4587 // module.
4588 F.SubmoduleRemap.insertOrReplace(
4589 std::make_pair(LocalBaseSubmoduleID,
4590 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004591
Ben Langmuir52ca6782014-10-20 16:27:32 +00004592 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4593 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004594 break;
4595 }
4596
4597 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004598 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004599 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004600 Unresolved.File = &F;
4601 Unresolved.Mod = CurrentModule;
4602 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004603 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004604 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004605 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004606 }
4607 break;
4608 }
4609
4610 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004611 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004612 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004613 Unresolved.File = &F;
4614 Unresolved.Mod = CurrentModule;
4615 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004616 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004617 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004618 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004619 }
4620
4621 // Once we've loaded the set of exports, there's no reason to keep
4622 // the parsed, unresolved exports around.
4623 CurrentModule->UnresolvedExports.clear();
4624 break;
4625 }
4626 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004627 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004628 Context.getTargetInfo());
4629 break;
4630 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004631
4632 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004633 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004634 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004635 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004636
4637 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004638 CurrentModule->ConfigMacros.push_back(Blob.str());
4639 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004640
4641 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004642 UnresolvedModuleRef Unresolved;
4643 Unresolved.File = &F;
4644 Unresolved.Mod = CurrentModule;
4645 Unresolved.ID = Record[0];
4646 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4647 Unresolved.IsWildcard = false;
4648 Unresolved.String = Blob;
4649 UnresolvedModuleRefs.push_back(Unresolved);
4650 break;
4651 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004652 }
4653 }
4654}
4655
4656/// \brief Parse the record that corresponds to a LangOptions data
4657/// structure.
4658///
4659/// This routine parses the language options from the AST file and then gives
4660/// them to the AST listener if one is set.
4661///
4662/// \returns true if the listener deems the file unacceptable, false otherwise.
4663bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4664 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004665 ASTReaderListener &Listener,
4666 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004667 LangOptions LangOpts;
4668 unsigned Idx = 0;
4669#define LANGOPT(Name, Bits, Default, Description) \
4670 LangOpts.Name = Record[Idx++];
4671#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4672 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4673#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004674#define SANITIZER(NAME, ID) \
4675 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004676#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004677
4678 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4679 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4680 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4681
4682 unsigned Length = Record[Idx++];
4683 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4684 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004685
4686 Idx += Length;
4687
4688 // Comment options.
4689 for (unsigned N = Record[Idx++]; N; --N) {
4690 LangOpts.CommentOpts.BlockCommandNames.push_back(
4691 ReadString(Record, Idx));
4692 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004693 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004694
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004695 return Listener.ReadLanguageOptions(LangOpts, Complain,
4696 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004697}
4698
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004699bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4700 ASTReaderListener &Listener,
4701 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004702 unsigned Idx = 0;
4703 TargetOptions TargetOpts;
4704 TargetOpts.Triple = ReadString(Record, Idx);
4705 TargetOpts.CPU = ReadString(Record, Idx);
4706 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004707 for (unsigned N = Record[Idx++]; N; --N) {
4708 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4709 }
4710 for (unsigned N = Record[Idx++]; N; --N) {
4711 TargetOpts.Features.push_back(ReadString(Record, Idx));
4712 }
4713
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004714 return Listener.ReadTargetOptions(TargetOpts, Complain,
4715 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004716}
4717
4718bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4719 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004720 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004721 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004722#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004723#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004724 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004725#include "clang/Basic/DiagnosticOptions.def"
4726
Richard Smith3be1cb22014-08-07 00:24:21 +00004727 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004728 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004729 for (unsigned N = Record[Idx++]; N; --N)
4730 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004731
4732 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4733}
4734
4735bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4736 ASTReaderListener &Listener) {
4737 FileSystemOptions FSOpts;
4738 unsigned Idx = 0;
4739 FSOpts.WorkingDir = ReadString(Record, Idx);
4740 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4741}
4742
4743bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4744 bool Complain,
4745 ASTReaderListener &Listener) {
4746 HeaderSearchOptions HSOpts;
4747 unsigned Idx = 0;
4748 HSOpts.Sysroot = ReadString(Record, Idx);
4749
4750 // Include entries.
4751 for (unsigned N = Record[Idx++]; N; --N) {
4752 std::string Path = ReadString(Record, Idx);
4753 frontend::IncludeDirGroup Group
4754 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004755 bool IsFramework = Record[Idx++];
4756 bool IgnoreSysRoot = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004757 HSOpts.UserEntries.push_back(
Daniel Dunbar53681732013-01-30 00:34:26 +00004758 HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
Guy Benyei11169dd2012-12-18 14:30:41 +00004759 }
4760
4761 // System header prefixes.
4762 for (unsigned N = Record[Idx++]; N; --N) {
4763 std::string Prefix = ReadString(Record, Idx);
4764 bool IsSystemHeader = Record[Idx++];
4765 HSOpts.SystemHeaderPrefixes.push_back(
4766 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4767 }
4768
4769 HSOpts.ResourceDir = ReadString(Record, Idx);
4770 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004771 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004772 HSOpts.DisableModuleHash = Record[Idx++];
4773 HSOpts.UseBuiltinIncludes = Record[Idx++];
4774 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4775 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4776 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004777 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004778
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004779 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4780 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004781}
4782
4783bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4784 bool Complain,
4785 ASTReaderListener &Listener,
4786 std::string &SuggestedPredefines) {
4787 PreprocessorOptions PPOpts;
4788 unsigned Idx = 0;
4789
4790 // Macro definitions/undefs
4791 for (unsigned N = Record[Idx++]; N; --N) {
4792 std::string Macro = ReadString(Record, Idx);
4793 bool IsUndef = Record[Idx++];
4794 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4795 }
4796
4797 // Includes
4798 for (unsigned N = Record[Idx++]; N; --N) {
4799 PPOpts.Includes.push_back(ReadString(Record, Idx));
4800 }
4801
4802 // Macro Includes
4803 for (unsigned N = Record[Idx++]; N; --N) {
4804 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4805 }
4806
4807 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004808 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004809 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4810 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4811 PPOpts.ObjCXXARCStandardLibrary =
4812 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4813 SuggestedPredefines.clear();
4814 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4815 SuggestedPredefines);
4816}
4817
4818std::pair<ModuleFile *, unsigned>
4819ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4820 GlobalPreprocessedEntityMapType::iterator
4821 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4822 assert(I != GlobalPreprocessedEntityMap.end() &&
4823 "Corrupted global preprocessed entity map");
4824 ModuleFile *M = I->second;
4825 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4826 return std::make_pair(M, LocalIndex);
4827}
4828
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004829llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004830ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4831 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4832 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4833 Mod.NumPreprocessedEntities);
4834
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004835 return llvm::make_range(PreprocessingRecord::iterator(),
4836 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004837}
4838
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004839llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004840ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004841 return llvm::make_range(
4842 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4843 ModuleDeclIterator(this, &Mod,
4844 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004845}
4846
4847PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4848 PreprocessedEntityID PPID = Index+1;
4849 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4850 ModuleFile &M = *PPInfo.first;
4851 unsigned LocalIndex = PPInfo.second;
4852 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4853
Guy Benyei11169dd2012-12-18 14:30:41 +00004854 if (!PP.getPreprocessingRecord()) {
4855 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004856 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004857 }
4858
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004859 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4860 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4861
4862 llvm::BitstreamEntry Entry =
4863 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4864 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004865 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004866
Guy Benyei11169dd2012-12-18 14:30:41 +00004867 // Read the record.
4868 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4869 ReadSourceLocation(M, PPOffs.End));
4870 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004871 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004872 RecordData Record;
4873 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004874 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4875 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004876 switch (RecType) {
4877 case PPD_MACRO_EXPANSION: {
4878 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004879 IdentifierInfo *Name = nullptr;
4880 MacroDefinition *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004881 if (isBuiltin)
4882 Name = getLocalIdentifier(M, Record[1]);
4883 else {
4884 PreprocessedEntityID
4885 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4886 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4887 }
4888
4889 MacroExpansion *ME;
4890 if (isBuiltin)
4891 ME = new (PPRec) MacroExpansion(Name, Range);
4892 else
4893 ME = new (PPRec) MacroExpansion(Def, Range);
4894
4895 return ME;
4896 }
4897
4898 case PPD_MACRO_DEFINITION: {
4899 // Decode the identifier info and then check again; if the macro is
4900 // still defined and associated with the identifier,
4901 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4902 MacroDefinition *MD
4903 = new (PPRec) MacroDefinition(II, Range);
4904
4905 if (DeserializationListener)
4906 DeserializationListener->MacroDefinitionRead(PPID, MD);
4907
4908 return MD;
4909 }
4910
4911 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004912 const char *FullFileNameStart = Blob.data() + Record[0];
4913 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004914 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004915 if (!FullFileName.empty())
4916 File = PP.getFileManager().getFile(FullFileName);
4917
4918 // FIXME: Stable encoding
4919 InclusionDirective::InclusionKind Kind
4920 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4921 InclusionDirective *ID
4922 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004923 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004924 Record[1], Record[3],
4925 File,
4926 Range);
4927 return ID;
4928 }
4929 }
4930
4931 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4932}
4933
4934/// \brief \arg SLocMapI points at a chunk of a module that contains no
4935/// preprocessed entities or the entities it contains are not the ones we are
4936/// looking for. Find the next module that contains entities and return the ID
4937/// of the first entry.
4938PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4939 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4940 ++SLocMapI;
4941 for (GlobalSLocOffsetMapType::const_iterator
4942 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4943 ModuleFile &M = *SLocMapI->second;
4944 if (M.NumPreprocessedEntities)
4945 return M.BasePreprocessedEntityID;
4946 }
4947
4948 return getTotalNumPreprocessedEntities();
4949}
4950
4951namespace {
4952
4953template <unsigned PPEntityOffset::*PPLoc>
4954struct PPEntityComp {
4955 const ASTReader &Reader;
4956 ModuleFile &M;
4957
4958 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4959
4960 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4961 SourceLocation LHS = getLoc(L);
4962 SourceLocation RHS = getLoc(R);
4963 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4964 }
4965
4966 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4967 SourceLocation LHS = getLoc(L);
4968 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4969 }
4970
4971 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4972 SourceLocation RHS = getLoc(R);
4973 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4974 }
4975
4976 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4977 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4978 }
4979};
4980
4981}
4982
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004983PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4984 bool EndsAfter) const {
4985 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004986 return getTotalNumPreprocessedEntities();
4987
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004988 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4989 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004990 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4991 "Corrupted global sloc offset map");
4992
4993 if (SLocMapI->second->NumPreprocessedEntities == 0)
4994 return findNextPreprocessedEntity(SLocMapI);
4995
4996 ModuleFile &M = *SLocMapI->second;
4997 typedef const PPEntityOffset *pp_iterator;
4998 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4999 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5000
5001 size_t Count = M.NumPreprocessedEntities;
5002 size_t Half;
5003 pp_iterator First = pp_begin;
5004 pp_iterator PPI;
5005
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005006 if (EndsAfter) {
5007 PPI = std::upper_bound(pp_begin, pp_end, Loc,
5008 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
5009 } else {
5010 // Do a binary search manually instead of using std::lower_bound because
5011 // The end locations of entities may be unordered (when a macro expansion
5012 // is inside another macro argument), but for this case it is not important
5013 // whether we get the first macro expansion or its containing macro.
5014 while (Count > 0) {
5015 Half = Count / 2;
5016 PPI = First;
5017 std::advance(PPI, Half);
5018 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
5019 Loc)) {
5020 First = PPI;
5021 ++First;
5022 Count = Count - Half - 1;
5023 } else
5024 Count = Half;
5025 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005026 }
5027
5028 if (PPI == pp_end)
5029 return findNextPreprocessedEntity(SLocMapI);
5030
5031 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5032}
5033
Guy Benyei11169dd2012-12-18 14:30:41 +00005034/// \brief Returns a pair of [Begin, End) indices of preallocated
5035/// preprocessed entities that \arg Range encompasses.
5036std::pair<unsigned, unsigned>
5037 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5038 if (Range.isInvalid())
5039 return std::make_pair(0,0);
5040 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5041
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005042 PreprocessedEntityID BeginID =
5043 findPreprocessedEntity(Range.getBegin(), false);
5044 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005045 return std::make_pair(BeginID, EndID);
5046}
5047
5048/// \brief Optionally returns true or false if the preallocated preprocessed
5049/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005050Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005051 FileID FID) {
5052 if (FID.isInvalid())
5053 return false;
5054
5055 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5056 ModuleFile &M = *PPInfo.first;
5057 unsigned LocalIndex = PPInfo.second;
5058 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5059
5060 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
5061 if (Loc.isInvalid())
5062 return false;
5063
5064 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5065 return true;
5066 else
5067 return false;
5068}
5069
5070namespace {
5071 /// \brief Visitor used to search for information about a header file.
5072 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005073 const FileEntry *FE;
5074
David Blaikie05785d12013-02-20 22:23:23 +00005075 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005076
5077 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005078 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5079 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00005080
5081 static bool visit(ModuleFile &M, void *UserData) {
5082 HeaderFileInfoVisitor *This
5083 = static_cast<HeaderFileInfoVisitor *>(UserData);
5084
Guy Benyei11169dd2012-12-18 14:30:41 +00005085 HeaderFileInfoLookupTable *Table
5086 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5087 if (!Table)
5088 return false;
5089
5090 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00005091 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005092 if (Pos == Table->end())
5093 return false;
5094
5095 This->HFI = *Pos;
5096 return true;
5097 }
5098
David Blaikie05785d12013-02-20 22:23:23 +00005099 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005100 };
5101}
5102
5103HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005104 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005105 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005106 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005107 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00005108
5109 return HeaderFileInfo();
5110}
5111
5112void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5113 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005114 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00005115 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
5116 ModuleFile &F = *(*I);
5117 unsigned Idx = 0;
5118 DiagStates.clear();
5119 assert(!Diag.DiagStates.empty());
5120 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
5121 while (Idx < F.PragmaDiagMappings.size()) {
5122 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5123 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
5124 if (DiagStateID != 0) {
5125 Diag.DiagStatePoints.push_back(
5126 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
5127 FullSourceLoc(Loc, SourceMgr)));
5128 continue;
5129 }
5130
5131 assert(DiagStateID == 0);
5132 // A new DiagState was created here.
5133 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
5134 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
5135 DiagStates.push_back(NewState);
5136 Diag.DiagStatePoints.push_back(
5137 DiagnosticsEngine::DiagStatePoint(NewState,
5138 FullSourceLoc(Loc, SourceMgr)));
5139 while (1) {
5140 assert(Idx < F.PragmaDiagMappings.size() &&
5141 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5142 if (Idx >= F.PragmaDiagMappings.size()) {
5143 break; // Something is messed up but at least avoid infinite loop in
5144 // release build.
5145 }
5146 unsigned DiagID = F.PragmaDiagMappings[Idx++];
5147 if (DiagID == (unsigned)-1) {
5148 break; // no more diag/map pairs for this location.
5149 }
Alp Tokerc726c362014-06-10 09:31:37 +00005150 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
5151 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
5152 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00005153 }
5154 }
5155 }
5156}
5157
5158/// \brief Get the correct cursor and offset for loading a type.
5159ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5160 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5161 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5162 ModuleFile *M = I->second;
5163 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5164}
5165
5166/// \brief Read and return the type with the given index..
5167///
5168/// The index is the type ID, shifted and minus the number of predefs. This
5169/// routine actually reads the record corresponding to the type at the given
5170/// location. It is a helper routine for GetType, which deals with reading type
5171/// IDs.
5172QualType ASTReader::readTypeRecord(unsigned Index) {
5173 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005174 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005175
5176 // Keep track of where we are in the stream, then jump back there
5177 // after reading this type.
5178 SavedStreamPosition SavedPosition(DeclsCursor);
5179
5180 ReadingKindTracker ReadingKind(Read_Type, *this);
5181
5182 // Note that we are loading a type record.
5183 Deserializing AType(this);
5184
5185 unsigned Idx = 0;
5186 DeclsCursor.JumpToBit(Loc.Offset);
5187 RecordData Record;
5188 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005189 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005190 case TYPE_EXT_QUAL: {
5191 if (Record.size() != 2) {
5192 Error("Incorrect encoding of extended qualifier type");
5193 return QualType();
5194 }
5195 QualType Base = readType(*Loc.F, Record, Idx);
5196 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5197 return Context.getQualifiedType(Base, Quals);
5198 }
5199
5200 case TYPE_COMPLEX: {
5201 if (Record.size() != 1) {
5202 Error("Incorrect encoding of complex type");
5203 return QualType();
5204 }
5205 QualType ElemType = readType(*Loc.F, Record, Idx);
5206 return Context.getComplexType(ElemType);
5207 }
5208
5209 case TYPE_POINTER: {
5210 if (Record.size() != 1) {
5211 Error("Incorrect encoding of pointer type");
5212 return QualType();
5213 }
5214 QualType PointeeType = readType(*Loc.F, Record, Idx);
5215 return Context.getPointerType(PointeeType);
5216 }
5217
Reid Kleckner8a365022013-06-24 17:51:48 +00005218 case TYPE_DECAYED: {
5219 if (Record.size() != 1) {
5220 Error("Incorrect encoding of decayed type");
5221 return QualType();
5222 }
5223 QualType OriginalType = readType(*Loc.F, Record, Idx);
5224 QualType DT = Context.getAdjustedParameterType(OriginalType);
5225 if (!isa<DecayedType>(DT))
5226 Error("Decayed type does not decay");
5227 return DT;
5228 }
5229
Reid Kleckner0503a872013-12-05 01:23:43 +00005230 case TYPE_ADJUSTED: {
5231 if (Record.size() != 2) {
5232 Error("Incorrect encoding of adjusted type");
5233 return QualType();
5234 }
5235 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5236 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5237 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5238 }
5239
Guy Benyei11169dd2012-12-18 14:30:41 +00005240 case TYPE_BLOCK_POINTER: {
5241 if (Record.size() != 1) {
5242 Error("Incorrect encoding of block pointer type");
5243 return QualType();
5244 }
5245 QualType PointeeType = readType(*Loc.F, Record, Idx);
5246 return Context.getBlockPointerType(PointeeType);
5247 }
5248
5249 case TYPE_LVALUE_REFERENCE: {
5250 if (Record.size() != 2) {
5251 Error("Incorrect encoding of lvalue reference type");
5252 return QualType();
5253 }
5254 QualType PointeeType = readType(*Loc.F, Record, Idx);
5255 return Context.getLValueReferenceType(PointeeType, Record[1]);
5256 }
5257
5258 case TYPE_RVALUE_REFERENCE: {
5259 if (Record.size() != 1) {
5260 Error("Incorrect encoding of rvalue reference type");
5261 return QualType();
5262 }
5263 QualType PointeeType = readType(*Loc.F, Record, Idx);
5264 return Context.getRValueReferenceType(PointeeType);
5265 }
5266
5267 case TYPE_MEMBER_POINTER: {
5268 if (Record.size() != 2) {
5269 Error("Incorrect encoding of member pointer type");
5270 return QualType();
5271 }
5272 QualType PointeeType = readType(*Loc.F, Record, Idx);
5273 QualType ClassType = readType(*Loc.F, Record, Idx);
5274 if (PointeeType.isNull() || ClassType.isNull())
5275 return QualType();
5276
5277 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5278 }
5279
5280 case TYPE_CONSTANT_ARRAY: {
5281 QualType ElementType = readType(*Loc.F, Record, Idx);
5282 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5283 unsigned IndexTypeQuals = Record[2];
5284 unsigned Idx = 3;
5285 llvm::APInt Size = ReadAPInt(Record, Idx);
5286 return Context.getConstantArrayType(ElementType, Size,
5287 ASM, IndexTypeQuals);
5288 }
5289
5290 case TYPE_INCOMPLETE_ARRAY: {
5291 QualType ElementType = readType(*Loc.F, Record, Idx);
5292 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5293 unsigned IndexTypeQuals = Record[2];
5294 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5295 }
5296
5297 case TYPE_VARIABLE_ARRAY: {
5298 QualType ElementType = readType(*Loc.F, Record, Idx);
5299 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5300 unsigned IndexTypeQuals = Record[2];
5301 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5302 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5303 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5304 ASM, IndexTypeQuals,
5305 SourceRange(LBLoc, RBLoc));
5306 }
5307
5308 case TYPE_VECTOR: {
5309 if (Record.size() != 3) {
5310 Error("incorrect encoding of vector type in AST file");
5311 return QualType();
5312 }
5313
5314 QualType ElementType = readType(*Loc.F, Record, Idx);
5315 unsigned NumElements = Record[1];
5316 unsigned VecKind = Record[2];
5317 return Context.getVectorType(ElementType, NumElements,
5318 (VectorType::VectorKind)VecKind);
5319 }
5320
5321 case TYPE_EXT_VECTOR: {
5322 if (Record.size() != 3) {
5323 Error("incorrect encoding of extended vector type in AST file");
5324 return QualType();
5325 }
5326
5327 QualType ElementType = readType(*Loc.F, Record, Idx);
5328 unsigned NumElements = Record[1];
5329 return Context.getExtVectorType(ElementType, NumElements);
5330 }
5331
5332 case TYPE_FUNCTION_NO_PROTO: {
5333 if (Record.size() != 6) {
5334 Error("incorrect encoding of no-proto function type");
5335 return QualType();
5336 }
5337 QualType ResultType = readType(*Loc.F, Record, Idx);
5338 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5339 (CallingConv)Record[4], Record[5]);
5340 return Context.getFunctionNoProtoType(ResultType, Info);
5341 }
5342
5343 case TYPE_FUNCTION_PROTO: {
5344 QualType ResultType = readType(*Loc.F, Record, Idx);
5345
5346 FunctionProtoType::ExtProtoInfo EPI;
5347 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5348 /*hasregparm*/ Record[2],
5349 /*regparm*/ Record[3],
5350 static_cast<CallingConv>(Record[4]),
5351 /*produces*/ Record[5]);
5352
5353 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005354
5355 EPI.Variadic = Record[Idx++];
5356 EPI.HasTrailingReturn = Record[Idx++];
5357 EPI.TypeQuals = Record[Idx++];
5358 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005359 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005360 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005361
5362 unsigned NumParams = Record[Idx++];
5363 SmallVector<QualType, 16> ParamTypes;
5364 for (unsigned I = 0; I != NumParams; ++I)
5365 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5366
Jordan Rose5c382722013-03-08 21:51:21 +00005367 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005368 }
5369
5370 case TYPE_UNRESOLVED_USING: {
5371 unsigned Idx = 0;
5372 return Context.getTypeDeclType(
5373 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5374 }
5375
5376 case TYPE_TYPEDEF: {
5377 if (Record.size() != 2) {
5378 Error("incorrect encoding of typedef type");
5379 return QualType();
5380 }
5381 unsigned Idx = 0;
5382 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5383 QualType Canonical = readType(*Loc.F, Record, Idx);
5384 if (!Canonical.isNull())
5385 Canonical = Context.getCanonicalType(Canonical);
5386 return Context.getTypedefType(Decl, Canonical);
5387 }
5388
5389 case TYPE_TYPEOF_EXPR:
5390 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5391
5392 case TYPE_TYPEOF: {
5393 if (Record.size() != 1) {
5394 Error("incorrect encoding of typeof(type) in AST file");
5395 return QualType();
5396 }
5397 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5398 return Context.getTypeOfType(UnderlyingType);
5399 }
5400
5401 case TYPE_DECLTYPE: {
5402 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5403 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5404 }
5405
5406 case TYPE_UNARY_TRANSFORM: {
5407 QualType BaseType = readType(*Loc.F, Record, Idx);
5408 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5409 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5410 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5411 }
5412
Richard Smith74aeef52013-04-26 16:15:35 +00005413 case TYPE_AUTO: {
5414 QualType Deduced = readType(*Loc.F, Record, Idx);
5415 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005416 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005417 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005418 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005419
5420 case TYPE_RECORD: {
5421 if (Record.size() != 2) {
5422 Error("incorrect encoding of record type");
5423 return QualType();
5424 }
5425 unsigned Idx = 0;
5426 bool IsDependent = Record[Idx++];
5427 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5428 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5429 QualType T = Context.getRecordType(RD);
5430 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5431 return T;
5432 }
5433
5434 case TYPE_ENUM: {
5435 if (Record.size() != 2) {
5436 Error("incorrect encoding of enum type");
5437 return QualType();
5438 }
5439 unsigned Idx = 0;
5440 bool IsDependent = Record[Idx++];
5441 QualType T
5442 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5443 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5444 return T;
5445 }
5446
5447 case TYPE_ATTRIBUTED: {
5448 if (Record.size() != 3) {
5449 Error("incorrect encoding of attributed type");
5450 return QualType();
5451 }
5452 QualType modifiedType = readType(*Loc.F, Record, Idx);
5453 QualType equivalentType = readType(*Loc.F, Record, Idx);
5454 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5455 return Context.getAttributedType(kind, modifiedType, equivalentType);
5456 }
5457
5458 case TYPE_PAREN: {
5459 if (Record.size() != 1) {
5460 Error("incorrect encoding of paren type");
5461 return QualType();
5462 }
5463 QualType InnerType = readType(*Loc.F, Record, Idx);
5464 return Context.getParenType(InnerType);
5465 }
5466
5467 case TYPE_PACK_EXPANSION: {
5468 if (Record.size() != 2) {
5469 Error("incorrect encoding of pack expansion type");
5470 return QualType();
5471 }
5472 QualType Pattern = readType(*Loc.F, Record, Idx);
5473 if (Pattern.isNull())
5474 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005475 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005476 if (Record[1])
5477 NumExpansions = Record[1] - 1;
5478 return Context.getPackExpansionType(Pattern, NumExpansions);
5479 }
5480
5481 case TYPE_ELABORATED: {
5482 unsigned Idx = 0;
5483 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5484 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5485 QualType NamedType = readType(*Loc.F, Record, Idx);
5486 return Context.getElaboratedType(Keyword, NNS, NamedType);
5487 }
5488
5489 case TYPE_OBJC_INTERFACE: {
5490 unsigned Idx = 0;
5491 ObjCInterfaceDecl *ItfD
5492 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5493 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5494 }
5495
5496 case TYPE_OBJC_OBJECT: {
5497 unsigned Idx = 0;
5498 QualType Base = readType(*Loc.F, Record, Idx);
5499 unsigned NumProtos = Record[Idx++];
5500 SmallVector<ObjCProtocolDecl*, 4> Protos;
5501 for (unsigned I = 0; I != NumProtos; ++I)
5502 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5503 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5504 }
5505
5506 case TYPE_OBJC_OBJECT_POINTER: {
5507 unsigned Idx = 0;
5508 QualType Pointee = readType(*Loc.F, Record, Idx);
5509 return Context.getObjCObjectPointerType(Pointee);
5510 }
5511
5512 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5513 unsigned Idx = 0;
5514 QualType Parm = readType(*Loc.F, Record, Idx);
5515 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005516 return Context.getSubstTemplateTypeParmType(
5517 cast<TemplateTypeParmType>(Parm),
5518 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005519 }
5520
5521 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5522 unsigned Idx = 0;
5523 QualType Parm = readType(*Loc.F, Record, Idx);
5524 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5525 return Context.getSubstTemplateTypeParmPackType(
5526 cast<TemplateTypeParmType>(Parm),
5527 ArgPack);
5528 }
5529
5530 case TYPE_INJECTED_CLASS_NAME: {
5531 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5532 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5533 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5534 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005535 const Type *T = nullptr;
5536 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5537 if (const Type *Existing = DI->getTypeForDecl()) {
5538 T = Existing;
5539 break;
5540 }
5541 }
5542 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005543 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005544 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5545 DI->setTypeForDecl(T);
5546 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005547 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005548 }
5549
5550 case TYPE_TEMPLATE_TYPE_PARM: {
5551 unsigned Idx = 0;
5552 unsigned Depth = Record[Idx++];
5553 unsigned Index = Record[Idx++];
5554 bool Pack = Record[Idx++];
5555 TemplateTypeParmDecl *D
5556 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5557 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5558 }
5559
5560 case TYPE_DEPENDENT_NAME: {
5561 unsigned Idx = 0;
5562 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5563 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5564 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5565 QualType Canon = readType(*Loc.F, Record, Idx);
5566 if (!Canon.isNull())
5567 Canon = Context.getCanonicalType(Canon);
5568 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5569 }
5570
5571 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5572 unsigned Idx = 0;
5573 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5574 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5575 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5576 unsigned NumArgs = Record[Idx++];
5577 SmallVector<TemplateArgument, 8> Args;
5578 Args.reserve(NumArgs);
5579 while (NumArgs--)
5580 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5581 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5582 Args.size(), Args.data());
5583 }
5584
5585 case TYPE_DEPENDENT_SIZED_ARRAY: {
5586 unsigned Idx = 0;
5587
5588 // ArrayType
5589 QualType ElementType = readType(*Loc.F, Record, Idx);
5590 ArrayType::ArraySizeModifier ASM
5591 = (ArrayType::ArraySizeModifier)Record[Idx++];
5592 unsigned IndexTypeQuals = Record[Idx++];
5593
5594 // DependentSizedArrayType
5595 Expr *NumElts = ReadExpr(*Loc.F);
5596 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5597
5598 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5599 IndexTypeQuals, Brackets);
5600 }
5601
5602 case TYPE_TEMPLATE_SPECIALIZATION: {
5603 unsigned Idx = 0;
5604 bool IsDependent = Record[Idx++];
5605 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5606 SmallVector<TemplateArgument, 8> Args;
5607 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5608 QualType Underlying = readType(*Loc.F, Record, Idx);
5609 QualType T;
5610 if (Underlying.isNull())
5611 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5612 Args.size());
5613 else
5614 T = Context.getTemplateSpecializationType(Name, Args.data(),
5615 Args.size(), Underlying);
5616 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5617 return T;
5618 }
5619
5620 case TYPE_ATOMIC: {
5621 if (Record.size() != 1) {
5622 Error("Incorrect encoding of atomic type");
5623 return QualType();
5624 }
5625 QualType ValueType = readType(*Loc.F, Record, Idx);
5626 return Context.getAtomicType(ValueType);
5627 }
5628 }
5629 llvm_unreachable("Invalid TypeCode!");
5630}
5631
Richard Smith564417a2014-03-20 21:47:22 +00005632void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5633 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005634 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005635 const RecordData &Record, unsigned &Idx) {
5636 ExceptionSpecificationType EST =
5637 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005638 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005639 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005640 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005641 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005642 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005643 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005644 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005645 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005646 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5647 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005648 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005649 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005650 }
5651}
5652
Guy Benyei11169dd2012-12-18 14:30:41 +00005653class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5654 ASTReader &Reader;
5655 ModuleFile &F;
5656 const ASTReader::RecordData &Record;
5657 unsigned &Idx;
5658
5659 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5660 unsigned &I) {
5661 return Reader.ReadSourceLocation(F, R, I);
5662 }
5663
5664 template<typename T>
5665 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5666 return Reader.ReadDeclAs<T>(F, Record, Idx);
5667 }
5668
5669public:
5670 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5671 const ASTReader::RecordData &Record, unsigned &Idx)
5672 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5673 { }
5674
5675 // We want compile-time assurance that we've enumerated all of
5676 // these, so unfortunately we have to declare them first, then
5677 // define them out-of-line.
5678#define ABSTRACT_TYPELOC(CLASS, PARENT)
5679#define TYPELOC(CLASS, PARENT) \
5680 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5681#include "clang/AST/TypeLocNodes.def"
5682
5683 void VisitFunctionTypeLoc(FunctionTypeLoc);
5684 void VisitArrayTypeLoc(ArrayTypeLoc);
5685};
5686
5687void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5688 // nothing to do
5689}
5690void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5691 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5692 if (TL.needsExtraLocalData()) {
5693 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5694 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5695 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5696 TL.setModeAttr(Record[Idx++]);
5697 }
5698}
5699void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5700 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5701}
5702void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5703 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5704}
Reid Kleckner8a365022013-06-24 17:51:48 +00005705void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5706 // nothing to do
5707}
Reid Kleckner0503a872013-12-05 01:23:43 +00005708void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5709 // nothing to do
5710}
Guy Benyei11169dd2012-12-18 14:30:41 +00005711void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5712 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5713}
5714void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5715 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5716}
5717void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5718 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5719}
5720void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5721 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5722 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5723}
5724void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5725 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5726 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5727 if (Record[Idx++])
5728 TL.setSizeExpr(Reader.ReadExpr(F));
5729 else
Craig Toppera13603a2014-05-22 05:54:18 +00005730 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005731}
5732void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5733 VisitArrayTypeLoc(TL);
5734}
5735void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5736 VisitArrayTypeLoc(TL);
5737}
5738void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5739 VisitArrayTypeLoc(TL);
5740}
5741void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5742 DependentSizedArrayTypeLoc TL) {
5743 VisitArrayTypeLoc(TL);
5744}
5745void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5746 DependentSizedExtVectorTypeLoc TL) {
5747 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5748}
5749void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5750 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5751}
5752void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5753 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5754}
5755void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5756 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5757 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5758 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5759 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005760 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5761 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005762 }
5763}
5764void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5765 VisitFunctionTypeLoc(TL);
5766}
5767void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5768 VisitFunctionTypeLoc(TL);
5769}
5770void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5771 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5772}
5773void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5774 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5775}
5776void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5777 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5778 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5779 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5780}
5781void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5782 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5783 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5784 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5785 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5786}
5787void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5788 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5789}
5790void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5791 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5792 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5793 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5794 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5795}
5796void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5797 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5798}
5799void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5800 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5801}
5802void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5803 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5804}
5805void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5806 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5807 if (TL.hasAttrOperand()) {
5808 SourceRange range;
5809 range.setBegin(ReadSourceLocation(Record, Idx));
5810 range.setEnd(ReadSourceLocation(Record, Idx));
5811 TL.setAttrOperandParensRange(range);
5812 }
5813 if (TL.hasAttrExprOperand()) {
5814 if (Record[Idx++])
5815 TL.setAttrExprOperand(Reader.ReadExpr(F));
5816 else
Craig Toppera13603a2014-05-22 05:54:18 +00005817 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005818 } else if (TL.hasAttrEnumOperand())
5819 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5820}
5821void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5822 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5823}
5824void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5825 SubstTemplateTypeParmTypeLoc TL) {
5826 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5827}
5828void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5829 SubstTemplateTypeParmPackTypeLoc TL) {
5830 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5831}
5832void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5833 TemplateSpecializationTypeLoc TL) {
5834 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5835 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5836 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5837 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5838 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5839 TL.setArgLocInfo(i,
5840 Reader.GetTemplateArgumentLocInfo(F,
5841 TL.getTypePtr()->getArg(i).getKind(),
5842 Record, Idx));
5843}
5844void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5845 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5846 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5847}
5848void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5849 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5850 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5851}
5852void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5853 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5854}
5855void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5856 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5857 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5858 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5859}
5860void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5861 DependentTemplateSpecializationTypeLoc TL) {
5862 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5863 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5864 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5865 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5866 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5867 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5868 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5869 TL.setArgLocInfo(I,
5870 Reader.GetTemplateArgumentLocInfo(F,
5871 TL.getTypePtr()->getArg(I).getKind(),
5872 Record, Idx));
5873}
5874void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5875 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5876}
5877void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5878 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5879}
5880void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5881 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5882 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5883 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5884 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5885 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5886}
5887void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5888 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5889}
5890void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5891 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5892 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5893 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5894}
5895
5896TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5897 const RecordData &Record,
5898 unsigned &Idx) {
5899 QualType InfoTy = readType(F, Record, Idx);
5900 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005901 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005902
5903 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5904 TypeLocReader TLR(*this, F, Record, Idx);
5905 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5906 TLR.Visit(TL);
5907 return TInfo;
5908}
5909
5910QualType ASTReader::GetType(TypeID ID) {
5911 unsigned FastQuals = ID & Qualifiers::FastMask;
5912 unsigned Index = ID >> Qualifiers::FastWidth;
5913
5914 if (Index < NUM_PREDEF_TYPE_IDS) {
5915 QualType T;
5916 switch ((PredefinedTypeIDs)Index) {
5917 case PREDEF_TYPE_NULL_ID: return QualType();
5918 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5919 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5920
5921 case PREDEF_TYPE_CHAR_U_ID:
5922 case PREDEF_TYPE_CHAR_S_ID:
5923 // FIXME: Check that the signedness of CharTy is correct!
5924 T = Context.CharTy;
5925 break;
5926
5927 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5928 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5929 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5930 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5931 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5932 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5933 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5934 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5935 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5936 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5937 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5938 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5939 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5940 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5941 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5942 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5943 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5944 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5945 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5946 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5947 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5948 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5949 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5950 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5951 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5952 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5953 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5954 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005955 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5956 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5957 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5958 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5959 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5960 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005961 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005962 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005963 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5964
5965 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5966 T = Context.getAutoRRefDeductType();
5967 break;
5968
5969 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5970 T = Context.ARCUnbridgedCastTy;
5971 break;
5972
5973 case PREDEF_TYPE_VA_LIST_TAG:
5974 T = Context.getVaListTagType();
5975 break;
5976
5977 case PREDEF_TYPE_BUILTIN_FN:
5978 T = Context.BuiltinFnTy;
5979 break;
5980 }
5981
5982 assert(!T.isNull() && "Unknown predefined type");
5983 return T.withFastQualifiers(FastQuals);
5984 }
5985
5986 Index -= NUM_PREDEF_TYPE_IDS;
5987 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5988 if (TypesLoaded[Index].isNull()) {
5989 TypesLoaded[Index] = readTypeRecord(Index);
5990 if (TypesLoaded[Index].isNull())
5991 return QualType();
5992
5993 TypesLoaded[Index]->setFromAST();
5994 if (DeserializationListener)
5995 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5996 TypesLoaded[Index]);
5997 }
5998
5999 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6000}
6001
6002QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6003 return GetType(getGlobalTypeID(F, LocalID));
6004}
6005
6006serialization::TypeID
6007ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6008 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6009 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6010
6011 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6012 return LocalID;
6013
6014 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6015 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6016 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6017
6018 unsigned GlobalIndex = LocalIndex + I->second;
6019 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6020}
6021
6022TemplateArgumentLocInfo
6023ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6024 TemplateArgument::ArgKind Kind,
6025 const RecordData &Record,
6026 unsigned &Index) {
6027 switch (Kind) {
6028 case TemplateArgument::Expression:
6029 return ReadExpr(F);
6030 case TemplateArgument::Type:
6031 return GetTypeSourceInfo(F, Record, Index);
6032 case TemplateArgument::Template: {
6033 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6034 Index);
6035 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6036 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6037 SourceLocation());
6038 }
6039 case TemplateArgument::TemplateExpansion: {
6040 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6041 Index);
6042 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6043 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6044 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6045 EllipsisLoc);
6046 }
6047 case TemplateArgument::Null:
6048 case TemplateArgument::Integral:
6049 case TemplateArgument::Declaration:
6050 case TemplateArgument::NullPtr:
6051 case TemplateArgument::Pack:
6052 // FIXME: Is this right?
6053 return TemplateArgumentLocInfo();
6054 }
6055 llvm_unreachable("unexpected template argument loc");
6056}
6057
6058TemplateArgumentLoc
6059ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6060 const RecordData &Record, unsigned &Index) {
6061 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6062
6063 if (Arg.getKind() == TemplateArgument::Expression) {
6064 if (Record[Index++]) // bool InfoHasSameExpr.
6065 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6066 }
6067 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6068 Record, Index));
6069}
6070
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006071const ASTTemplateArgumentListInfo*
6072ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6073 const RecordData &Record,
6074 unsigned &Index) {
6075 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6076 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6077 unsigned NumArgsAsWritten = Record[Index++];
6078 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6079 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6080 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6081 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6082}
6083
Guy Benyei11169dd2012-12-18 14:30:41 +00006084Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6085 return GetDecl(ID);
6086}
6087
Richard Smith50895422015-01-31 03:04:55 +00006088template<typename TemplateSpecializationDecl>
6089static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6090 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6091 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6092}
6093
Richard Smith053f6c62014-05-16 23:01:30 +00006094void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006095 if (NumCurrentElementsDeserializing) {
6096 // We arrange to not care about the complete redeclaration chain while we're
6097 // deserializing. Just remember that the AST has marked this one as complete
6098 // but that it's not actually complete yet, so we know we still need to
6099 // complete it later.
6100 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6101 return;
6102 }
6103
Richard Smith053f6c62014-05-16 23:01:30 +00006104 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6105
Richard Smith053f6c62014-05-16 23:01:30 +00006106 // If this is a named declaration, complete it by looking it up
6107 // within its context.
6108 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006109 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006110 // all mergeable entities within it.
6111 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6112 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6113 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
6114 auto *II = Name.getAsIdentifierInfo();
6115 if (isa<TranslationUnitDecl>(DC) && II) {
6116 // Outside of C++, we don't have a lookup table for the TU, so update
6117 // the identifier instead. In C++, either way should work fine.
6118 if (II->isOutOfDate())
6119 updateOutOfDateIdentifier(*II);
6120 } else
6121 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006122 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
6123 // FIXME: It'd be nice to do something a bit more targeted here.
6124 D->getDeclContext()->decls_begin();
Richard Smith053f6c62014-05-16 23:01:30 +00006125 }
6126 }
Richard Smith50895422015-01-31 03:04:55 +00006127
6128 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6129 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6130 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6131 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6132 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6133 if (auto *Template = FD->getPrimaryTemplate())
6134 Template->LoadLazySpecializations();
6135 }
Richard Smith053f6c62014-05-16 23:01:30 +00006136}
6137
Richard Smithc2bb8182015-03-24 06:36:48 +00006138uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
6139 const RecordData &Record,
6140 unsigned &Idx) {
6141 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
6142 Error("malformed AST file: missing C++ ctor initializers");
6143 return 0;
6144 }
6145
6146 unsigned LocalID = Record[Idx++];
6147 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
6148}
6149
6150CXXCtorInitializer **
6151ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6152 RecordLocation Loc = getLocalBitOffset(Offset);
6153 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6154 SavedStreamPosition SavedPosition(Cursor);
6155 Cursor.JumpToBit(Loc.Offset);
6156 ReadingKindTracker ReadingKind(Read_Decl, *this);
6157
6158 RecordData Record;
6159 unsigned Code = Cursor.ReadCode();
6160 unsigned RecCode = Cursor.readRecord(Code, Record);
6161 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6162 Error("malformed AST file: missing C++ ctor initializers");
6163 return nullptr;
6164 }
6165
6166 unsigned Idx = 0;
6167 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6168}
6169
Richard Smithcd45dbc2014-04-19 03:48:30 +00006170uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6171 const RecordData &Record,
6172 unsigned &Idx) {
6173 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6174 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006175 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006176 }
6177
Guy Benyei11169dd2012-12-18 14:30:41 +00006178 unsigned LocalID = Record[Idx++];
6179 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6180}
6181
6182CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6183 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006184 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006185 SavedStreamPosition SavedPosition(Cursor);
6186 Cursor.JumpToBit(Loc.Offset);
6187 ReadingKindTracker ReadingKind(Read_Decl, *this);
6188 RecordData Record;
6189 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006190 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006191 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006192 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006193 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006194 }
6195
6196 unsigned Idx = 0;
6197 unsigned NumBases = Record[Idx++];
6198 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6199 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6200 for (unsigned I = 0; I != NumBases; ++I)
6201 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6202 return Bases;
6203}
6204
6205serialization::DeclID
6206ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6207 if (LocalID < NUM_PREDEF_DECL_IDS)
6208 return LocalID;
6209
6210 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6211 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6212 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6213
6214 return LocalID + I->second;
6215}
6216
6217bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6218 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006219 // Predefined decls aren't from any module.
6220 if (ID < NUM_PREDEF_DECL_IDS)
6221 return false;
6222
Guy Benyei11169dd2012-12-18 14:30:41 +00006223 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
6224 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6225 return &M == I->second;
6226}
6227
Douglas Gregor9f782892013-01-21 15:25:38 +00006228ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006229 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006230 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006231 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6232 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6233 return I->second;
6234}
6235
6236SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6237 if (ID < NUM_PREDEF_DECL_IDS)
6238 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006239
Guy Benyei11169dd2012-12-18 14:30:41 +00006240 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6241
6242 if (Index > DeclsLoaded.size()) {
6243 Error("declaration ID out-of-range for AST file");
6244 return SourceLocation();
6245 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006246
Guy Benyei11169dd2012-12-18 14:30:41 +00006247 if (Decl *D = DeclsLoaded[Index])
6248 return D->getLocation();
6249
6250 unsigned RawLocation = 0;
6251 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6252 return ReadSourceLocation(*Rec.F, RawLocation);
6253}
6254
Richard Smithfe620d22015-03-05 23:24:12 +00006255static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6256 switch (ID) {
6257 case PREDEF_DECL_NULL_ID:
6258 return nullptr;
6259
6260 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6261 return Context.getTranslationUnitDecl();
6262
6263 case PREDEF_DECL_OBJC_ID_ID:
6264 return Context.getObjCIdDecl();
6265
6266 case PREDEF_DECL_OBJC_SEL_ID:
6267 return Context.getObjCSelDecl();
6268
6269 case PREDEF_DECL_OBJC_CLASS_ID:
6270 return Context.getObjCClassDecl();
6271
6272 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6273 return Context.getObjCProtocolDecl();
6274
6275 case PREDEF_DECL_INT_128_ID:
6276 return Context.getInt128Decl();
6277
6278 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6279 return Context.getUInt128Decl();
6280
6281 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6282 return Context.getObjCInstanceTypeDecl();
6283
6284 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6285 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006286
6287 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6288 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006289 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006290 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006291}
6292
Richard Smithcd45dbc2014-04-19 03:48:30 +00006293Decl *ASTReader::GetExistingDecl(DeclID ID) {
6294 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006295 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6296 if (D) {
6297 // Track that we have merged the declaration with ID \p ID into the
6298 // pre-existing predefined declaration \p D.
6299 auto &Merged = MergedDecls[D->getCanonicalDecl()];
6300 if (Merged.empty())
6301 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006302 }
Richard Smithfe620d22015-03-05 23:24:12 +00006303 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006304 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006305
Guy Benyei11169dd2012-12-18 14:30:41 +00006306 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6307
6308 if (Index >= DeclsLoaded.size()) {
6309 assert(0 && "declaration ID out-of-range for AST file");
6310 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006311 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006312 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006313
6314 return DeclsLoaded[Index];
6315}
6316
6317Decl *ASTReader::GetDecl(DeclID ID) {
6318 if (ID < NUM_PREDEF_DECL_IDS)
6319 return GetExistingDecl(ID);
6320
6321 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6322
6323 if (Index >= DeclsLoaded.size()) {
6324 assert(0 && "declaration ID out-of-range for AST file");
6325 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006326 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006327 }
6328
Guy Benyei11169dd2012-12-18 14:30:41 +00006329 if (!DeclsLoaded[Index]) {
6330 ReadDeclRecord(ID);
6331 if (DeserializationListener)
6332 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6333 }
6334
6335 return DeclsLoaded[Index];
6336}
6337
6338DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6339 DeclID GlobalID) {
6340 if (GlobalID < NUM_PREDEF_DECL_IDS)
6341 return GlobalID;
6342
6343 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6344 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6345 ModuleFile *Owner = I->second;
6346
6347 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6348 = M.GlobalToLocalDeclIDs.find(Owner);
6349 if (Pos == M.GlobalToLocalDeclIDs.end())
6350 return 0;
6351
6352 return GlobalID - Owner->BaseDeclID + Pos->second;
6353}
6354
6355serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6356 const RecordData &Record,
6357 unsigned &Idx) {
6358 if (Idx >= Record.size()) {
6359 Error("Corrupted AST file");
6360 return 0;
6361 }
6362
6363 return getGlobalDeclID(F, Record[Idx++]);
6364}
6365
6366/// \brief Resolve the offset of a statement into a statement.
6367///
6368/// This operation will read a new statement from the external
6369/// source each time it is called, and is meant to be used via a
6370/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6371Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6372 // Switch case IDs are per Decl.
6373 ClearSwitchCaseIDs();
6374
6375 // Offset here is a global offset across the entire chain.
6376 RecordLocation Loc = getLocalBitOffset(Offset);
6377 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6378 return ReadStmtFromStream(*Loc.F);
6379}
6380
6381namespace {
6382 class FindExternalLexicalDeclsVisitor {
6383 ASTReader &Reader;
6384 const DeclContext *DC;
6385 bool (*isKindWeWant)(Decl::Kind);
6386
6387 SmallVectorImpl<Decl*> &Decls;
6388 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6389
6390 public:
6391 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6392 bool (*isKindWeWant)(Decl::Kind),
6393 SmallVectorImpl<Decl*> &Decls)
6394 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6395 {
6396 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6397 PredefsVisited[I] = false;
6398 }
6399
6400 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
6401 if (Preorder)
6402 return false;
6403
6404 FindExternalLexicalDeclsVisitor *This
6405 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6406
6407 ModuleFile::DeclContextInfosMap::iterator Info
6408 = M.DeclContextInfos.find(This->DC);
6409 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6410 return false;
6411
6412 // Load all of the declaration IDs
6413 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6414 *IDE = ID + Info->second.NumLexicalDecls;
6415 ID != IDE; ++ID) {
6416 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6417 continue;
6418
6419 // Don't add predefined declarations to the lexical context more
6420 // than once.
6421 if (ID->second < NUM_PREDEF_DECL_IDS) {
6422 if (This->PredefsVisited[ID->second])
6423 continue;
6424
6425 This->PredefsVisited[ID->second] = true;
6426 }
6427
6428 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6429 if (!This->DC->isDeclInLexicalTraversal(D))
6430 This->Decls.push_back(D);
6431 }
6432 }
6433
6434 return false;
6435 }
6436 };
6437}
6438
6439ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6440 bool (*isKindWeWant)(Decl::Kind),
6441 SmallVectorImpl<Decl*> &Decls) {
6442 // There might be lexical decls in multiple modules, for the TU at
6443 // least. Walk all of the modules in the order they were loaded.
6444 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6445 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
6446 ++NumLexicalDeclContextsRead;
6447 return ELR_Success;
6448}
6449
6450namespace {
6451
6452class DeclIDComp {
6453 ASTReader &Reader;
6454 ModuleFile &Mod;
6455
6456public:
6457 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6458
6459 bool operator()(LocalDeclID L, LocalDeclID R) const {
6460 SourceLocation LHS = getLocation(L);
6461 SourceLocation RHS = getLocation(R);
6462 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6463 }
6464
6465 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6466 SourceLocation RHS = getLocation(R);
6467 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6468 }
6469
6470 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6471 SourceLocation LHS = getLocation(L);
6472 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6473 }
6474
6475 SourceLocation getLocation(LocalDeclID ID) const {
6476 return Reader.getSourceManager().getFileLoc(
6477 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6478 }
6479};
6480
6481}
6482
6483void ASTReader::FindFileRegionDecls(FileID File,
6484 unsigned Offset, unsigned Length,
6485 SmallVectorImpl<Decl *> &Decls) {
6486 SourceManager &SM = getSourceManager();
6487
6488 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6489 if (I == FileDeclIDs.end())
6490 return;
6491
6492 FileDeclsInfo &DInfo = I->second;
6493 if (DInfo.Decls.empty())
6494 return;
6495
6496 SourceLocation
6497 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6498 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6499
6500 DeclIDComp DIDComp(*this, *DInfo.Mod);
6501 ArrayRef<serialization::LocalDeclID>::iterator
6502 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6503 BeginLoc, DIDComp);
6504 if (BeginIt != DInfo.Decls.begin())
6505 --BeginIt;
6506
6507 // If we are pointing at a top-level decl inside an objc container, we need
6508 // to backtrack until we find it otherwise we will fail to report that the
6509 // region overlaps with an objc container.
6510 while (BeginIt != DInfo.Decls.begin() &&
6511 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6512 ->isTopLevelDeclInObjCContainer())
6513 --BeginIt;
6514
6515 ArrayRef<serialization::LocalDeclID>::iterator
6516 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6517 EndLoc, DIDComp);
6518 if (EndIt != DInfo.Decls.end())
6519 ++EndIt;
6520
6521 for (ArrayRef<serialization::LocalDeclID>::iterator
6522 DIt = BeginIt; DIt != EndIt; ++DIt)
6523 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6524}
6525
6526namespace {
6527 /// \brief ModuleFile visitor used to perform name lookup into a
6528 /// declaration context.
6529 class DeclContextNameLookupVisitor {
6530 ASTReader &Reader;
Richard Smith8c913ec2014-08-14 02:21:01 +00006531 ArrayRef<const DeclContext *> Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006532 DeclarationName Name;
6533 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006534 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006535
6536 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006537 DeclContextNameLookupVisitor(ASTReader &Reader,
6538 ArrayRef<const DeclContext *> Contexts,
Guy Benyei11169dd2012-12-18 14:30:41 +00006539 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006540 SmallVectorImpl<NamedDecl *> &Decls,
6541 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
6542 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls),
6543 DeclSet(DeclSet) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006544
6545 static bool visit(ModuleFile &M, void *UserData) {
6546 DeclContextNameLookupVisitor *This
6547 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6548
6549 // Check whether we have any visible declaration information for
6550 // this context in this module.
6551 ModuleFile::DeclContextInfosMap::iterator Info;
6552 bool FoundInfo = false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006553 for (auto *DC : This->Contexts) {
6554 Info = M.DeclContextInfos.find(DC);
6555 if (Info != M.DeclContextInfos.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006556 Info->second.NameLookupTableData) {
6557 FoundInfo = true;
6558 break;
6559 }
6560 }
6561
6562 if (!FoundInfo)
6563 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006564
Guy Benyei11169dd2012-12-18 14:30:41 +00006565 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006566 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006567 Info->second.NameLookupTableData;
6568 ASTDeclContextNameLookupTable::iterator Pos
6569 = LookupTable->find(This->Name);
6570 if (Pos == LookupTable->end())
6571 return false;
6572
6573 bool FoundAnything = false;
6574 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6575 for (; Data.first != Data.second; ++Data.first) {
6576 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6577 if (!ND)
6578 continue;
6579
6580 if (ND->getDeclName() != This->Name) {
6581 // A name might be null because the decl's redeclarable part is
6582 // currently read before reading its name. The lookup is triggered by
6583 // building that decl (likely indirectly), and so it is later in the
6584 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006585 // FIXME: This should not happen; deserializing declarations should
6586 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006587 continue;
6588 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006589
Guy Benyei11169dd2012-12-18 14:30:41 +00006590 // Record this declaration.
6591 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006592 if (This->DeclSet.insert(ND).second)
6593 This->Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006594 }
6595
6596 return FoundAnything;
6597 }
6598 };
6599}
6600
Douglas Gregor9f782892013-01-21 15:25:38 +00006601/// \brief Retrieve the "definitive" module file for the definition of the
6602/// given declaration context, if there is one.
6603///
6604/// The "definitive" module file is the only place where we need to look to
6605/// find information about the declarations within the given declaration
6606/// context. For example, C++ and Objective-C classes, C structs/unions, and
6607/// Objective-C protocols, categories, and extensions are all defined in a
6608/// single place in the source code, so they have definitive module files
6609/// associated with them. C++ namespaces, on the other hand, can have
6610/// definitions in multiple different module files.
6611///
6612/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6613/// NDEBUG checking.
6614static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6615 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006616 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6617 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006618
Craig Toppera13603a2014-05-22 05:54:18 +00006619 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006620}
6621
Richard Smith9ce12e32013-02-07 03:30:24 +00006622bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006623ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6624 DeclarationName Name) {
6625 assert(DC->hasExternalVisibleStorage() &&
6626 "DeclContext has no visible decls in storage");
6627 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006628 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006629
Richard Smith8c913ec2014-08-14 02:21:01 +00006630 Deserializing LookupResults(this);
6631
Guy Benyei11169dd2012-12-18 14:30:41 +00006632 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006633 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006634
Guy Benyei11169dd2012-12-18 14:30:41 +00006635 // Compute the declaration contexts we need to look into. Multiple such
6636 // declaration contexts occur when two declaration contexts from disjoint
6637 // modules get merged, e.g., when two namespaces with the same name are
6638 // independently defined in separate modules.
6639 SmallVector<const DeclContext *, 2> Contexts;
6640 Contexts.push_back(DC);
Richard Smith8c913ec2014-08-14 02:21:01 +00006641
Guy Benyei11169dd2012-12-18 14:30:41 +00006642 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006643 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006644 if (Merged != MergedDecls.end()) {
6645 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6646 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6647 }
6648 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006649
6650 auto LookUpInContexts = [&](ArrayRef<const DeclContext*> Contexts) {
Richard Smith52874ec2015-02-13 20:17:14 +00006651 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls, DeclSet);
Richard Smith8c913ec2014-08-14 02:21:01 +00006652
6653 // If we can definitively determine which module file to look into,
6654 // only look there. Otherwise, look in all module files.
6655 ModuleFile *Definitive;
6656 if (Contexts.size() == 1 &&
6657 (Definitive = getDefinitiveModuleFileFor(Contexts[0], *this))) {
6658 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6659 } else {
6660 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6661 }
6662 };
6663
6664 LookUpInContexts(Contexts);
6665
6666 // If this might be an implicit special member function, then also search
6667 // all merged definitions of the surrounding class. We need to search them
6668 // individually, because finding an entity in one of them doesn't imply that
6669 // we can't find a different entity in another one.
Richard Smithcd45dbc2014-04-19 03:48:30 +00006670 if (isa<CXXRecordDecl>(DC)) {
Richard Smith02793752015-03-27 21:16:39 +00006671 auto Merged = MergedLookups.find(DC);
6672 if (Merged != MergedLookups.end()) {
6673 for (unsigned I = 0; I != Merged->second.size(); ++I) {
6674 const DeclContext *Context = Merged->second[I];
6675 LookUpInContexts(Context);
6676 // We might have just added some more merged lookups. If so, our
6677 // iterator is now invalid, so grab a fresh one before continuing.
6678 Merged = MergedLookups.find(DC);
Richard Smithe0612472014-11-21 05:16:13 +00006679 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006680 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006681 }
6682
Guy Benyei11169dd2012-12-18 14:30:41 +00006683 ++NumVisibleDeclContextsRead;
6684 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006685 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006686}
6687
6688namespace {
6689 /// \brief ModuleFile visitor used to retrieve all visible names in a
6690 /// declaration context.
6691 class DeclContextAllNamesVisitor {
6692 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006693 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006694 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006695 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006696 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006697
6698 public:
6699 DeclContextAllNamesVisitor(ASTReader &Reader,
6700 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006701 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006702 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006703
6704 static bool visit(ModuleFile &M, void *UserData) {
6705 DeclContextAllNamesVisitor *This
6706 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6707
6708 // Check whether we have any visible declaration information for
6709 // this context in this module.
6710 ModuleFile::DeclContextInfosMap::iterator Info;
6711 bool FoundInfo = false;
6712 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6713 Info = M.DeclContextInfos.find(This->Contexts[I]);
6714 if (Info != M.DeclContextInfos.end() &&
6715 Info->second.NameLookupTableData) {
6716 FoundInfo = true;
6717 break;
6718 }
6719 }
6720
6721 if (!FoundInfo)
6722 return false;
6723
Richard Smith52e3fba2014-03-11 07:17:35 +00006724 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006725 Info->second.NameLookupTableData;
6726 bool FoundAnything = false;
6727 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006728 I = LookupTable->data_begin(), E = LookupTable->data_end();
6729 I != E;
6730 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006731 ASTDeclContextNameLookupTrait::data_type Data = *I;
6732 for (; Data.first != Data.second; ++Data.first) {
6733 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6734 *Data.first);
6735 if (!ND)
6736 continue;
6737
6738 // Record this declaration.
6739 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006740 if (This->DeclSet.insert(ND).second)
6741 This->Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006742 }
6743 }
6744
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006745 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006746 }
6747 };
6748}
6749
6750void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6751 if (!DC->hasExternalVisibleStorage())
6752 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006753 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006754
6755 // Compute the declaration contexts we need to look into. Multiple such
6756 // declaration contexts occur when two declaration contexts from disjoint
6757 // modules get merged, e.g., when two namespaces with the same name are
6758 // independently defined in separate modules.
6759 SmallVector<const DeclContext *, 2> Contexts;
6760 Contexts.push_back(DC);
6761
6762 if (DC->isNamespace()) {
6763 MergedDeclsMap::iterator Merged
6764 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6765 if (Merged != MergedDecls.end()) {
6766 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6767 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6768 }
6769 }
6770
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006771 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6772 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006773 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6774 ++NumVisibleDeclContextsRead;
6775
Craig Topper79be4cd2013-07-05 04:33:53 +00006776 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006777 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6778 }
6779 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6780}
6781
6782/// \brief Under non-PCH compilation the consumer receives the objc methods
6783/// before receiving the implementation, and codegen depends on this.
6784/// We simulate this by deserializing and passing to consumer the methods of the
6785/// implementation before passing the deserialized implementation decl.
6786static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6787 ASTConsumer *Consumer) {
6788 assert(ImplD && Consumer);
6789
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006790 for (auto *I : ImplD->methods())
6791 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006792
6793 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6794}
6795
6796void ASTReader::PassInterestingDeclsToConsumer() {
6797 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006798
6799 if (PassingDeclsToConsumer)
6800 return;
6801
6802 // Guard variable to avoid recursively redoing the process of passing
6803 // decls to consumer.
6804 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6805 true);
6806
Richard Smith9e2341d2015-03-23 03:25:59 +00006807 // Ensure that we've loaded all potentially-interesting declarations
6808 // that need to be eagerly loaded.
6809 for (auto ID : EagerlyDeserializedDecls)
6810 GetDecl(ID);
6811 EagerlyDeserializedDecls.clear();
6812
Guy Benyei11169dd2012-12-18 14:30:41 +00006813 while (!InterestingDecls.empty()) {
6814 Decl *D = InterestingDecls.front();
6815 InterestingDecls.pop_front();
6816
6817 PassInterestingDeclToConsumer(D);
6818 }
6819}
6820
6821void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6822 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6823 PassObjCImplDeclToConsumer(ImplD, Consumer);
6824 else
6825 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6826}
6827
6828void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6829 this->Consumer = Consumer;
6830
Richard Smith9e2341d2015-03-23 03:25:59 +00006831 if (Consumer)
6832 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006833
6834 if (DeserializationListener)
6835 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006836}
6837
6838void ASTReader::PrintStats() {
6839 std::fprintf(stderr, "*** AST File Statistics:\n");
6840
6841 unsigned NumTypesLoaded
6842 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6843 QualType());
6844 unsigned NumDeclsLoaded
6845 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006846 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006847 unsigned NumIdentifiersLoaded
6848 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6849 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006850 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006851 unsigned NumMacrosLoaded
6852 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6853 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006854 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006855 unsigned NumSelectorsLoaded
6856 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6857 SelectorsLoaded.end(),
6858 Selector());
6859
6860 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6861 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6862 NumSLocEntriesRead, TotalNumSLocEntries,
6863 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6864 if (!TypesLoaded.empty())
6865 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6866 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6867 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6868 if (!DeclsLoaded.empty())
6869 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6870 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6871 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6872 if (!IdentifiersLoaded.empty())
6873 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6874 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6875 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6876 if (!MacrosLoaded.empty())
6877 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6878 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6879 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6880 if (!SelectorsLoaded.empty())
6881 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6882 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6883 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6884 if (TotalNumStatements)
6885 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6886 NumStatementsRead, TotalNumStatements,
6887 ((float)NumStatementsRead/TotalNumStatements * 100));
6888 if (TotalNumMacros)
6889 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6890 NumMacrosRead, TotalNumMacros,
6891 ((float)NumMacrosRead/TotalNumMacros * 100));
6892 if (TotalLexicalDeclContexts)
6893 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6894 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6895 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6896 * 100));
6897 if (TotalVisibleDeclContexts)
6898 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6899 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6900 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6901 * 100));
6902 if (TotalNumMethodPoolEntries) {
6903 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6904 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6905 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6906 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006907 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006908 if (NumMethodPoolLookups) {
6909 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6910 NumMethodPoolHits, NumMethodPoolLookups,
6911 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6912 }
6913 if (NumMethodPoolTableLookups) {
6914 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6915 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6916 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6917 * 100.0));
6918 }
6919
Douglas Gregor00a50f72013-01-25 00:38:33 +00006920 if (NumIdentifierLookupHits) {
6921 std::fprintf(stderr,
6922 " %u / %u identifier table lookups succeeded (%f%%)\n",
6923 NumIdentifierLookupHits, NumIdentifierLookups,
6924 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6925 }
6926
Douglas Gregore060e572013-01-25 01:03:03 +00006927 if (GlobalIndex) {
6928 std::fprintf(stderr, "\n");
6929 GlobalIndex->printStats();
6930 }
6931
Guy Benyei11169dd2012-12-18 14:30:41 +00006932 std::fprintf(stderr, "\n");
6933 dump();
6934 std::fprintf(stderr, "\n");
6935}
6936
6937template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6938static void
6939dumpModuleIDMap(StringRef Name,
6940 const ContinuousRangeMap<Key, ModuleFile *,
6941 InitialCapacity> &Map) {
6942 if (Map.begin() == Map.end())
6943 return;
6944
6945 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6946 llvm::errs() << Name << ":\n";
6947 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6948 I != IEnd; ++I) {
6949 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6950 << "\n";
6951 }
6952}
6953
6954void ASTReader::dump() {
6955 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6956 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6957 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6958 dumpModuleIDMap("Global type map", GlobalTypeMap);
6959 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6960 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6961 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6962 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6963 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6964 dumpModuleIDMap("Global preprocessed entity map",
6965 GlobalPreprocessedEntityMap);
6966
6967 llvm::errs() << "\n*** PCH/Modules Loaded:";
6968 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6969 MEnd = ModuleMgr.end();
6970 M != MEnd; ++M)
6971 (*M)->dump();
6972}
6973
6974/// Return the amount of memory used by memory buffers, breaking down
6975/// by heap-backed versus mmap'ed memory.
6976void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6977 for (ModuleConstIterator I = ModuleMgr.begin(),
6978 E = ModuleMgr.end(); I != E; ++I) {
6979 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6980 size_t bytes = buf->getBufferSize();
6981 switch (buf->getBufferKind()) {
6982 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6983 sizes.malloc_bytes += bytes;
6984 break;
6985 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6986 sizes.mmap_bytes += bytes;
6987 break;
6988 }
6989 }
6990 }
6991}
6992
6993void ASTReader::InitializeSema(Sema &S) {
6994 SemaObj = &S;
6995 S.addExternalSource(this);
6996
6997 // Makes sure any declarations that were deserialized "too early"
6998 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006999 for (uint64_t ID : PreloadedDeclIDs) {
7000 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7001 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007002 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007003 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007004
Richard Smith3d8e97e2013-10-18 06:54:39 +00007005 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007006 if (!FPPragmaOptions.empty()) {
7007 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7008 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
7009 }
7010
Richard Smith3d8e97e2013-10-18 06:54:39 +00007011 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007012 if (!OpenCLExtensions.empty()) {
7013 unsigned I = 0;
7014#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
7015#include "clang/Basic/OpenCLExtensions.def"
7016
7017 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
7018 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00007019
7020 UpdateSema();
7021}
7022
7023void ASTReader::UpdateSema() {
7024 assert(SemaObj && "no Sema to update");
7025
7026 // Load the offsets of the declarations that Sema references.
7027 // They will be lazily deserialized when needed.
7028 if (!SemaDeclRefs.empty()) {
7029 assert(SemaDeclRefs.size() % 2 == 0);
7030 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
7031 if (!SemaObj->StdNamespace)
7032 SemaObj->StdNamespace = SemaDeclRefs[I];
7033 if (!SemaObj->StdBadAlloc)
7034 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
7035 }
7036 SemaDeclRefs.clear();
7037 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007038
7039 // Update the state of 'pragma clang optimize'. Use the same API as if we had
7040 // encountered the pragma in the source.
7041 if(OptimizeOffPragmaLocation.isValid())
7042 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00007043}
7044
7045IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
7046 // Note that we are loading an identifier.
7047 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007048 StringRef Name(NameStart, NameEnd - NameStart);
7049
7050 // If there is a global index, look there first to determine which modules
7051 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00007052 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00007053 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00007054 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00007055 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7056 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00007057 }
7058 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00007059 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007060 NumIdentifierLookups,
7061 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00007062 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007063 IdentifierInfo *II = Visitor.getIdentifierInfo();
7064 markIdentifierUpToDate(II);
7065 return II;
7066}
7067
7068namespace clang {
7069 /// \brief An identifier-lookup iterator that enumerates all of the
7070 /// identifiers stored within a set of AST files.
7071 class ASTIdentifierIterator : public IdentifierIterator {
7072 /// \brief The AST reader whose identifiers are being enumerated.
7073 const ASTReader &Reader;
7074
7075 /// \brief The current index into the chain of AST files stored in
7076 /// the AST reader.
7077 unsigned Index;
7078
7079 /// \brief The current position within the identifier lookup table
7080 /// of the current AST file.
7081 ASTIdentifierLookupTable::key_iterator Current;
7082
7083 /// \brief The end position within the identifier lookup table of
7084 /// the current AST file.
7085 ASTIdentifierLookupTable::key_iterator End;
7086
7087 public:
7088 explicit ASTIdentifierIterator(const ASTReader &Reader);
7089
Craig Topper3e89dfe2014-03-13 02:13:41 +00007090 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007091 };
7092}
7093
7094ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
7095 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
7096 ASTIdentifierLookupTable *IdTable
7097 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
7098 Current = IdTable->key_begin();
7099 End = IdTable->key_end();
7100}
7101
7102StringRef ASTIdentifierIterator::Next() {
7103 while (Current == End) {
7104 // If we have exhausted all of our AST files, we're done.
7105 if (Index == 0)
7106 return StringRef();
7107
7108 --Index;
7109 ASTIdentifierLookupTable *IdTable
7110 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
7111 IdentifierLookupTable;
7112 Current = IdTable->key_begin();
7113 End = IdTable->key_end();
7114 }
7115
7116 // We have any identifiers remaining in the current AST file; return
7117 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007118 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007119 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007120 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007121}
7122
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007123IdentifierIterator *ASTReader::getIdentifiers() {
7124 if (!loadGlobalIndex())
7125 return GlobalIndex->createIdentifierIterator();
7126
Guy Benyei11169dd2012-12-18 14:30:41 +00007127 return new ASTIdentifierIterator(*this);
7128}
7129
7130namespace clang { namespace serialization {
7131 class ReadMethodPoolVisitor {
7132 ASTReader &Reader;
7133 Selector Sel;
7134 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007135 unsigned InstanceBits;
7136 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007137 bool InstanceHasMoreThanOneDecl;
7138 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007139 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7140 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007141
7142 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007143 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007144 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007145 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007146 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7147 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007148
Guy Benyei11169dd2012-12-18 14:30:41 +00007149 static bool visit(ModuleFile &M, void *UserData) {
7150 ReadMethodPoolVisitor *This
7151 = static_cast<ReadMethodPoolVisitor *>(UserData);
7152
7153 if (!M.SelectorLookupTable)
7154 return false;
7155
7156 // If we've already searched this module file, skip it now.
7157 if (M.Generation <= This->PriorGeneration)
7158 return true;
7159
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007160 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007161 ASTSelectorLookupTable *PoolTable
7162 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
7163 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
7164 if (Pos == PoolTable->end())
7165 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007166
7167 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00007168 ++This->Reader.NumSelectorsRead;
7169 // FIXME: Not quite happy with the statistics here. We probably should
7170 // disable this tracking when called via LoadSelector.
7171 // Also, should entries without methods count as misses?
7172 ++This->Reader.NumMethodPoolEntriesRead;
7173 ASTSelectorLookupTrait::data_type Data = *Pos;
7174 if (This->Reader.DeserializationListener)
7175 This->Reader.DeserializationListener->SelectorRead(Data.ID,
7176 This->Sel);
7177
7178 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7179 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007180 This->InstanceBits = Data.InstanceBits;
7181 This->FactoryBits = Data.FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007182 This->InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7183 This->FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007184 return true;
7185 }
7186
7187 /// \brief Retrieve the instance methods found by this visitor.
7188 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7189 return InstanceMethods;
7190 }
7191
7192 /// \brief Retrieve the instance methods found by this visitor.
7193 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7194 return FactoryMethods;
7195 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007196
7197 unsigned getInstanceBits() const { return InstanceBits; }
7198 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007199 bool instanceHasMoreThanOneDecl() const {
7200 return InstanceHasMoreThanOneDecl;
7201 }
7202 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007203 };
7204} } // end namespace clang::serialization
7205
7206/// \brief Add the given set of methods to the method list.
7207static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7208 ObjCMethodList &List) {
7209 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7210 S.addMethodToGlobalList(&List, Methods[I]);
7211 }
7212}
7213
7214void ASTReader::ReadMethodPool(Selector Sel) {
7215 // Get the selector generation and update it to the current generation.
7216 unsigned &Generation = SelectorGeneration[Sel];
7217 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007218 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007219
7220 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007221 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007222 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7223 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
7224
7225 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007226 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007227 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007228
7229 ++NumMethodPoolHits;
7230
Guy Benyei11169dd2012-12-18 14:30:41 +00007231 if (!getSema())
7232 return;
7233
7234 Sema &S = *getSema();
7235 Sema::GlobalMethodPool::iterator Pos
7236 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007237
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007238 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007239 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007240 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007241 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007242
7243 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7244 // when building a module we keep every method individually and may need to
7245 // update hasMoreThanOneDecl as we add the methods.
7246 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7247 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007248}
7249
7250void ASTReader::ReadKnownNamespaces(
7251 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7252 Namespaces.clear();
7253
7254 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7255 if (NamespaceDecl *Namespace
7256 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7257 Namespaces.push_back(Namespace);
7258 }
7259}
7260
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007261void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007262 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007263 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7264 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007265 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007266 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007267 Undefined.insert(std::make_pair(D, Loc));
7268 }
7269}
Nick Lewycky8334af82013-01-26 00:35:08 +00007270
Guy Benyei11169dd2012-12-18 14:30:41 +00007271void ASTReader::ReadTentativeDefinitions(
7272 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7273 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7274 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7275 if (Var)
7276 TentativeDefs.push_back(Var);
7277 }
7278 TentativeDefinitions.clear();
7279}
7280
7281void ASTReader::ReadUnusedFileScopedDecls(
7282 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7283 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7284 DeclaratorDecl *D
7285 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7286 if (D)
7287 Decls.push_back(D);
7288 }
7289 UnusedFileScopedDecls.clear();
7290}
7291
7292void ASTReader::ReadDelegatingConstructors(
7293 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7294 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7295 CXXConstructorDecl *D
7296 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7297 if (D)
7298 Decls.push_back(D);
7299 }
7300 DelegatingCtorDecls.clear();
7301}
7302
7303void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7304 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7305 TypedefNameDecl *D
7306 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7307 if (D)
7308 Decls.push_back(D);
7309 }
7310 ExtVectorDecls.clear();
7311}
7312
Nico Weber72889432014-09-06 01:25:55 +00007313void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7314 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7315 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7316 ++I) {
7317 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7318 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7319 if (D)
7320 Decls.insert(D);
7321 }
7322 UnusedLocalTypedefNameCandidates.clear();
7323}
7324
Guy Benyei11169dd2012-12-18 14:30:41 +00007325void ASTReader::ReadReferencedSelectors(
7326 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7327 if (ReferencedSelectorsData.empty())
7328 return;
7329
7330 // If there are @selector references added them to its pool. This is for
7331 // implementation of -Wselector.
7332 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7333 unsigned I = 0;
7334 while (I < DataSize) {
7335 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7336 SourceLocation SelLoc
7337 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7338 Sels.push_back(std::make_pair(Sel, SelLoc));
7339 }
7340 ReferencedSelectorsData.clear();
7341}
7342
7343void ASTReader::ReadWeakUndeclaredIdentifiers(
7344 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7345 if (WeakUndeclaredIdentifiers.empty())
7346 return;
7347
7348 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7349 IdentifierInfo *WeakId
7350 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7351 IdentifierInfo *AliasId
7352 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7353 SourceLocation Loc
7354 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7355 bool Used = WeakUndeclaredIdentifiers[I++];
7356 WeakInfo WI(AliasId, Loc);
7357 WI.setUsed(Used);
7358 WeakIDs.push_back(std::make_pair(WeakId, WI));
7359 }
7360 WeakUndeclaredIdentifiers.clear();
7361}
7362
7363void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7364 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7365 ExternalVTableUse VT;
7366 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7367 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7368 VT.DefinitionRequired = VTableUses[Idx++];
7369 VTables.push_back(VT);
7370 }
7371
7372 VTableUses.clear();
7373}
7374
7375void ASTReader::ReadPendingInstantiations(
7376 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7377 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7378 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7379 SourceLocation Loc
7380 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7381
7382 Pending.push_back(std::make_pair(D, Loc));
7383 }
7384 PendingInstantiations.clear();
7385}
7386
Richard Smithe40f2ba2013-08-07 21:41:30 +00007387void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007388 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007389 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7390 /* In loop */) {
7391 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7392
7393 LateParsedTemplate *LT = new LateParsedTemplate;
7394 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7395
7396 ModuleFile *F = getOwningModuleFile(LT->D);
7397 assert(F && "No module");
7398
7399 unsigned TokN = LateParsedTemplates[Idx++];
7400 LT->Toks.reserve(TokN);
7401 for (unsigned T = 0; T < TokN; ++T)
7402 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7403
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007404 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007405 }
7406
7407 LateParsedTemplates.clear();
7408}
7409
Guy Benyei11169dd2012-12-18 14:30:41 +00007410void ASTReader::LoadSelector(Selector Sel) {
7411 // It would be complicated to avoid reading the methods anyway. So don't.
7412 ReadMethodPool(Sel);
7413}
7414
7415void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7416 assert(ID && "Non-zero identifier ID required");
7417 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7418 IdentifiersLoaded[ID - 1] = II;
7419 if (DeserializationListener)
7420 DeserializationListener->IdentifierRead(ID, II);
7421}
7422
7423/// \brief Set the globally-visible declarations associated with the given
7424/// identifier.
7425///
7426/// If the AST reader is currently in a state where the given declaration IDs
7427/// cannot safely be resolved, they are queued until it is safe to resolve
7428/// them.
7429///
7430/// \param II an IdentifierInfo that refers to one or more globally-visible
7431/// declarations.
7432///
7433/// \param DeclIDs the set of declaration IDs with the name @p II that are
7434/// visible at global scope.
7435///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007436/// \param Decls if non-null, this vector will be populated with the set of
7437/// deserialized declarations. These declarations will not be pushed into
7438/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007439void
7440ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7441 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007442 SmallVectorImpl<Decl *> *Decls) {
7443 if (NumCurrentElementsDeserializing && !Decls) {
7444 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007445 return;
7446 }
7447
7448 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007449 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007450 // Queue this declaration so that it will be added to the
7451 // translation unit scope and identifier's declaration chain
7452 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007453 PreloadedDeclIDs.push_back(DeclIDs[I]);
7454 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007455 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007456
7457 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7458
7459 // If we're simply supposed to record the declarations, do so now.
7460 if (Decls) {
7461 Decls->push_back(D);
7462 continue;
7463 }
7464
7465 // Introduce this declaration into the translation-unit scope
7466 // and add it to the declaration chain for this identifier, so
7467 // that (unqualified) name lookup will find it.
7468 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007469 }
7470}
7471
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007472IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007473 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007474 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007475
7476 if (IdentifiersLoaded.empty()) {
7477 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007478 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007479 }
7480
7481 ID -= 1;
7482 if (!IdentifiersLoaded[ID]) {
7483 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7484 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7485 ModuleFile *M = I->second;
7486 unsigned Index = ID - M->BaseIdentifierID;
7487 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7488
7489 // All of the strings in the AST file are preceded by a 16-bit length.
7490 // Extract that 16-bit length to avoid having to execute strlen().
7491 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7492 // unsigned integers. This is important to avoid integer overflow when
7493 // we cast them to 'unsigned'.
7494 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7495 unsigned StrLen = (((unsigned) StrLenPtr[0])
7496 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007497 IdentifiersLoaded[ID]
7498 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007499 if (DeserializationListener)
7500 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7501 }
7502
7503 return IdentifiersLoaded[ID];
7504}
7505
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007506IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7507 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007508}
7509
7510IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7511 if (LocalID < NUM_PREDEF_IDENT_IDS)
7512 return LocalID;
7513
7514 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7515 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7516 assert(I != M.IdentifierRemap.end()
7517 && "Invalid index into identifier index remap");
7518
7519 return LocalID + I->second;
7520}
7521
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007522MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007523 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007524 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007525
7526 if (MacrosLoaded.empty()) {
7527 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007528 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007529 }
7530
7531 ID -= NUM_PREDEF_MACRO_IDS;
7532 if (!MacrosLoaded[ID]) {
7533 GlobalMacroMapType::iterator I
7534 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7535 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7536 ModuleFile *M = I->second;
7537 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007538 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7539
7540 if (DeserializationListener)
7541 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7542 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007543 }
7544
7545 return MacrosLoaded[ID];
7546}
7547
7548MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7549 if (LocalID < NUM_PREDEF_MACRO_IDS)
7550 return LocalID;
7551
7552 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7553 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7554 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7555
7556 return LocalID + I->second;
7557}
7558
7559serialization::SubmoduleID
7560ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7561 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7562 return LocalID;
7563
7564 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7565 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7566 assert(I != M.SubmoduleRemap.end()
7567 && "Invalid index into submodule index remap");
7568
7569 return LocalID + I->second;
7570}
7571
7572Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7573 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7574 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007575 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007576 }
7577
7578 if (GlobalID > SubmodulesLoaded.size()) {
7579 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007580 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007581 }
7582
7583 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7584}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007585
7586Module *ASTReader::getModule(unsigned ID) {
7587 return getSubmodule(ID);
7588}
7589
Guy Benyei11169dd2012-12-18 14:30:41 +00007590Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7591 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7592}
7593
7594Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7595 if (ID == 0)
7596 return Selector();
7597
7598 if (ID > SelectorsLoaded.size()) {
7599 Error("selector ID out of range in AST file");
7600 return Selector();
7601 }
7602
Craig Toppera13603a2014-05-22 05:54:18 +00007603 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007604 // Load this selector from the selector table.
7605 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7606 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7607 ModuleFile &M = *I->second;
7608 ASTSelectorLookupTrait Trait(*this, M);
7609 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7610 SelectorsLoaded[ID - 1] =
7611 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7612 if (DeserializationListener)
7613 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7614 }
7615
7616 return SelectorsLoaded[ID - 1];
7617}
7618
7619Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7620 return DecodeSelector(ID);
7621}
7622
7623uint32_t ASTReader::GetNumExternalSelectors() {
7624 // ID 0 (the null selector) is considered an external selector.
7625 return getTotalNumSelectors() + 1;
7626}
7627
7628serialization::SelectorID
7629ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7630 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7631 return LocalID;
7632
7633 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7634 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7635 assert(I != M.SelectorRemap.end()
7636 && "Invalid index into selector index remap");
7637
7638 return LocalID + I->second;
7639}
7640
7641DeclarationName
7642ASTReader::ReadDeclarationName(ModuleFile &F,
7643 const RecordData &Record, unsigned &Idx) {
7644 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7645 switch (Kind) {
7646 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007647 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007648
7649 case DeclarationName::ObjCZeroArgSelector:
7650 case DeclarationName::ObjCOneArgSelector:
7651 case DeclarationName::ObjCMultiArgSelector:
7652 return DeclarationName(ReadSelector(F, Record, Idx));
7653
7654 case DeclarationName::CXXConstructorName:
7655 return Context.DeclarationNames.getCXXConstructorName(
7656 Context.getCanonicalType(readType(F, Record, Idx)));
7657
7658 case DeclarationName::CXXDestructorName:
7659 return Context.DeclarationNames.getCXXDestructorName(
7660 Context.getCanonicalType(readType(F, Record, Idx)));
7661
7662 case DeclarationName::CXXConversionFunctionName:
7663 return Context.DeclarationNames.getCXXConversionFunctionName(
7664 Context.getCanonicalType(readType(F, Record, Idx)));
7665
7666 case DeclarationName::CXXOperatorName:
7667 return Context.DeclarationNames.getCXXOperatorName(
7668 (OverloadedOperatorKind)Record[Idx++]);
7669
7670 case DeclarationName::CXXLiteralOperatorName:
7671 return Context.DeclarationNames.getCXXLiteralOperatorName(
7672 GetIdentifierInfo(F, Record, Idx));
7673
7674 case DeclarationName::CXXUsingDirective:
7675 return DeclarationName::getUsingDirectiveName();
7676 }
7677
7678 llvm_unreachable("Invalid NameKind!");
7679}
7680
7681void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7682 DeclarationNameLoc &DNLoc,
7683 DeclarationName Name,
7684 const RecordData &Record, unsigned &Idx) {
7685 switch (Name.getNameKind()) {
7686 case DeclarationName::CXXConstructorName:
7687 case DeclarationName::CXXDestructorName:
7688 case DeclarationName::CXXConversionFunctionName:
7689 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7690 break;
7691
7692 case DeclarationName::CXXOperatorName:
7693 DNLoc.CXXOperatorName.BeginOpNameLoc
7694 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7695 DNLoc.CXXOperatorName.EndOpNameLoc
7696 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7697 break;
7698
7699 case DeclarationName::CXXLiteralOperatorName:
7700 DNLoc.CXXLiteralOperatorName.OpNameLoc
7701 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7702 break;
7703
7704 case DeclarationName::Identifier:
7705 case DeclarationName::ObjCZeroArgSelector:
7706 case DeclarationName::ObjCOneArgSelector:
7707 case DeclarationName::ObjCMultiArgSelector:
7708 case DeclarationName::CXXUsingDirective:
7709 break;
7710 }
7711}
7712
7713void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7714 DeclarationNameInfo &NameInfo,
7715 const RecordData &Record, unsigned &Idx) {
7716 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7717 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7718 DeclarationNameLoc DNLoc;
7719 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7720 NameInfo.setInfo(DNLoc);
7721}
7722
7723void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7724 const RecordData &Record, unsigned &Idx) {
7725 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7726 unsigned NumTPLists = Record[Idx++];
7727 Info.NumTemplParamLists = NumTPLists;
7728 if (NumTPLists) {
7729 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7730 for (unsigned i=0; i != NumTPLists; ++i)
7731 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7732 }
7733}
7734
7735TemplateName
7736ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7737 unsigned &Idx) {
7738 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7739 switch (Kind) {
7740 case TemplateName::Template:
7741 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7742
7743 case TemplateName::OverloadedTemplate: {
7744 unsigned size = Record[Idx++];
7745 UnresolvedSet<8> Decls;
7746 while (size--)
7747 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7748
7749 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7750 }
7751
7752 case TemplateName::QualifiedTemplate: {
7753 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7754 bool hasTemplKeyword = Record[Idx++];
7755 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7756 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7757 }
7758
7759 case TemplateName::DependentTemplate: {
7760 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7761 if (Record[Idx++]) // isIdentifier
7762 return Context.getDependentTemplateName(NNS,
7763 GetIdentifierInfo(F, Record,
7764 Idx));
7765 return Context.getDependentTemplateName(NNS,
7766 (OverloadedOperatorKind)Record[Idx++]);
7767 }
7768
7769 case TemplateName::SubstTemplateTemplateParm: {
7770 TemplateTemplateParmDecl *param
7771 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7772 if (!param) return TemplateName();
7773 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7774 return Context.getSubstTemplateTemplateParm(param, replacement);
7775 }
7776
7777 case TemplateName::SubstTemplateTemplateParmPack: {
7778 TemplateTemplateParmDecl *Param
7779 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7780 if (!Param)
7781 return TemplateName();
7782
7783 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7784 if (ArgPack.getKind() != TemplateArgument::Pack)
7785 return TemplateName();
7786
7787 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7788 }
7789 }
7790
7791 llvm_unreachable("Unhandled template name kind!");
7792}
7793
7794TemplateArgument
7795ASTReader::ReadTemplateArgument(ModuleFile &F,
7796 const RecordData &Record, unsigned &Idx) {
7797 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7798 switch (Kind) {
7799 case TemplateArgument::Null:
7800 return TemplateArgument();
7801 case TemplateArgument::Type:
7802 return TemplateArgument(readType(F, Record, Idx));
7803 case TemplateArgument::Declaration: {
7804 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007805 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007806 }
7807 case TemplateArgument::NullPtr:
7808 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7809 case TemplateArgument::Integral: {
7810 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7811 QualType T = readType(F, Record, Idx);
7812 return TemplateArgument(Context, Value, T);
7813 }
7814 case TemplateArgument::Template:
7815 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7816 case TemplateArgument::TemplateExpansion: {
7817 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007818 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007819 if (unsigned NumExpansions = Record[Idx++])
7820 NumTemplateExpansions = NumExpansions - 1;
7821 return TemplateArgument(Name, NumTemplateExpansions);
7822 }
7823 case TemplateArgument::Expression:
7824 return TemplateArgument(ReadExpr(F));
7825 case TemplateArgument::Pack: {
7826 unsigned NumArgs = Record[Idx++];
7827 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7828 for (unsigned I = 0; I != NumArgs; ++I)
7829 Args[I] = ReadTemplateArgument(F, Record, Idx);
7830 return TemplateArgument(Args, NumArgs);
7831 }
7832 }
7833
7834 llvm_unreachable("Unhandled template argument kind!");
7835}
7836
7837TemplateParameterList *
7838ASTReader::ReadTemplateParameterList(ModuleFile &F,
7839 const RecordData &Record, unsigned &Idx) {
7840 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7841 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7842 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7843
7844 unsigned NumParams = Record[Idx++];
7845 SmallVector<NamedDecl *, 16> Params;
7846 Params.reserve(NumParams);
7847 while (NumParams--)
7848 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7849
7850 TemplateParameterList* TemplateParams =
7851 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7852 Params.data(), Params.size(), RAngleLoc);
7853 return TemplateParams;
7854}
7855
7856void
7857ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007858ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007859 ModuleFile &F, const RecordData &Record,
7860 unsigned &Idx) {
7861 unsigned NumTemplateArgs = Record[Idx++];
7862 TemplArgs.reserve(NumTemplateArgs);
7863 while (NumTemplateArgs--)
7864 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7865}
7866
7867/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007868void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007869 const RecordData &Record, unsigned &Idx) {
7870 unsigned NumDecls = Record[Idx++];
7871 Set.reserve(Context, NumDecls);
7872 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007873 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007874 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007875 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007876 }
7877}
7878
7879CXXBaseSpecifier
7880ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7881 const RecordData &Record, unsigned &Idx) {
7882 bool isVirtual = static_cast<bool>(Record[Idx++]);
7883 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7884 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7885 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7886 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7887 SourceRange Range = ReadSourceRange(F, Record, Idx);
7888 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7889 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7890 EllipsisLoc);
7891 Result.setInheritConstructors(inheritConstructors);
7892 return Result;
7893}
7894
Richard Smithc2bb8182015-03-24 06:36:48 +00007895CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007896ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7897 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007898 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007899 assert(NumInitializers && "wrote ctor initializers but have no inits");
7900 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7901 for (unsigned i = 0; i != NumInitializers; ++i) {
7902 TypeSourceInfo *TInfo = nullptr;
7903 bool IsBaseVirtual = false;
7904 FieldDecl *Member = nullptr;
7905 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007906
Richard Smithc2bb8182015-03-24 06:36:48 +00007907 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7908 switch (Type) {
7909 case CTOR_INITIALIZER_BASE:
7910 TInfo = GetTypeSourceInfo(F, Record, Idx);
7911 IsBaseVirtual = Record[Idx++];
7912 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007913
Richard Smithc2bb8182015-03-24 06:36:48 +00007914 case CTOR_INITIALIZER_DELEGATING:
7915 TInfo = GetTypeSourceInfo(F, Record, Idx);
7916 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007917
Richard Smithc2bb8182015-03-24 06:36:48 +00007918 case CTOR_INITIALIZER_MEMBER:
7919 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7920 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007921
Richard Smithc2bb8182015-03-24 06:36:48 +00007922 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7923 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7924 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007925 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007926
7927 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7928 Expr *Init = ReadExpr(F);
7929 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7930 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7931 bool IsWritten = Record[Idx++];
7932 unsigned SourceOrderOrNumArrayIndices;
7933 SmallVector<VarDecl *, 8> Indices;
7934 if (IsWritten) {
7935 SourceOrderOrNumArrayIndices = Record[Idx++];
7936 } else {
7937 SourceOrderOrNumArrayIndices = Record[Idx++];
7938 Indices.reserve(SourceOrderOrNumArrayIndices);
7939 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7940 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7941 }
7942
7943 CXXCtorInitializer *BOMInit;
7944 if (Type == CTOR_INITIALIZER_BASE) {
7945 BOMInit = new (Context)
7946 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7947 RParenLoc, MemberOrEllipsisLoc);
7948 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7949 BOMInit = new (Context)
7950 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7951 } else if (IsWritten) {
7952 if (Member)
7953 BOMInit = new (Context) CXXCtorInitializer(
7954 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7955 else
7956 BOMInit = new (Context)
7957 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7958 LParenLoc, Init, RParenLoc);
7959 } else {
7960 if (IndirectMember) {
7961 assert(Indices.empty() && "Indirect field improperly initialized");
7962 BOMInit = new (Context)
7963 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7964 LParenLoc, Init, RParenLoc);
7965 } else {
7966 BOMInit = CXXCtorInitializer::Create(
7967 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7968 Indices.data(), Indices.size());
7969 }
7970 }
7971
7972 if (IsWritten)
7973 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7974 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007975 }
7976
Richard Smithc2bb8182015-03-24 06:36:48 +00007977 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007978}
7979
7980NestedNameSpecifier *
7981ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7982 const RecordData &Record, unsigned &Idx) {
7983 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007984 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007985 for (unsigned I = 0; I != N; ++I) {
7986 NestedNameSpecifier::SpecifierKind Kind
7987 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7988 switch (Kind) {
7989 case NestedNameSpecifier::Identifier: {
7990 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7991 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7992 break;
7993 }
7994
7995 case NestedNameSpecifier::Namespace: {
7996 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7997 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7998 break;
7999 }
8000
8001 case NestedNameSpecifier::NamespaceAlias: {
8002 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8003 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8004 break;
8005 }
8006
8007 case NestedNameSpecifier::TypeSpec:
8008 case NestedNameSpecifier::TypeSpecWithTemplate: {
8009 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8010 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008011 return nullptr;
8012
Guy Benyei11169dd2012-12-18 14:30:41 +00008013 bool Template = Record[Idx++];
8014 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8015 break;
8016 }
8017
8018 case NestedNameSpecifier::Global: {
8019 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8020 // No associated value, and there can't be a prefix.
8021 break;
8022 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008023
8024 case NestedNameSpecifier::Super: {
8025 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8026 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8027 break;
8028 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008029 }
8030 Prev = NNS;
8031 }
8032 return NNS;
8033}
8034
8035NestedNameSpecifierLoc
8036ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8037 unsigned &Idx) {
8038 unsigned N = Record[Idx++];
8039 NestedNameSpecifierLocBuilder Builder;
8040 for (unsigned I = 0; I != N; ++I) {
8041 NestedNameSpecifier::SpecifierKind Kind
8042 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8043 switch (Kind) {
8044 case NestedNameSpecifier::Identifier: {
8045 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8046 SourceRange Range = ReadSourceRange(F, Record, Idx);
8047 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8048 break;
8049 }
8050
8051 case NestedNameSpecifier::Namespace: {
8052 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8053 SourceRange Range = ReadSourceRange(F, Record, Idx);
8054 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8055 break;
8056 }
8057
8058 case NestedNameSpecifier::NamespaceAlias: {
8059 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8060 SourceRange Range = ReadSourceRange(F, Record, Idx);
8061 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8062 break;
8063 }
8064
8065 case NestedNameSpecifier::TypeSpec:
8066 case NestedNameSpecifier::TypeSpecWithTemplate: {
8067 bool Template = Record[Idx++];
8068 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8069 if (!T)
8070 return NestedNameSpecifierLoc();
8071 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8072
8073 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8074 Builder.Extend(Context,
8075 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8076 T->getTypeLoc(), ColonColonLoc);
8077 break;
8078 }
8079
8080 case NestedNameSpecifier::Global: {
8081 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8082 Builder.MakeGlobal(Context, ColonColonLoc);
8083 break;
8084 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008085
8086 case NestedNameSpecifier::Super: {
8087 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8088 SourceRange Range = ReadSourceRange(F, Record, Idx);
8089 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8090 break;
8091 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008092 }
8093 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008094
Guy Benyei11169dd2012-12-18 14:30:41 +00008095 return Builder.getWithLocInContext(Context);
8096}
8097
8098SourceRange
8099ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8100 unsigned &Idx) {
8101 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8102 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8103 return SourceRange(beg, end);
8104}
8105
8106/// \brief Read an integral value
8107llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8108 unsigned BitWidth = Record[Idx++];
8109 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8110 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8111 Idx += NumWords;
8112 return Result;
8113}
8114
8115/// \brief Read a signed integral value
8116llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8117 bool isUnsigned = Record[Idx++];
8118 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8119}
8120
8121/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008122llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8123 const llvm::fltSemantics &Sem,
8124 unsigned &Idx) {
8125 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008126}
8127
8128// \brief Read a string
8129std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8130 unsigned Len = Record[Idx++];
8131 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8132 Idx += Len;
8133 return Result;
8134}
8135
Richard Smith7ed1bc92014-12-05 22:42:13 +00008136std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8137 unsigned &Idx) {
8138 std::string Filename = ReadString(Record, Idx);
8139 ResolveImportedPath(F, Filename);
8140 return Filename;
8141}
8142
Guy Benyei11169dd2012-12-18 14:30:41 +00008143VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8144 unsigned &Idx) {
8145 unsigned Major = Record[Idx++];
8146 unsigned Minor = Record[Idx++];
8147 unsigned Subminor = Record[Idx++];
8148 if (Minor == 0)
8149 return VersionTuple(Major);
8150 if (Subminor == 0)
8151 return VersionTuple(Major, Minor - 1);
8152 return VersionTuple(Major, Minor - 1, Subminor - 1);
8153}
8154
8155CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8156 const RecordData &Record,
8157 unsigned &Idx) {
8158 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8159 return CXXTemporary::Create(Context, Decl);
8160}
8161
8162DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008163 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008164}
8165
8166DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8167 return Diags.Report(Loc, DiagID);
8168}
8169
8170/// \brief Retrieve the identifier table associated with the
8171/// preprocessor.
8172IdentifierTable &ASTReader::getIdentifierTable() {
8173 return PP.getIdentifierTable();
8174}
8175
8176/// \brief Record that the given ID maps to the given switch-case
8177/// statement.
8178void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008179 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008180 "Already have a SwitchCase with this ID");
8181 (*CurrSwitchCaseStmts)[ID] = SC;
8182}
8183
8184/// \brief Retrieve the switch-case statement with the given ID.
8185SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008186 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008187 return (*CurrSwitchCaseStmts)[ID];
8188}
8189
8190void ASTReader::ClearSwitchCaseIDs() {
8191 CurrSwitchCaseStmts->clear();
8192}
8193
8194void ASTReader::ReadComments() {
8195 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008196 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008197 serialization::ModuleFile *> >::iterator
8198 I = CommentsCursors.begin(),
8199 E = CommentsCursors.end();
8200 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008201 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008202 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008203 serialization::ModuleFile &F = *I->second;
8204 SavedStreamPosition SavedPosition(Cursor);
8205
8206 RecordData Record;
8207 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008208 llvm::BitstreamEntry Entry =
8209 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008210
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008211 switch (Entry.Kind) {
8212 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8213 case llvm::BitstreamEntry::Error:
8214 Error("malformed block record in AST file");
8215 return;
8216 case llvm::BitstreamEntry::EndBlock:
8217 goto NextCursor;
8218 case llvm::BitstreamEntry::Record:
8219 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008220 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008221 }
8222
8223 // Read a record.
8224 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008225 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008226 case COMMENTS_RAW_COMMENT: {
8227 unsigned Idx = 0;
8228 SourceRange SR = ReadSourceRange(F, Record, Idx);
8229 RawComment::CommentKind Kind =
8230 (RawComment::CommentKind) Record[Idx++];
8231 bool IsTrailingComment = Record[Idx++];
8232 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008233 Comments.push_back(new (Context) RawComment(
8234 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8235 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008236 break;
8237 }
8238 }
8239 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008240 NextCursor:
8241 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008242 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008243}
8244
Argyrios Kyrtzidis1bde1172014-11-18 05:24:18 +00008245void ASTReader::getInputFiles(ModuleFile &F,
8246 SmallVectorImpl<serialization::InputFile> &Files) {
8247 for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
8248 unsigned ID = I+1;
8249 Files.push_back(getInputFile(F, ID));
8250 }
8251}
8252
Richard Smithcd45dbc2014-04-19 03:48:30 +00008253std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8254 // If we know the owning module, use it.
8255 if (Module *M = D->getOwningModule())
8256 return M->getFullModuleName();
8257
8258 // Otherwise, use the name of the top-level module the decl is within.
8259 if (ModuleFile *M = getOwningModuleFile(D))
8260 return M->ModuleName;
8261
8262 // Not from a module.
8263 return "";
8264}
8265
Guy Benyei11169dd2012-12-18 14:30:41 +00008266void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008267 while (!PendingIdentifierInfos.empty() ||
8268 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008269 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008270 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008271 // If any identifiers with corresponding top-level declarations have
8272 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008273 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8274 TopLevelDeclsMap;
8275 TopLevelDeclsMap TopLevelDecls;
8276
Guy Benyei11169dd2012-12-18 14:30:41 +00008277 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008278 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008279 SmallVector<uint32_t, 4> DeclIDs =
8280 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008281 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008282
8283 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008284 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008285
Richard Smith851072e2014-05-19 20:59:20 +00008286 // For each decl chain that we wanted to complete while deserializing, mark
8287 // it as "still needs to be completed".
8288 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8289 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8290 }
8291 PendingIncompleteDeclChains.clear();
8292
Guy Benyei11169dd2012-12-18 14:30:41 +00008293 // Load pending declaration chains.
Richard Smithfe620d22015-03-05 23:24:12 +00008294 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
Richard Smithfe620d22015-03-05 23:24:12 +00008295 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
Richard Smithe687bf82015-03-16 20:54:07 +00008296 loadPendingDeclChain(PendingDeclChains[I]);
Richard Smithfe620d22015-03-05 23:24:12 +00008297 }
8298 assert(PendingDeclChainsKnown.empty());
Guy Benyei11169dd2012-12-18 14:30:41 +00008299 PendingDeclChains.clear();
8300
Douglas Gregor6168bd22013-02-18 15:53:43 +00008301 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008302 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8303 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008304 IdentifierInfo *II = TLD->first;
8305 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008306 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008307 }
8308 }
8309
Guy Benyei11169dd2012-12-18 14:30:41 +00008310 // Load any pending macro definitions.
8311 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008312 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8313 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8314 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8315 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008316 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008317 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008318 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008319 if (Info.M->Kind != MK_ImplicitModule &&
8320 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008321 resolvePendingMacro(II, Info);
8322 }
8323 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008324 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008325 ++IDIdx) {
8326 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008327 if (Info.M->Kind == MK_ImplicitModule ||
8328 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008329 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008330 }
8331 }
8332 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008333
8334 // Wire up the DeclContexts for Decls that we delayed setting until
8335 // recursive loading is completed.
8336 while (!PendingDeclContextInfos.empty()) {
8337 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8338 PendingDeclContextInfos.pop_front();
8339 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8340 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8341 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8342 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008343
Richard Smithd1c46742014-04-30 02:24:17 +00008344 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008345 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008346 auto Update = PendingUpdateRecords.pop_back_val();
8347 ReadingKindTracker ReadingKind(Read_Decl, *this);
8348 loadDeclUpdateRecords(Update.first, Update.second);
8349 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008350 }
Richard Smith8a639892015-01-24 01:07:20 +00008351
8352 // At this point, all update records for loaded decls are in place, so any
8353 // fake class definitions should have become real.
8354 assert(PendingFakeDefinitionData.empty() &&
8355 "faked up a class definition but never saw the real one");
8356
Guy Benyei11169dd2012-12-18 14:30:41 +00008357 // If we deserialized any C++ or Objective-C class definitions, any
8358 // Objective-C protocol definitions, or any redeclarable templates, make sure
8359 // that all redeclarations point to the definitions. Note that this can only
8360 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008361 for (Decl *D : PendingDefinitions) {
8362 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008363 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008364 // Make sure that the TagType points at the definition.
8365 const_cast<TagType*>(TagT)->decl = TD;
8366 }
Richard Smith8ce51082015-03-11 01:44:51 +00008367
Craig Topperc6914d02014-08-25 04:15:02 +00008368 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008369 for (auto *R = getMostRecentExistingDecl(RD); R;
8370 R = R->getPreviousDecl()) {
8371 assert((R == D) ==
8372 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008373 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008374 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008375 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008376 }
8377
8378 continue;
8379 }
Richard Smith8ce51082015-03-11 01:44:51 +00008380
Craig Topperc6914d02014-08-25 04:15:02 +00008381 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008382 // Make sure that the ObjCInterfaceType points at the definition.
8383 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8384 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008385
8386 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8387 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8388
Guy Benyei11169dd2012-12-18 14:30:41 +00008389 continue;
8390 }
Richard Smith8ce51082015-03-11 01:44:51 +00008391
Craig Topperc6914d02014-08-25 04:15:02 +00008392 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008393 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8394 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8395
Guy Benyei11169dd2012-12-18 14:30:41 +00008396 continue;
8397 }
Richard Smith8ce51082015-03-11 01:44:51 +00008398
Craig Topperc6914d02014-08-25 04:15:02 +00008399 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008400 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8401 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008402 }
8403 PendingDefinitions.clear();
8404
8405 // Load the bodies of any functions or methods we've encountered. We do
8406 // this now (delayed) so that we can be sure that the declaration chains
8407 // have been fully wired up.
Richard Smith8ce51082015-03-11 01:44:51 +00008408 // FIXME: There seems to be no point in delaying this, it does not depend
8409 // on the redecl chains having been wired up.
Guy Benyei11169dd2012-12-18 14:30:41 +00008410 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8411 PBEnd = PendingBodies.end();
8412 PB != PBEnd; ++PB) {
8413 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8414 // FIXME: Check for =delete/=default?
8415 // FIXME: Complain about ODR violations here?
8416 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8417 FD->setLazyBody(PB->second);
8418 continue;
8419 }
8420
8421 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8422 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8423 MD->setLazyBody(PB->second);
8424 }
8425 PendingBodies.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008426}
8427
8428void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008429 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8430 return;
8431
Richard Smitha0ce9c42014-07-29 23:23:27 +00008432 // Trigger the import of the full definition of each class that had any
8433 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008434 // These updates may in turn find and diagnose some ODR failures, so take
8435 // ownership of the set first.
8436 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8437 PendingOdrMergeFailures.clear();
8438 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008439 Merge.first->buildLookup();
8440 Merge.first->decls_begin();
8441 Merge.first->bases_begin();
8442 Merge.first->vbases_begin();
8443 for (auto *RD : Merge.second) {
8444 RD->decls_begin();
8445 RD->bases_begin();
8446 RD->vbases_begin();
8447 }
8448 }
8449
8450 // For each declaration from a merged context, check that the canonical
8451 // definition of that context also contains a declaration of the same
8452 // entity.
8453 //
8454 // Caution: this loop does things that might invalidate iterators into
8455 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8456 while (!PendingOdrMergeChecks.empty()) {
8457 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8458
8459 // FIXME: Skip over implicit declarations for now. This matters for things
8460 // like implicitly-declared special member functions. This isn't entirely
8461 // correct; we can end up with multiple unmerged declarations of the same
8462 // implicit entity.
8463 if (D->isImplicit())
8464 continue;
8465
8466 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008467
8468 bool Found = false;
8469 const Decl *DCanon = D->getCanonicalDecl();
8470
Richard Smith01bdb7a2014-08-28 05:44:07 +00008471 for (auto RI : D->redecls()) {
8472 if (RI->getLexicalDeclContext() == CanonDef) {
8473 Found = true;
8474 break;
8475 }
8476 }
8477 if (Found)
8478 continue;
8479
Richard Smitha0ce9c42014-07-29 23:23:27 +00008480 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith01bdb7a2014-08-28 05:44:07 +00008481 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
Richard Smitha0ce9c42014-07-29 23:23:27 +00008482 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8483 !Found && I != E; ++I) {
8484 for (auto RI : (*I)->redecls()) {
8485 if (RI->getLexicalDeclContext() == CanonDef) {
8486 // This declaration is present in the canonical definition. If it's
8487 // in the same redecl chain, it's the one we're looking for.
8488 if (RI->getCanonicalDecl() == DCanon)
8489 Found = true;
8490 else
8491 Candidates.push_back(cast<NamedDecl>(RI));
8492 break;
8493 }
8494 }
8495 }
8496
8497 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008498 // The AST doesn't like TagDecls becoming invalid after they've been
8499 // completed. We only really need to mark FieldDecls as invalid here.
8500 if (!isa<TagDecl>(D))
8501 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008502
8503 // Ensure we don't accidentally recursively enter deserialization while
8504 // we're producing our diagnostic.
8505 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008506
8507 std::string CanonDefModule =
8508 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8509 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8510 << D << getOwningModuleNameForDiagnostic(D)
8511 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8512
8513 if (Candidates.empty())
8514 Diag(cast<Decl>(CanonDef)->getLocation(),
8515 diag::note_module_odr_violation_no_possible_decls) << D;
8516 else {
8517 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8518 Diag(Candidates[I]->getLocation(),
8519 diag::note_module_odr_violation_possible_decl)
8520 << Candidates[I];
8521 }
8522
8523 DiagnosedOdrMergeFailures.insert(CanonDef);
8524 }
8525 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008526
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008527 if (OdrMergeFailures.empty())
8528 return;
8529
8530 // Ensure we don't accidentally recursively enter deserialization while
8531 // we're producing our diagnostics.
8532 Deserializing RecursionGuard(this);
8533
Richard Smithcd45dbc2014-04-19 03:48:30 +00008534 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008535 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008536 // If we've already pointed out a specific problem with this class, don't
8537 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008538 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008539 continue;
8540
8541 bool Diagnosed = false;
8542 for (auto *RD : Merge.second) {
8543 // Multiple different declarations got merged together; tell the user
8544 // where they came from.
8545 if (Merge.first != RD) {
8546 // FIXME: Walk the definition, figure out what's different,
8547 // and diagnose that.
8548 if (!Diagnosed) {
8549 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8550 Diag(Merge.first->getLocation(),
8551 diag::err_module_odr_violation_different_definitions)
8552 << Merge.first << Module.empty() << Module;
8553 Diagnosed = true;
8554 }
8555
8556 Diag(RD->getLocation(),
8557 diag::note_module_odr_violation_different_definitions)
8558 << getOwningModuleNameForDiagnostic(RD);
8559 }
8560 }
8561
8562 if (!Diagnosed) {
8563 // All definitions are updates to the same declaration. This happens if a
8564 // module instantiates the declaration of a class template specialization
8565 // and two or more other modules instantiate its definition.
8566 //
8567 // FIXME: Indicate which modules had instantiations of this definition.
8568 // FIXME: How can this even happen?
8569 Diag(Merge.first->getLocation(),
8570 diag::err_module_odr_violation_different_instantiations)
8571 << Merge.first;
8572 }
8573 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008574}
8575
8576void ASTReader::FinishedDeserializing() {
8577 assert(NumCurrentElementsDeserializing &&
8578 "FinishedDeserializing not paired with StartedDeserializing");
8579 if (NumCurrentElementsDeserializing == 1) {
8580 // We decrease NumCurrentElementsDeserializing only after pending actions
8581 // are finished, to avoid recursively re-calling finishPendingActions().
8582 finishPendingActions();
8583 }
8584 --NumCurrentElementsDeserializing;
8585
Richard Smitha0ce9c42014-07-29 23:23:27 +00008586 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008587 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008588 while (!PendingExceptionSpecUpdates.empty()) {
8589 auto Updates = std::move(PendingExceptionSpecUpdates);
8590 PendingExceptionSpecUpdates.clear();
8591 for (auto Update : Updates) {
8592 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8593 SemaObj->UpdateExceptionSpec(Update.second,
8594 FPT->getExtProtoInfo().ExceptionSpec);
8595 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008596 }
8597
Richard Smitha0ce9c42014-07-29 23:23:27 +00008598 diagnoseOdrViolations();
8599
Richard Smith04d05b52014-03-23 00:27:18 +00008600 // We are not in recursive loading, so it's safe to pass the "interesting"
8601 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008602 if (Consumer)
8603 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008604 }
8605}
8606
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008607void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008608 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8609 // Remove any fake results before adding any real ones.
8610 auto It = PendingFakeLookupResults.find(II);
8611 if (It != PendingFakeLookupResults.end()) {
8612 for (auto *ND : PendingFakeLookupResults[II])
8613 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008614 // FIXME: this works around module+PCH performance issue.
8615 // Rather than erase the result from the map, which is O(n), just clear
8616 // the vector of NamedDecls.
8617 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008618 }
8619 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008620
8621 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8622 SemaObj->TUScope->AddDecl(D);
8623 } else if (SemaObj->TUScope) {
8624 // Adding the decl to IdResolver may have failed because it was already in
8625 // (even though it was not added in scope). If it is already in, make sure
8626 // it gets in the scope as well.
8627 if (std::find(SemaObj->IdResolver.begin(Name),
8628 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8629 SemaObj->TUScope->AddDecl(D);
8630 }
8631}
8632
Nico Weber824285e2014-05-08 04:26:47 +00008633ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
8634 bool DisableValidation, bool AllowASTWithCompilerErrors,
8635 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008636 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008637 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008638 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Craig Toppera13603a2014-05-22 05:54:18 +00008639 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
8640 SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
8641 ModuleMgr(PP.getFileManager()), isysroot(isysroot),
8642 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008643 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8644 AllowConfigurationMismatch(AllowConfigurationMismatch),
8645 ValidateSystemInputs(ValidateSystemInputs),
8646 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Richard Smith053f6c62014-05-16 23:01:30 +00008647 CurrSwitchCaseStmts(&SwitchCaseStmts),
Nico Weber824285e2014-05-08 04:26:47 +00008648 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
8649 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
8650 NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
8651 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8652 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8653 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8654 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8655 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8656 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008657 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008658 SourceMgr.setExternalSLocEntrySource(this);
8659}
8660
8661ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008662 if (OwnsDeserializationListener)
8663 delete DeserializationListener;
8664
Guy Benyei11169dd2012-12-18 14:30:41 +00008665 for (DeclContextVisibleUpdatesPending::iterator
8666 I = PendingVisibleUpdates.begin(),
8667 E = PendingVisibleUpdates.end();
8668 I != E; ++I) {
8669 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8670 F = I->second.end();
8671 J != F; ++J)
8672 delete J->first;
8673 }
8674}