blob: b763f022b4333798757d15aba336dbe0fbc3fe73 [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"
Adrian Prantlbb165fb2015-06-20 18:53:08 +000022#include "clang/Frontend/PCHContainerOperations.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000023#include "clang/AST/NestedNameSpecifier.h"
24#include "clang/AST/Type.h"
25#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000026#include "clang/Basic/DiagnosticOptions.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000027#include "clang/Basic/FileManager.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000028#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/SourceManagerInternals.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Basic/TargetOptions.h"
32#include "clang/Basic/Version.h"
33#include "clang/Basic/VersionTuple.h"
Ben Langmuirb92de022014-04-29 16:25:26 +000034#include "clang/Frontend/Utils.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000035#include "clang/Lex/HeaderSearch.h"
36#include "clang/Lex/HeaderSearchOptions.h"
37#include "clang/Lex/MacroInfo.h"
38#include "clang/Lex/PreprocessingRecord.h"
39#include "clang/Lex/Preprocessor.h"
40#include "clang/Lex/PreprocessorOptions.h"
41#include "clang/Sema/Scope.h"
42#include "clang/Sema/Sema.h"
43#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000044#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000045#include "clang/Serialization/ModuleManager.h"
46#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000047#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000048#include "llvm/ADT/StringExtras.h"
49#include "llvm/Bitcode/BitstreamReader.h"
50#include "llvm/Support/ErrorHandling.h"
51#include "llvm/Support/FileSystem.h"
52#include "llvm/Support/MemoryBuffer.h"
53#include "llvm/Support/Path.h"
54#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000055#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000056#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000057#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000058#include <iterator>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000059#include <system_error>
Guy Benyei11169dd2012-12-18 14:30:41 +000060
61using namespace clang;
62using namespace clang::serialization;
63using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000064using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000065
Ben Langmuircb69b572014-03-07 06:40:32 +000066
67//===----------------------------------------------------------------------===//
68// ChainedASTReaderListener implementation
69//===----------------------------------------------------------------------===//
70
71bool
72ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
73 return First->ReadFullVersionInformation(FullVersion) ||
74 Second->ReadFullVersionInformation(FullVersion);
75}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000076void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
77 First->ReadModuleName(ModuleName);
78 Second->ReadModuleName(ModuleName);
79}
80void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
81 First->ReadModuleMapFile(ModuleMapPath);
82 Second->ReadModuleMapFile(ModuleMapPath);
83}
Richard Smith1e2cf0d2014-10-31 02:28:58 +000084bool
85ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
86 bool Complain,
87 bool AllowCompatibleDifferences) {
88 return First->ReadLanguageOptions(LangOpts, Complain,
89 AllowCompatibleDifferences) ||
90 Second->ReadLanguageOptions(LangOpts, Complain,
91 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000092}
Chandler Carruth0d745bc2015-03-14 04:47:43 +000093bool ChainedASTReaderListener::ReadTargetOptions(
94 const TargetOptions &TargetOpts, bool Complain,
95 bool AllowCompatibleDifferences) {
96 return First->ReadTargetOptions(TargetOpts, Complain,
97 AllowCompatibleDifferences) ||
98 Second->ReadTargetOptions(TargetOpts, Complain,
99 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000100}
101bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000102 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000103 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
104 Second->ReadDiagnosticOptions(DiagOpts, Complain);
105}
106bool
107ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
108 bool Complain) {
109 return First->ReadFileSystemOptions(FSOpts, Complain) ||
110 Second->ReadFileSystemOptions(FSOpts, Complain);
111}
112
113bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000114 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
115 bool Complain) {
116 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
117 Complain) ||
118 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
119 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000120}
121bool ChainedASTReaderListener::ReadPreprocessorOptions(
122 const PreprocessorOptions &PPOpts, bool Complain,
123 std::string &SuggestedPredefines) {
124 return First->ReadPreprocessorOptions(PPOpts, Complain,
125 SuggestedPredefines) ||
126 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
127}
128void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
129 unsigned Value) {
130 First->ReadCounter(M, Value);
131 Second->ReadCounter(M, Value);
132}
133bool ChainedASTReaderListener::needsInputFileVisitation() {
134 return First->needsInputFileVisitation() ||
135 Second->needsInputFileVisitation();
136}
137bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
138 return First->needsSystemInputFileVisitation() ||
139 Second->needsSystemInputFileVisitation();
140}
Richard Smith216a3bd2015-08-13 17:57:10 +0000141void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
142 ModuleKind Kind) {
143 First->visitModuleFile(Filename, Kind);
144 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000145}
Ben Langmuircb69b572014-03-07 06:40:32 +0000146bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000147 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000148 bool isOverridden,
149 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000150 bool Continue = false;
151 if (First->needsInputFileVisitation() &&
152 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000153 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
154 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000155 if (Second->needsInputFileVisitation() &&
156 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000157 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
158 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000159 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000160}
161
Guy Benyei11169dd2012-12-18 14:30:41 +0000162//===----------------------------------------------------------------------===//
163// PCH validator implementation
164//===----------------------------------------------------------------------===//
165
166ASTReaderListener::~ASTReaderListener() {}
167
168/// \brief Compare the given set of language options against an existing set of
169/// language options.
170///
171/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000172/// \param AllowCompatibleDifferences If true, differences between compatible
173/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000174///
175/// \returns true if the languagae options mis-match, false otherwise.
176static bool checkLanguageOptions(const LangOptions &LangOpts,
177 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000178 DiagnosticsEngine *Diags,
179 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000180#define LANGOPT(Name, Bits, Default, Description) \
181 if (ExistingLangOpts.Name != LangOpts.Name) { \
182 if (Diags) \
183 Diags->Report(diag::err_pch_langopt_mismatch) \
184 << Description << LangOpts.Name << ExistingLangOpts.Name; \
185 return true; \
186 }
187
188#define VALUE_LANGOPT(Name, Bits, Default, Description) \
189 if (ExistingLangOpts.Name != LangOpts.Name) { \
190 if (Diags) \
191 Diags->Report(diag::err_pch_langopt_value_mismatch) \
192 << Description; \
193 return true; \
194 }
195
196#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
197 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
198 if (Diags) \
199 Diags->Report(diag::err_pch_langopt_value_mismatch) \
200 << Description; \
201 return true; \
202 }
203
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000204#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
205 if (!AllowCompatibleDifferences) \
206 LANGOPT(Name, Bits, Default, Description)
207
208#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
209 if (!AllowCompatibleDifferences) \
210 ENUM_LANGOPT(Name, Bits, Default, Description)
211
Guy Benyei11169dd2012-12-18 14:30:41 +0000212#define BENIGN_LANGOPT(Name, Bits, Default, Description)
213#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
214#include "clang/Basic/LangOptions.def"
215
Ben Langmuircd98cb72015-06-23 18:20:18 +0000216 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
217 if (Diags)
218 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
219 return true;
220 }
221
Guy Benyei11169dd2012-12-18 14:30:41 +0000222 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
223 if (Diags)
224 Diags->Report(diag::err_pch_langopt_value_mismatch)
225 << "target Objective-C runtime";
226 return true;
227 }
228
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000229 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
230 LangOpts.CommentOpts.BlockCommandNames) {
231 if (Diags)
232 Diags->Report(diag::err_pch_langopt_value_mismatch)
233 << "block command names";
234 return true;
235 }
236
Guy Benyei11169dd2012-12-18 14:30:41 +0000237 return false;
238}
239
240/// \brief Compare the given set of target options against an existing set of
241/// target options.
242///
243/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
244///
245/// \returns true if the target options mis-match, false otherwise.
246static bool checkTargetOptions(const TargetOptions &TargetOpts,
247 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000248 DiagnosticsEngine *Diags,
249 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000250#define CHECK_TARGET_OPT(Field, Name) \
251 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
252 if (Diags) \
253 Diags->Report(diag::err_pch_targetopt_mismatch) \
254 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
255 return true; \
256 }
257
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000258 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000259 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000260 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000261
262 // We can tolerate different CPUs in many cases, notably when one CPU
263 // supports a strict superset of another. When allowing compatible
264 // differences skip this check.
265 if (!AllowCompatibleDifferences)
266 CHECK_TARGET_OPT(CPU, "target CPU");
267
Guy Benyei11169dd2012-12-18 14:30:41 +0000268#undef CHECK_TARGET_OPT
269
270 // Compare feature sets.
271 SmallVector<StringRef, 4> ExistingFeatures(
272 ExistingTargetOpts.FeaturesAsWritten.begin(),
273 ExistingTargetOpts.FeaturesAsWritten.end());
274 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
275 TargetOpts.FeaturesAsWritten.end());
276 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
277 std::sort(ReadFeatures.begin(), ReadFeatures.end());
278
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000279 // We compute the set difference in both directions explicitly so that we can
280 // diagnose the differences differently.
281 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
282 std::set_difference(
283 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
284 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
285 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
286 ExistingFeatures.begin(), ExistingFeatures.end(),
287 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000288
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000289 // If we are allowing compatible differences and the read feature set is
290 // a strict subset of the existing feature set, there is nothing to diagnose.
291 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
292 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000293
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000294 if (Diags) {
295 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000296 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000297 << /* is-existing-feature */ false << Feature;
298 for (StringRef Feature : UnmatchedExistingFeatures)
299 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
300 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000301 }
302
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000303 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000304}
305
306bool
307PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000308 bool Complain,
309 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000310 const LangOptions &ExistingLangOpts = PP.getLangOpts();
311 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000312 Complain ? &Reader.Diags : nullptr,
313 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000314}
315
316bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000317 bool Complain,
318 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000319 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
320 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000321 Complain ? &Reader.Diags : nullptr,
322 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000323}
324
325namespace {
326 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
327 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000328 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
329 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000330}
331
Ben Langmuirb92de022014-04-29 16:25:26 +0000332static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
333 DiagnosticsEngine &Diags,
334 bool Complain) {
335 typedef DiagnosticsEngine::Level Level;
336
337 // Check current mappings for new -Werror mappings, and the stored mappings
338 // for cases that were explicitly mapped to *not* be errors that are now
339 // errors because of options like -Werror.
340 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
341
342 for (DiagnosticsEngine *MappingSource : MappingSources) {
343 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
344 diag::kind DiagID = DiagIDMappingPair.first;
345 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
346 if (CurLevel < DiagnosticsEngine::Error)
347 continue; // not significant
348 Level StoredLevel =
349 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
350 if (StoredLevel < DiagnosticsEngine::Error) {
351 if (Complain)
352 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
353 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
354 return true;
355 }
356 }
357 }
358
359 return false;
360}
361
Alp Tokerac4e8e52014-06-22 21:58:33 +0000362static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
363 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
364 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
365 return true;
366 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000367}
368
369static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
370 DiagnosticsEngine &Diags,
371 bool IsSystem, bool Complain) {
372 // Top-level options
373 if (IsSystem) {
374 if (Diags.getSuppressSystemWarnings())
375 return false;
376 // If -Wsystem-headers was not enabled before, be conservative
377 if (StoredDiags.getSuppressSystemWarnings()) {
378 if (Complain)
379 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
380 return true;
381 }
382 }
383
384 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
385 if (Complain)
386 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
387 return true;
388 }
389
390 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
391 !StoredDiags.getEnableAllWarnings()) {
392 if (Complain)
393 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
394 return true;
395 }
396
397 if (isExtHandlingFromDiagsError(Diags) &&
398 !isExtHandlingFromDiagsError(StoredDiags)) {
399 if (Complain)
400 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
401 return true;
402 }
403
404 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
405}
406
407bool PCHValidator::ReadDiagnosticOptions(
408 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
409 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
410 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
411 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000412 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000413 // This should never fail, because we would have processed these options
414 // before writing them to an ASTFile.
415 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
416
417 ModuleManager &ModuleMgr = Reader.getModuleManager();
418 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
419
420 // If the original import came from a file explicitly generated by the user,
421 // don't check the diagnostic mappings.
422 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000423 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000424 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
425 // the transitive closure of its imports, since unrelated modules cannot be
426 // imported until after this module finishes validation.
427 ModuleFile *TopImport = *ModuleMgr.rbegin();
428 while (!TopImport->ImportedBy.empty())
429 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000430 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000431 return false;
432
433 StringRef ModuleName = TopImport->ModuleName;
434 assert(!ModuleName.empty() && "diagnostic options read before module name");
435
436 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
437 assert(M && "missing module");
438
439 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
440 // contains the union of their flags.
441 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
442}
443
Guy Benyei11169dd2012-12-18 14:30:41 +0000444/// \brief Collect the macro definitions provided by the given preprocessor
445/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000446static void
447collectMacroDefinitions(const PreprocessorOptions &PPOpts,
448 MacroDefinitionsMap &Macros,
449 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000450 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
451 StringRef Macro = PPOpts.Macros[I].first;
452 bool IsUndef = PPOpts.Macros[I].second;
453
454 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
455 StringRef MacroName = MacroPair.first;
456 StringRef MacroBody = MacroPair.second;
457
458 // For an #undef'd macro, we only care about the name.
459 if (IsUndef) {
460 if (MacroNames && !Macros.count(MacroName))
461 MacroNames->push_back(MacroName);
462
463 Macros[MacroName] = std::make_pair("", true);
464 continue;
465 }
466
467 // For a #define'd macro, figure out the actual definition.
468 if (MacroName.size() == Macro.size())
469 MacroBody = "1";
470 else {
471 // Note: GCC drops anything following an end-of-line character.
472 StringRef::size_type End = MacroBody.find_first_of("\n\r");
473 MacroBody = MacroBody.substr(0, End);
474 }
475
476 if (MacroNames && !Macros.count(MacroName))
477 MacroNames->push_back(MacroName);
478 Macros[MacroName] = std::make_pair(MacroBody, false);
479 }
480}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000481
Guy Benyei11169dd2012-12-18 14:30:41 +0000482/// \brief Check the preprocessor options deserialized from the control block
483/// against the preprocessor options in an existing preprocessor.
484///
485/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
486static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
487 const PreprocessorOptions &ExistingPPOpts,
488 DiagnosticsEngine *Diags,
489 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000490 std::string &SuggestedPredefines,
491 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000492 // Check macro definitions.
493 MacroDefinitionsMap ASTFileMacros;
494 collectMacroDefinitions(PPOpts, ASTFileMacros);
495 MacroDefinitionsMap ExistingMacros;
496 SmallVector<StringRef, 4> ExistingMacroNames;
497 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
498
499 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
500 // Dig out the macro definition in the existing preprocessor options.
501 StringRef MacroName = ExistingMacroNames[I];
502 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
503
504 // Check whether we know anything about this macro name or not.
505 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
506 = ASTFileMacros.find(MacroName);
507 if (Known == ASTFileMacros.end()) {
508 // FIXME: Check whether this identifier was referenced anywhere in the
509 // AST file. If so, we should reject the AST file. Unfortunately, this
510 // information isn't in the control block. What shall we do about it?
511
512 if (Existing.second) {
513 SuggestedPredefines += "#undef ";
514 SuggestedPredefines += MacroName.str();
515 SuggestedPredefines += '\n';
516 } else {
517 SuggestedPredefines += "#define ";
518 SuggestedPredefines += MacroName.str();
519 SuggestedPredefines += ' ';
520 SuggestedPredefines += Existing.first.str();
521 SuggestedPredefines += '\n';
522 }
523 continue;
524 }
525
526 // If the macro was defined in one but undef'd in the other, we have a
527 // conflict.
528 if (Existing.second != Known->second.second) {
529 if (Diags) {
530 Diags->Report(diag::err_pch_macro_def_undef)
531 << MacroName << Known->second.second;
532 }
533 return true;
534 }
535
536 // If the macro was #undef'd in both, or if the macro bodies are identical,
537 // it's fine.
538 if (Existing.second || Existing.first == Known->second.first)
539 continue;
540
541 // The macro bodies differ; complain.
542 if (Diags) {
543 Diags->Report(diag::err_pch_macro_def_conflict)
544 << MacroName << Known->second.first << Existing.first;
545 }
546 return true;
547 }
548
549 // Check whether we're using predefines.
550 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
551 if (Diags) {
552 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
553 }
554 return true;
555 }
556
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000557 // Detailed record is important since it is used for the module cache hash.
558 if (LangOpts.Modules &&
559 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
560 if (Diags) {
561 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
562 }
563 return true;
564 }
565
Guy Benyei11169dd2012-12-18 14:30:41 +0000566 // Compute the #include and #include_macros lines we need.
567 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
568 StringRef File = ExistingPPOpts.Includes[I];
569 if (File == ExistingPPOpts.ImplicitPCHInclude)
570 continue;
571
572 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
573 != PPOpts.Includes.end())
574 continue;
575
576 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000577 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000578 SuggestedPredefines += "\"\n";
579 }
580
581 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
582 StringRef File = ExistingPPOpts.MacroIncludes[I];
583 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
584 File)
585 != PPOpts.MacroIncludes.end())
586 continue;
587
588 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000589 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000590 SuggestedPredefines += "\"\n##\n";
591 }
592
593 return false;
594}
595
596bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
597 bool Complain,
598 std::string &SuggestedPredefines) {
599 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
600
601 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000602 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000603 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000604 SuggestedPredefines,
605 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000606}
607
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000608/// Check the header search options deserialized from the control block
609/// against the header search options in an existing preprocessor.
610///
611/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
612static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
613 StringRef SpecificModuleCachePath,
614 StringRef ExistingModuleCachePath,
615 DiagnosticsEngine *Diags,
616 const LangOptions &LangOpts) {
617 if (LangOpts.Modules) {
618 if (SpecificModuleCachePath != ExistingModuleCachePath) {
619 if (Diags)
620 Diags->Report(diag::err_pch_modulecache_mismatch)
621 << SpecificModuleCachePath << ExistingModuleCachePath;
622 return true;
623 }
624 }
625
626 return false;
627}
628
629bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
630 StringRef SpecificModuleCachePath,
631 bool Complain) {
632 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
633 PP.getHeaderSearchInfo().getModuleCachePath(),
634 Complain ? &Reader.Diags : nullptr,
635 PP.getLangOpts());
636}
637
Guy Benyei11169dd2012-12-18 14:30:41 +0000638void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
639 PP.setCounterValue(Value);
640}
641
642//===----------------------------------------------------------------------===//
643// AST reader implementation
644//===----------------------------------------------------------------------===//
645
Nico Weber824285e2014-05-08 04:26:47 +0000646void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
647 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000648 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000649 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000650}
651
652
653
654unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
655 return serialization::ComputeHash(Sel);
656}
657
658
659std::pair<unsigned, unsigned>
660ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000661 using namespace llvm::support;
662 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
663 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000664 return std::make_pair(KeyLen, DataLen);
665}
666
667ASTSelectorLookupTrait::internal_key_type
668ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000669 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000670 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000671 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
672 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
673 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000674 if (N == 0)
675 return SelTable.getNullarySelector(FirstII);
676 else if (N == 1)
677 return SelTable.getUnarySelector(FirstII);
678
679 SmallVector<IdentifierInfo *, 16> Args;
680 Args.push_back(FirstII);
681 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000682 Args.push_back(Reader.getLocalIdentifier(
683 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000684
685 return SelTable.getSelector(N, Args.data());
686}
687
688ASTSelectorLookupTrait::data_type
689ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
690 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000691 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000692
693 data_type Result;
694
Justin Bogner57ba0b22014-03-28 22:03:24 +0000695 Result.ID = Reader.getGlobalSelectorID(
696 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000697 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
698 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
699 Result.InstanceBits = FullInstanceBits & 0x3;
700 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
701 Result.FactoryBits = FullFactoryBits & 0x3;
702 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
703 unsigned NumInstanceMethods = FullInstanceBits >> 3;
704 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000705
706 // Load instance methods
707 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000708 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
709 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000710 Result.Instance.push_back(Method);
711 }
712
713 // Load factory methods
714 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000715 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
716 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000717 Result.Factory.push_back(Method);
718 }
719
720 return Result;
721}
722
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000723unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
724 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000725}
726
727std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000728ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000729 using namespace llvm::support;
730 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
731 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000732 return std::make_pair(KeyLen, DataLen);
733}
734
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000735ASTIdentifierLookupTraitBase::internal_key_type
736ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000737 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000738 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000739}
740
Douglas Gregordcf25082013-02-11 18:16:18 +0000741/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000742static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
743 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000744 return II.hadMacroDefinition() ||
745 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000746 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000747 II.hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +0000748 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
749 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000750}
751
Richard Smith76c2f2c2015-07-17 20:09:43 +0000752static bool readBit(unsigned &Bits) {
753 bool Value = Bits & 0x1;
754 Bits >>= 1;
755 return Value;
756}
757
Guy Benyei11169dd2012-12-18 14:30:41 +0000758IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
759 const unsigned char* d,
760 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000761 using namespace llvm::support;
762 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000763 bool IsInteresting = RawID & 0x01;
764
765 // Wipe out the "is interesting" bit.
766 RawID = RawID >> 1;
767
Richard Smith76c2f2c2015-07-17 20:09:43 +0000768 // Build the IdentifierInfo and link the identifier ID with it.
769 IdentifierInfo *II = KnownII;
770 if (!II) {
771 II = &Reader.getIdentifierTable().getOwn(k);
772 KnownII = II;
773 }
774 if (!II->isFromAST()) {
775 II->setIsFromAST();
Richard Smitha534a312015-07-21 23:54:07 +0000776 if (isInterestingIdentifier(Reader, *II, F.isModule()))
Richard Smith76c2f2c2015-07-17 20:09:43 +0000777 II->setChangedSinceDeserialization();
778 }
779 Reader.markIdentifierUpToDate(II);
780
Guy Benyei11169dd2012-12-18 14:30:41 +0000781 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
782 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000783 // For uninteresting identifiers, there's nothing else to do. Just notify
784 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000785 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000786 return II;
787 }
788
Justin Bogner57ba0b22014-03-28 22:03:24 +0000789 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
790 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000791 bool CPlusPlusOperatorKeyword = readBit(Bits);
792 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000793 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000794 bool Poisoned = readBit(Bits);
795 bool ExtensionToken = readBit(Bits);
796 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000797
798 assert(Bits == 0 && "Extra bits in the identifier?");
799 DataLen -= 8;
800
Guy Benyei11169dd2012-12-18 14:30:41 +0000801 // 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)
Richard Smith9c254182015-07-19 21:41:12 +0000804 II->revertTokenIDToIdentifier();
805 if (!F.isModule())
806 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
807 else if (HasRevertedBuiltin && II->getBuiltinID()) {
808 II->revertBuiltin();
809 assert((II->hasRevertedBuiltin() ||
810 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
811 "Incorrect ObjC keyword or builtin ID");
812 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000813 assert(II->isExtensionToken() == ExtensionToken &&
814 "Incorrect extension token flag");
815 (void)ExtensionToken;
816 if (Poisoned)
817 II->setIsPoisoned(true);
818 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
819 "Incorrect C++ operator keyword flag");
820 (void)CPlusPlusOperatorKeyword;
821
822 // If this identifier is a macro, deserialize the macro
823 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000824 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000825 uint32_t MacroDirectivesOffset =
826 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000827 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000828
Richard Smithd7329392015-04-21 21:46:32 +0000829 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000830 }
831
832 Reader.SetIdentifierInfo(ID, II);
833
834 // Read all of the declarations visible at global scope with this
835 // name.
836 if (DataLen > 0) {
837 SmallVector<uint32_t, 4> DeclIDs;
838 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000839 DeclIDs.push_back(Reader.getGlobalDeclID(
840 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000841 Reader.SetGloballyVisibleDecls(II, DeclIDs);
842 }
843
844 return II;
845}
846
847unsigned
Richard Smith3b637412015-07-14 18:42:41 +0000848ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000849 llvm::FoldingSetNodeID ID;
850 ID.AddInteger(Key.Kind);
851
852 switch (Key.Kind) {
853 case DeclarationName::Identifier:
854 case DeclarationName::CXXLiteralOperatorName:
855 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
856 break;
857 case DeclarationName::ObjCZeroArgSelector:
858 case DeclarationName::ObjCOneArgSelector:
859 case DeclarationName::ObjCMultiArgSelector:
860 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
861 break;
862 case DeclarationName::CXXOperatorName:
863 ID.AddInteger((OverloadedOperatorKind)Key.Data);
864 break;
865 case DeclarationName::CXXConstructorName:
866 case DeclarationName::CXXDestructorName:
867 case DeclarationName::CXXConversionFunctionName:
868 case DeclarationName::CXXUsingDirective:
869 break;
870 }
871
872 return ID.ComputeHash();
873}
874
875ASTDeclContextNameLookupTrait::internal_key_type
876ASTDeclContextNameLookupTrait::GetInternalKey(
Richard Smith3b637412015-07-14 18:42:41 +0000877 const external_key_type& Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000878 DeclNameKey Key;
879 Key.Kind = Name.getNameKind();
880 switch (Name.getNameKind()) {
881 case DeclarationName::Identifier:
882 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
883 break;
884 case DeclarationName::ObjCZeroArgSelector:
885 case DeclarationName::ObjCOneArgSelector:
886 case DeclarationName::ObjCMultiArgSelector:
887 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
888 break;
889 case DeclarationName::CXXOperatorName:
890 Key.Data = Name.getCXXOverloadedOperator();
891 break;
892 case DeclarationName::CXXLiteralOperatorName:
893 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
894 break;
895 case DeclarationName::CXXConstructorName:
896 case DeclarationName::CXXDestructorName:
897 case DeclarationName::CXXConversionFunctionName:
898 case DeclarationName::CXXUsingDirective:
899 Key.Data = 0;
900 break;
901 }
902
903 return Key;
904}
905
906std::pair<unsigned, unsigned>
907ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000908 using namespace llvm::support;
909 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
910 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000911 return std::make_pair(KeyLen, DataLen);
912}
913
914ASTDeclContextNameLookupTrait::internal_key_type
915ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000916 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000917
918 DeclNameKey Key;
919 Key.Kind = (DeclarationName::NameKind)*d++;
920 switch (Key.Kind) {
921 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000922 Key.Data = (uint64_t)Reader.getLocalIdentifier(
923 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000924 break;
925 case DeclarationName::ObjCZeroArgSelector:
926 case DeclarationName::ObjCOneArgSelector:
927 case DeclarationName::ObjCMultiArgSelector:
928 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000929 (uint64_t)Reader.getLocalSelector(
930 F, endian::readNext<uint32_t, little, unaligned>(
931 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000932 break;
933 case DeclarationName::CXXOperatorName:
934 Key.Data = *d++; // OverloadedOperatorKind
935 break;
936 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000937 Key.Data = (uint64_t)Reader.getLocalIdentifier(
938 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000939 break;
940 case DeclarationName::CXXConstructorName:
941 case DeclarationName::CXXDestructorName:
942 case DeclarationName::CXXConversionFunctionName:
943 case DeclarationName::CXXUsingDirective:
944 Key.Data = 0;
945 break;
946 }
947
948 return Key;
949}
950
Richard Smithf02662d2015-07-30 03:17:16 +0000951ASTDeclContextNameLookupTrait::data_type
952ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
953 const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000954 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000955 using namespace llvm::support;
Richard Smithf02662d2015-07-30 03:17:16 +0000956 unsigned NumDecls = DataLen / 4;
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000957 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
958 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000959 return std::make_pair(Start, Start + NumDecls);
960}
961
Richard Smith0f4e2c42015-08-06 04:23:48 +0000962bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
963 BitstreamCursor &Cursor,
964 uint64_t Offset,
965 DeclContext *DC) {
966 assert(Offset != 0);
967
Guy Benyei11169dd2012-12-18 14:30:41 +0000968 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +0000969 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000970
Richard Smith0f4e2c42015-08-06 04:23:48 +0000971 RecordData Record;
972 StringRef Blob;
973 unsigned Code = Cursor.ReadCode();
974 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
975 if (RecCode != DECL_CONTEXT_LEXICAL) {
976 Error("Expected lexical block");
977 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000978 }
979
Richard Smith82f8fcd2015-08-06 22:07:25 +0000980 assert(!isa<TranslationUnitDecl>(DC) &&
981 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +0000982 // If we are handling a C++ class template instantiation, we can see multiple
983 // lexical updates for the same record. It's important that we select only one
984 // of them, so that field numbering works properly. Just pick the first one we
985 // see.
986 auto &Lex = LexicalDecls[DC];
987 if (!Lex.first) {
988 Lex = std::make_pair(
989 &M, llvm::makeArrayRef(
990 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
991 Blob.data()),
992 Blob.size() / 4));
993 }
Richard Smith0f4e2c42015-08-06 04:23:48 +0000994 DC->setHasExternalLexicalStorage(true);
995 return false;
996}
Guy Benyei11169dd2012-12-18 14:30:41 +0000997
Richard Smith0f4e2c42015-08-06 04:23:48 +0000998bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
999 BitstreamCursor &Cursor,
1000 uint64_t Offset,
1001 DeclID ID) {
1002 assert(Offset != 0);
1003
1004 SavedStreamPosition SavedPosition(Cursor);
1005 Cursor.JumpToBit(Offset);
1006
1007 RecordData Record;
1008 StringRef Blob;
1009 unsigned Code = Cursor.ReadCode();
1010 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1011 if (RecCode != DECL_CONTEXT_VISIBLE) {
1012 Error("Expected visible lookup table block");
1013 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001014 }
1015
Richard Smith0f4e2c42015-08-06 04:23:48 +00001016 // We can't safely determine the primary context yet, so delay attaching the
1017 // lookup table until we're done with recursive deserialization.
1018 unsigned BucketOffset = Record[0];
1019 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{
1020 &M, (const unsigned char *)Blob.data(), BucketOffset});
Guy Benyei11169dd2012-12-18 14:30:41 +00001021 return false;
1022}
1023
1024void ASTReader::Error(StringRef Msg) {
1025 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithfb1e7f72015-08-14 05:02:58 +00001026 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1027 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001028 Diag(diag::note_module_cache_path)
1029 << PP.getHeaderSearchInfo().getModuleCachePath();
1030 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001031}
1032
1033void ASTReader::Error(unsigned DiagID,
1034 StringRef Arg1, StringRef Arg2) {
1035 if (Diags.isDiagnosticInFlight())
1036 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1037 else
1038 Diag(DiagID) << Arg1 << Arg2;
1039}
1040
1041//===----------------------------------------------------------------------===//
1042// Source Manager Deserialization
1043//===----------------------------------------------------------------------===//
1044
1045/// \brief Read the line table in the source manager block.
1046/// \returns true if there was an error.
1047bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001048 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001049 unsigned Idx = 0;
1050 LineTableInfo &LineTable = SourceMgr.getLineTable();
1051
1052 // Parse the file names
1053 std::map<int, int> FileIDs;
1054 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1055 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001056 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001057 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1058 }
1059
1060 // Parse the line entries
1061 std::vector<LineEntry> Entries;
1062 while (Idx < Record.size()) {
1063 int FID = Record[Idx++];
1064 assert(FID >= 0 && "Serialized line entries for non-local file.");
1065 // Remap FileID from 1-based old view.
1066 FID += F.SLocEntryBaseID - 1;
1067
1068 // Extract the line entries
1069 unsigned NumEntries = Record[Idx++];
1070 assert(NumEntries && "Numentries is 00000");
1071 Entries.clear();
1072 Entries.reserve(NumEntries);
1073 for (unsigned I = 0; I != NumEntries; ++I) {
1074 unsigned FileOffset = Record[Idx++];
1075 unsigned LineNo = Record[Idx++];
1076 int FilenameID = FileIDs[Record[Idx++]];
1077 SrcMgr::CharacteristicKind FileKind
1078 = (SrcMgr::CharacteristicKind)Record[Idx++];
1079 unsigned IncludeOffset = Record[Idx++];
1080 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1081 FileKind, IncludeOffset));
1082 }
1083 LineTable.AddEntry(FileID::get(FID), Entries);
1084 }
1085
1086 return false;
1087}
1088
1089/// \brief Read a source manager block
1090bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1091 using namespace SrcMgr;
1092
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001093 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001094
1095 // Set the source-location entry cursor to the current position in
1096 // the stream. This cursor will be used to read the contents of the
1097 // source manager block initially, and then lazily read
1098 // source-location entries as needed.
1099 SLocEntryCursor = F.Stream;
1100
1101 // The stream itself is going to skip over the source manager block.
1102 if (F.Stream.SkipBlock()) {
1103 Error("malformed block record in AST file");
1104 return true;
1105 }
1106
1107 // Enter the source manager block.
1108 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1109 Error("malformed source manager block record in AST file");
1110 return true;
1111 }
1112
1113 RecordData Record;
1114 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001115 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1116
1117 switch (E.Kind) {
1118 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1119 case llvm::BitstreamEntry::Error:
1120 Error("malformed block record in AST file");
1121 return true;
1122 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001123 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001124 case llvm::BitstreamEntry::Record:
1125 // The interesting case.
1126 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001127 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001128
Guy Benyei11169dd2012-12-18 14:30:41 +00001129 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001130 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001131 StringRef Blob;
1132 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001133 default: // Default behavior: ignore.
1134 break;
1135
1136 case SM_SLOC_FILE_ENTRY:
1137 case SM_SLOC_BUFFER_ENTRY:
1138 case SM_SLOC_EXPANSION_ENTRY:
1139 // Once we hit one of the source location entries, we're done.
1140 return false;
1141 }
1142 }
1143}
1144
1145/// \brief If a header file is not found at the path that we expect it to be
1146/// and the PCH file was moved from its original location, try to resolve the
1147/// file by assuming that header+PCH were moved together and the header is in
1148/// the same place relative to the PCH.
1149static std::string
1150resolveFileRelativeToOriginalDir(const std::string &Filename,
1151 const std::string &OriginalDir,
1152 const std::string &CurrDir) {
1153 assert(OriginalDir != CurrDir &&
1154 "No point trying to resolve the file if the PCH dir didn't change");
1155 using namespace llvm::sys;
1156 SmallString<128> filePath(Filename);
1157 fs::make_absolute(filePath);
1158 assert(path::is_absolute(OriginalDir));
1159 SmallString<128> currPCHPath(CurrDir);
1160
1161 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1162 fileDirE = path::end(path::parent_path(filePath));
1163 path::const_iterator origDirI = path::begin(OriginalDir),
1164 origDirE = path::end(OriginalDir);
1165 // Skip the common path components from filePath and OriginalDir.
1166 while (fileDirI != fileDirE && origDirI != origDirE &&
1167 *fileDirI == *origDirI) {
1168 ++fileDirI;
1169 ++origDirI;
1170 }
1171 for (; origDirI != origDirE; ++origDirI)
1172 path::append(currPCHPath, "..");
1173 path::append(currPCHPath, fileDirI, fileDirE);
1174 path::append(currPCHPath, path::filename(Filename));
1175 return currPCHPath.str();
1176}
1177
1178bool ASTReader::ReadSLocEntry(int ID) {
1179 if (ID == 0)
1180 return false;
1181
1182 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1183 Error("source location entry ID out-of-range for AST file");
1184 return true;
1185 }
1186
1187 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1188 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001189 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001190 unsigned BaseOffset = F->SLocEntryBaseOffset;
1191
1192 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001193 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1194 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001195 Error("incorrectly-formatted source location entry in AST file");
1196 return true;
1197 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001198
Guy Benyei11169dd2012-12-18 14:30:41 +00001199 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001200 StringRef Blob;
1201 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001202 default:
1203 Error("incorrectly-formatted source location entry in AST file");
1204 return true;
1205
1206 case SM_SLOC_FILE_ENTRY: {
1207 // We will detect whether a file changed and return 'Failure' for it, but
1208 // we will also try to fail gracefully by setting up the SLocEntry.
1209 unsigned InputID = Record[4];
1210 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001211 const FileEntry *File = IF.getFile();
1212 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001213
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001214 // Note that we only check if a File was returned. If it was out-of-date
1215 // we have complained but we will continue creating a FileID to recover
1216 // gracefully.
1217 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001218 return true;
1219
1220 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1221 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1222 // This is the module's main file.
1223 IncludeLoc = getImportLocation(F);
1224 }
1225 SrcMgr::CharacteristicKind
1226 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1227 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1228 ID, BaseOffset + Record[0]);
1229 SrcMgr::FileInfo &FileInfo =
1230 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1231 FileInfo.NumCreatedFIDs = Record[5];
1232 if (Record[3])
1233 FileInfo.setHasLineDirectives();
1234
1235 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1236 unsigned NumFileDecls = Record[7];
1237 if (NumFileDecls) {
1238 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1239 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1240 NumFileDecls));
1241 }
1242
1243 const SrcMgr::ContentCache *ContentCache
1244 = SourceMgr.getOrCreateContentCache(File,
1245 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1246 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1247 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1248 unsigned Code = SLocEntryCursor.ReadCode();
1249 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001250 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001251
1252 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1253 Error("AST record has invalid code");
1254 return true;
1255 }
1256
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001257 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001258 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001259 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001260 }
1261
1262 break;
1263 }
1264
1265 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001266 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001267 unsigned Offset = Record[0];
1268 SrcMgr::CharacteristicKind
1269 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1270 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001271 if (IncludeLoc.isInvalid() &&
1272 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001273 IncludeLoc = getImportLocation(F);
1274 }
1275 unsigned Code = SLocEntryCursor.ReadCode();
1276 Record.clear();
1277 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001278 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001279
1280 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1281 Error("AST record has invalid code");
1282 return true;
1283 }
1284
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001285 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1286 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001287 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001288 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001289 break;
1290 }
1291
1292 case SM_SLOC_EXPANSION_ENTRY: {
1293 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1294 SourceMgr.createExpansionLoc(SpellingLoc,
1295 ReadSourceLocation(*F, Record[2]),
1296 ReadSourceLocation(*F, Record[3]),
1297 Record[4],
1298 ID,
1299 BaseOffset + Record[0]);
1300 break;
1301 }
1302 }
1303
1304 return false;
1305}
1306
1307std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1308 if (ID == 0)
1309 return std::make_pair(SourceLocation(), "");
1310
1311 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1312 Error("source location entry ID out-of-range for AST file");
1313 return std::make_pair(SourceLocation(), "");
1314 }
1315
1316 // Find which module file this entry lands in.
1317 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001318 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001319 return std::make_pair(SourceLocation(), "");
1320
1321 // FIXME: Can we map this down to a particular submodule? That would be
1322 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001323 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001324}
1325
1326/// \brief Find the location where the module F is imported.
1327SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1328 if (F->ImportLoc.isValid())
1329 return F->ImportLoc;
1330
1331 // Otherwise we have a PCH. It's considered to be "imported" at the first
1332 // location of its includer.
1333 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001334 // Main file is the importer.
1335 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1336 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001337 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001338 return F->ImportedBy[0]->FirstLoc;
1339}
1340
1341/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1342/// specified cursor. Read the abbreviations that are at the top of the block
1343/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001344bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001345 if (Cursor.EnterSubBlock(BlockID)) {
1346 Error("malformed block record in AST file");
1347 return Failure;
1348 }
1349
1350 while (true) {
1351 uint64_t Offset = Cursor.GetCurrentBitNo();
1352 unsigned Code = Cursor.ReadCode();
1353
1354 // We expect all abbrevs to be at the start of the block.
1355 if (Code != llvm::bitc::DEFINE_ABBREV) {
1356 Cursor.JumpToBit(Offset);
1357 return false;
1358 }
1359 Cursor.ReadAbbrevRecord();
1360 }
1361}
1362
Richard Smithe40f2ba2013-08-07 21:41:30 +00001363Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001364 unsigned &Idx) {
1365 Token Tok;
1366 Tok.startToken();
1367 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1368 Tok.setLength(Record[Idx++]);
1369 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1370 Tok.setIdentifierInfo(II);
1371 Tok.setKind((tok::TokenKind)Record[Idx++]);
1372 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1373 return Tok;
1374}
1375
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001376MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001377 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001378
1379 // Keep track of where we are in the stream, then jump back there
1380 // after reading this macro.
1381 SavedStreamPosition SavedPosition(Stream);
1382
1383 Stream.JumpToBit(Offset);
1384 RecordData Record;
1385 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001386 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001387
Guy Benyei11169dd2012-12-18 14:30:41 +00001388 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001389 // Advance to the next record, but if we get to the end of the block, don't
1390 // pop it (removing all the abbreviations from the cursor) since we want to
1391 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001392 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001393 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1394
1395 switch (Entry.Kind) {
1396 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1397 case llvm::BitstreamEntry::Error:
1398 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001399 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001400 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001401 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001402 case llvm::BitstreamEntry::Record:
1403 // The interesting case.
1404 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001405 }
1406
1407 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001408 Record.clear();
1409 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001410 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001411 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001412 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001413 case PP_MACRO_DIRECTIVE_HISTORY:
1414 return Macro;
1415
Guy Benyei11169dd2012-12-18 14:30:41 +00001416 case PP_MACRO_OBJECT_LIKE:
1417 case PP_MACRO_FUNCTION_LIKE: {
1418 // If we already have a macro, that means that we've hit the end
1419 // of the definition of the macro we were looking for. We're
1420 // done.
1421 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001422 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001423
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001424 unsigned NextIndex = 1; // Skip identifier ID.
1425 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001426 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001427 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001428 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001429 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001430 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001431
Guy Benyei11169dd2012-12-18 14:30:41 +00001432 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1433 // Decode function-like macro info.
1434 bool isC99VarArgs = Record[NextIndex++];
1435 bool isGNUVarArgs = Record[NextIndex++];
1436 bool hasCommaPasting = Record[NextIndex++];
1437 MacroArgs.clear();
1438 unsigned NumArgs = Record[NextIndex++];
1439 for (unsigned i = 0; i != NumArgs; ++i)
1440 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1441
1442 // Install function-like macro info.
1443 MI->setIsFunctionLike();
1444 if (isC99VarArgs) MI->setIsC99Varargs();
1445 if (isGNUVarArgs) MI->setIsGNUVarargs();
1446 if (hasCommaPasting) MI->setHasCommaPasting();
1447 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1448 PP.getPreprocessorAllocator());
1449 }
1450
Guy Benyei11169dd2012-12-18 14:30:41 +00001451 // Remember that we saw this macro last so that we add the tokens that
1452 // form its body to it.
1453 Macro = MI;
1454
1455 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1456 Record[NextIndex]) {
1457 // We have a macro definition. Register the association
1458 PreprocessedEntityID
1459 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1460 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001461 PreprocessingRecord::PPEntityID PPID =
1462 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1463 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1464 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001465 if (PPDef)
1466 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001467 }
1468
1469 ++NumMacrosRead;
1470 break;
1471 }
1472
1473 case PP_TOKEN: {
1474 // If we see a TOKEN before a PP_MACRO_*, then the file is
1475 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001476 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001477
John McCallf413f5e2013-05-03 00:10:13 +00001478 unsigned Idx = 0;
1479 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001480 Macro->AddTokenToBody(Tok);
1481 break;
1482 }
1483 }
1484 }
1485}
1486
1487PreprocessedEntityID
1488ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1489 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1490 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1491 assert(I != M.PreprocessedEntityRemap.end()
1492 && "Invalid index into preprocessed entity index remap");
1493
1494 return LocalID + I->second;
1495}
1496
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001497unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1498 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001499}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001500
Guy Benyei11169dd2012-12-18 14:30:41 +00001501HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001502HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001503 internal_key_type ikey = {FE->getSize(),
1504 M.HasTimestamps ? FE->getModificationTime() : 0,
1505 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001506 return ikey;
1507}
Guy Benyei11169dd2012-12-18 14:30:41 +00001508
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001509bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001510 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001511 return false;
1512
Richard Smith7ed1bc92014-12-05 22:42:13 +00001513 if (llvm::sys::path::is_absolute(a.Filename) &&
1514 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001515 return true;
1516
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001518 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001519 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1520 if (!Key.Imported)
1521 return FileMgr.getFile(Key.Filename);
1522
1523 std::string Resolved = Key.Filename;
1524 Reader.ResolveImportedPath(M, Resolved);
1525 return FileMgr.getFile(Resolved);
1526 };
1527
1528 const FileEntry *FEA = GetFile(a);
1529 const FileEntry *FEB = GetFile(b);
1530 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001531}
1532
1533std::pair<unsigned, unsigned>
1534HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001535 using namespace llvm::support;
1536 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001537 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001538 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001539}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001540
1541HeaderFileInfoTrait::internal_key_type
1542HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001543 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001544 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001545 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1546 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001547 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001548 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001549 return ikey;
1550}
1551
Guy Benyei11169dd2012-12-18 14:30:41 +00001552HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001553HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001554 unsigned DataLen) {
1555 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001556 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001557 HeaderFileInfo HFI;
1558 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001559 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1560 HFI.isImport |= (Flags >> 4) & 0x01;
1561 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1562 HFI.DirInfo = (Flags >> 1) & 0x03;
Guy Benyei11169dd2012-12-18 14:30:41 +00001563 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001564 // FIXME: Find a better way to handle this. Maybe just store a
1565 // "has been included" flag?
1566 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1567 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001568 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1569 M, endian::readNext<uint32_t, little, unaligned>(d));
1570 if (unsigned FrameworkOffset =
1571 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001572 // The framework offset is 1 greater than the actual offset,
1573 // since 0 is used as an indicator for "no framework name".
1574 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1575 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1576 }
Richard Smith386bb072015-08-18 23:42:23 +00001577
1578 assert((End - d) % 4 == 0 &&
1579 "Wrong data length in HeaderFileInfo deserialization");
1580 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001581 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001582 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1583 LocalSMID >>= 2;
1584
1585 // This header is part of a module. Associate it with the module to enable
1586 // implicit module import.
1587 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1588 Module *Mod = Reader.getSubmodule(GlobalSMID);
1589 FileManager &FileMgr = Reader.getFileManager();
1590 ModuleMap &ModMap =
1591 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1592
1593 std::string Filename = key.Filename;
1594 if (key.Imported)
1595 Reader.ResolveImportedPath(M, Filename);
1596 // FIXME: This is not always the right filename-as-written, but we're not
1597 // going to use this information to rebuild the module, so it doesn't make
1598 // a lot of difference.
1599 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
1600 ModMap.addHeader(Mod, H, HeaderRole);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001601 }
1602
Guy Benyei11169dd2012-12-18 14:30:41 +00001603 // This HeaderFileInfo was externally loaded.
1604 HFI.External = true;
1605 return HFI;
1606}
1607
Richard Smithd7329392015-04-21 21:46:32 +00001608void ASTReader::addPendingMacro(IdentifierInfo *II,
1609 ModuleFile *M,
1610 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001611 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1612 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001613}
1614
1615void ASTReader::ReadDefinedMacros() {
1616 // Note that we are loading defined macros.
1617 Deserializing Macros(this);
1618
Pete Cooper57d3f142015-07-30 17:22:52 +00001619 for (auto &I : llvm::reverse(ModuleMgr)) {
1620 BitstreamCursor &MacroCursor = I->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001621
1622 // If there was no preprocessor block, skip this file.
1623 if (!MacroCursor.getBitStreamReader())
1624 continue;
1625
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001626 BitstreamCursor Cursor = MacroCursor;
Pete Cooper57d3f142015-07-30 17:22:52 +00001627 Cursor.JumpToBit(I->MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001628
1629 RecordData Record;
1630 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001631 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1632
1633 switch (E.Kind) {
1634 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1635 case llvm::BitstreamEntry::Error:
1636 Error("malformed block record in AST file");
1637 return;
1638 case llvm::BitstreamEntry::EndBlock:
1639 goto NextCursor;
1640
1641 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001642 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001643 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001644 default: // Default behavior: ignore.
1645 break;
1646
1647 case PP_MACRO_OBJECT_LIKE:
1648 case PP_MACRO_FUNCTION_LIKE:
Pete Cooper57d3f142015-07-30 17:22:52 +00001649 getLocalIdentifier(*I, Record[0]);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001650 break;
1651
1652 case PP_TOKEN:
1653 // Ignore tokens.
1654 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001655 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001656 break;
1657 }
1658 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001659 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001660 }
1661}
1662
1663namespace {
1664 /// \brief Visitor class used to look up identifirs in an AST file.
1665 class IdentifierLookupVisitor {
1666 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001667 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001668 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001669 unsigned &NumIdentifierLookups;
1670 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001671 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001672
Guy Benyei11169dd2012-12-18 14:30:41 +00001673 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001674 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1675 unsigned &NumIdentifierLookups,
1676 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001677 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1678 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001679 NumIdentifierLookups(NumIdentifierLookups),
1680 NumIdentifierLookupHits(NumIdentifierLookupHits),
1681 Found()
1682 {
1683 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001684
1685 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001686 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001687 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001688 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001689
Guy Benyei11169dd2012-12-18 14:30:41 +00001690 ASTIdentifierLookupTable *IdTable
1691 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1692 if (!IdTable)
1693 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001694
1695 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001696 Found);
1697 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001698 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001699 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001700 if (Pos == IdTable->end())
1701 return false;
1702
1703 // Dereferencing the iterator has the effect of building the
1704 // IdentifierInfo node and populating it with the various
1705 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001706 ++NumIdentifierLookupHits;
1707 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001708 return true;
1709 }
1710
1711 // \brief Retrieve the identifier info found within the module
1712 // files.
1713 IdentifierInfo *getIdentifierInfo() const { return Found; }
1714 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001715}
Guy Benyei11169dd2012-12-18 14:30:41 +00001716
1717void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1718 // Note that we are loading an identifier.
1719 Deserializing AnIdentifier(this);
1720
1721 unsigned PriorGeneration = 0;
1722 if (getContext().getLangOpts().Modules)
1723 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001724
1725 // If there is a global index, look there first to determine which modules
1726 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001727 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001728 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001729 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001730 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1731 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001732 }
1733 }
1734
Douglas Gregor7211ac12013-01-25 23:32:03 +00001735 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001736 NumIdentifierLookups,
1737 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001738 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001739 markIdentifierUpToDate(&II);
1740}
1741
1742void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1743 if (!II)
1744 return;
1745
1746 II->setOutOfDate(false);
1747
1748 // Update the generation for this identifier.
1749 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001750 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001751}
1752
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001753void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1754 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001755 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001756
1757 BitstreamCursor &Cursor = M.MacroCursor;
1758 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001759 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001760
Richard Smith713369b2015-04-23 20:40:50 +00001761 struct ModuleMacroRecord {
1762 SubmoduleID SubModID;
1763 MacroInfo *MI;
1764 SmallVector<SubmoduleID, 8> Overrides;
1765 };
1766 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001767
Richard Smithd7329392015-04-21 21:46:32 +00001768 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1769 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1770 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001771 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001772 while (true) {
1773 llvm::BitstreamEntry Entry =
1774 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1775 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1776 Error("malformed block record in AST file");
1777 return;
1778 }
1779
1780 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001781 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001782 case PP_MACRO_DIRECTIVE_HISTORY:
1783 break;
1784
1785 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001786 ModuleMacros.push_back(ModuleMacroRecord());
1787 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001788 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1789 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001790 for (int I = 2, N = Record.size(); I != N; ++I)
1791 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001792 continue;
1793 }
1794
1795 default:
1796 Error("malformed block record in AST file");
1797 return;
1798 }
1799
1800 // We found the macro directive history; that's the last record
1801 // for this macro.
1802 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001803 }
1804
Richard Smithd7329392015-04-21 21:46:32 +00001805 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001806 {
1807 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001808 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001809 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001810 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001811 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001812 Module *Mod = getSubmodule(ModID);
1813 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001814 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001815 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001816 }
1817
1818 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001819 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001820 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001821 }
1822 }
1823
1824 // Don't read the directive history for a module; we don't have anywhere
1825 // to put it.
1826 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1827 return;
1828
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001829 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001830 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001831 unsigned Idx = 0, N = Record.size();
1832 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001833 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001834 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001835 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1836 switch (K) {
1837 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001838 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001839 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001840 break;
1841 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001842 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001843 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001844 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001845 }
1846 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001847 bool isPublic = Record[Idx++];
1848 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1849 break;
1850 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001851
1852 if (!Latest)
1853 Latest = MD;
1854 if (Earliest)
1855 Earliest->setPrevious(MD);
1856 Earliest = MD;
1857 }
1858
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001859 if (Latest)
1860 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001861}
1862
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001863ASTReader::InputFileInfo
1864ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001865 // Go find this input file.
1866 BitstreamCursor &Cursor = F.InputFilesCursor;
1867 SavedStreamPosition SavedPosition(Cursor);
1868 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1869
1870 unsigned Code = Cursor.ReadCode();
1871 RecordData Record;
1872 StringRef Blob;
1873
1874 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1875 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1876 "invalid record type for input file");
1877 (void)Result;
1878
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001879 std::string Filename;
1880 off_t StoredSize;
1881 time_t StoredTime;
1882 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001883
Ben Langmuir198c1682014-03-07 07:27:49 +00001884 assert(Record[0] == ID && "Bogus stored ID or offset");
1885 StoredSize = static_cast<off_t>(Record[1]);
1886 StoredTime = static_cast<time_t>(Record[2]);
1887 Overridden = static_cast<bool>(Record[3]);
1888 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001889 ResolveImportedPath(F, Filename);
1890
Hans Wennborg73945142014-03-14 17:45:06 +00001891 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1892 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001893}
1894
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001895InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001896 // If this ID is bogus, just return an empty input file.
1897 if (ID == 0 || ID > F.InputFilesLoaded.size())
1898 return InputFile();
1899
1900 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001901 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001902 return F.InputFilesLoaded[ID-1];
1903
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001904 if (F.InputFilesLoaded[ID-1].isNotFound())
1905 return InputFile();
1906
Guy Benyei11169dd2012-12-18 14:30:41 +00001907 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001908 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001909 SavedStreamPosition SavedPosition(Cursor);
1910 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1911
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001912 InputFileInfo FI = readInputFileInfo(F, ID);
1913 off_t StoredSize = FI.StoredSize;
1914 time_t StoredTime = FI.StoredTime;
1915 bool Overridden = FI.Overridden;
1916 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001917
Ben Langmuir198c1682014-03-07 07:27:49 +00001918 const FileEntry *File
1919 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1920 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1921
1922 // If we didn't find the file, resolve it relative to the
1923 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00001924 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00001925 F.OriginalDir != CurrentDir) {
1926 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1927 F.OriginalDir,
1928 CurrentDir);
1929 if (!Resolved.empty())
1930 File = FileMgr.getFile(Resolved);
1931 }
1932
1933 // For an overridden file, create a virtual file with the stored
1934 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00001935 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001936 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1937 }
1938
Craig Toppera13603a2014-05-22 05:54:18 +00001939 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001940 if (Complain) {
1941 std::string ErrorStr = "could not find file '";
1942 ErrorStr += Filename;
1943 ErrorStr += "' referenced by AST file";
1944 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001945 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001946 // Record that we didn't find the file.
1947 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1948 return InputFile();
1949 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001950
Ben Langmuir198c1682014-03-07 07:27:49 +00001951 // Check if there was a request to override the contents of the file
1952 // that was part of the precompiled header. Overridding such a file
1953 // can lead to problems when lexing using the source locations from the
1954 // PCH.
1955 SourceManager &SM = getSourceManager();
1956 if (!Overridden && SM.isFileOverridden(File)) {
1957 if (Complain)
1958 Error(diag::err_fe_pch_file_overridden, Filename);
1959 // After emitting the diagnostic, recover by disabling the override so
1960 // that the original file will be used.
1961 SM.disableFileContentsOverride(File);
1962 // The FileEntry is a virtual file entry with the size of the contents
1963 // that would override the original contents. Set it to the original's
1964 // size/time.
1965 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1966 StoredSize, StoredTime);
1967 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001968
Ben Langmuir198c1682014-03-07 07:27:49 +00001969 bool IsOutOfDate = false;
1970
1971 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00001972 if (!Overridden && //
1973 (StoredSize != File->getSize() ||
1974#if defined(LLVM_ON_WIN32)
1975 false
1976#else
Ben Langmuir198c1682014-03-07 07:27:49 +00001977 // In our regression testing, the Windows file system seems to
1978 // have inconsistent modification times that sometimes
1979 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00001980 //
Richard Smithe75ee0f2015-08-17 07:13:32 +00001981 // FIXME: This probably also breaks HeaderFileInfo lookups on Windows.
1982 (StoredTime && StoredTime != File->getModificationTime() &&
1983 !DisableValidation)
Guy Benyei11169dd2012-12-18 14:30:41 +00001984#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00001985 )) {
1986 if (Complain) {
1987 // Build a list of the PCH imports that got us here (in reverse).
1988 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1989 while (ImportStack.back()->ImportedBy.size() > 0)
1990 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00001991
Ben Langmuir198c1682014-03-07 07:27:49 +00001992 // The top-level PCH is stale.
1993 StringRef TopLevelPCHName(ImportStack.back()->FileName);
1994 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00001995
Ben Langmuir198c1682014-03-07 07:27:49 +00001996 // Print the import stack.
1997 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
1998 Diag(diag::note_pch_required_by)
1999 << Filename << ImportStack[0]->FileName;
2000 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002001 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002002 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002003 }
2004
Ben Langmuir198c1682014-03-07 07:27:49 +00002005 if (!Diags.isDiagnosticInFlight())
2006 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002007 }
2008
Ben Langmuir198c1682014-03-07 07:27:49 +00002009 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002010 }
2011
Ben Langmuir198c1682014-03-07 07:27:49 +00002012 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2013
2014 // Note that we've loaded this input file.
2015 F.InputFilesLoaded[ID-1] = IF;
2016 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002017}
2018
Richard Smith7ed1bc92014-12-05 22:42:13 +00002019/// \brief If we are loading a relocatable PCH or module file, and the filename
2020/// is not an absolute path, add the system or module root to the beginning of
2021/// the file name.
2022void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2023 // Resolve relative to the base directory, if we have one.
2024 if (!M.BaseDirectory.empty())
2025 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002026}
2027
Richard Smith7ed1bc92014-12-05 22:42:13 +00002028void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002029 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2030 return;
2031
Richard Smith7ed1bc92014-12-05 22:42:13 +00002032 SmallString<128> Buffer;
2033 llvm::sys::path::append(Buffer, Prefix, Filename);
2034 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002035}
2036
Richard Smith0f99d6a2015-08-09 08:48:41 +00002037static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2038 switch (ARR) {
2039 case ASTReader::Failure: return true;
2040 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2041 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2042 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2043 case ASTReader::ConfigurationMismatch:
2044 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2045 case ASTReader::HadErrors: return true;
2046 case ASTReader::Success: return false;
2047 }
2048
2049 llvm_unreachable("unknown ASTReadResult");
2050}
2051
Guy Benyei11169dd2012-12-18 14:30:41 +00002052ASTReader::ASTReadResult
2053ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002054 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002055 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002056 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002057 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002058
2059 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2060 Error("malformed block record in AST file");
2061 return Failure;
2062 }
2063
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002064 // Should we allow the configuration of the module file to differ from the
2065 // configuration of the current translation unit in a compatible way?
2066 //
2067 // FIXME: Allow this for files explicitly specified with -include-pch too.
2068 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2069
Guy Benyei11169dd2012-12-18 14:30:41 +00002070 // Read all of the records and blocks in the control block.
2071 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002072 unsigned NumInputs = 0;
2073 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002074 while (1) {
2075 llvm::BitstreamEntry Entry = Stream.advance();
2076
2077 switch (Entry.Kind) {
2078 case llvm::BitstreamEntry::Error:
2079 Error("malformed block record in AST file");
2080 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002081 case llvm::BitstreamEntry::EndBlock: {
2082 // Validate input files.
2083 const HeaderSearchOptions &HSOpts =
2084 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002085
Richard Smitha1825302014-10-23 22:18:29 +00002086 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002087 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2088 // loaded module files, ignore missing inputs.
2089 if (!DisableValidation && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002090 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002091
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002092 // If we are reading a module, we will create a verification timestamp,
2093 // so we verify all input files. Otherwise, verify only user input
2094 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002095
2096 unsigned N = NumUserInputs;
2097 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002098 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002099 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002100 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002101 N = NumInputs;
2102
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002103 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002104 InputFile IF = getInputFile(F, I+1, Complain);
2105 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002106 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002107 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002108 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002109
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002110 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002111 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002112
Ben Langmuircb69b572014-03-07 06:40:32 +00002113 if (Listener && Listener->needsInputFileVisitation()) {
2114 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2115 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002116 for (unsigned I = 0; I < N; ++I) {
2117 bool IsSystem = I >= NumUserInputs;
2118 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002119 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2120 F.Kind == MK_ExplicitModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002121 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002122 }
2123
Guy Benyei11169dd2012-12-18 14:30:41 +00002124 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002125 }
2126
Chris Lattnere7b154b2013-01-19 21:39:22 +00002127 case llvm::BitstreamEntry::SubBlock:
2128 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002129 case INPUT_FILES_BLOCK_ID:
2130 F.InputFilesCursor = Stream;
2131 if (Stream.SkipBlock() || // Skip with the main cursor
2132 // Read the abbreviations
2133 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2134 Error("malformed block record in AST file");
2135 return Failure;
2136 }
2137 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002138
Guy Benyei11169dd2012-12-18 14:30:41 +00002139 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002140 if (Stream.SkipBlock()) {
2141 Error("malformed block record in AST file");
2142 return Failure;
2143 }
2144 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002145 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002146
2147 case llvm::BitstreamEntry::Record:
2148 // The interesting case.
2149 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002150 }
2151
2152 // Read and process a record.
2153 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002154 StringRef Blob;
2155 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002156 case METADATA: {
2157 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2158 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002159 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2160 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002161 return VersionMismatch;
2162 }
2163
Richard Smithe75ee0f2015-08-17 07:13:32 +00002164 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002165 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2166 Diag(diag::err_pch_with_compiler_errors);
2167 return HadErrors;
2168 }
2169
2170 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002171 // Relative paths in a relocatable PCH are relative to our sysroot.
2172 if (F.RelocatablePCH)
2173 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002174
Richard Smithe75ee0f2015-08-17 07:13:32 +00002175 F.HasTimestamps = Record[5];
2176
Guy Benyei11169dd2012-12-18 14:30:41 +00002177 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002178 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002179 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2180 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002181 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002182 return VersionMismatch;
2183 }
2184 break;
2185 }
2186
Ben Langmuir487ea142014-10-23 18:05:36 +00002187 case SIGNATURE:
2188 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2189 F.Signature = Record[0];
2190 break;
2191
Guy Benyei11169dd2012-12-18 14:30:41 +00002192 case IMPORTS: {
2193 // Load each of the imported PCH files.
2194 unsigned Idx = 0, N = Record.size();
2195 while (Idx < N) {
2196 // Read information about the AST file.
2197 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2198 // The import location will be the local one for now; we will adjust
2199 // all import locations of module imports after the global source
2200 // location info are setup.
2201 SourceLocation ImportLoc =
2202 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002203 off_t StoredSize = (off_t)Record[Idx++];
2204 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002205 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002206 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002207
Richard Smith0f99d6a2015-08-09 08:48:41 +00002208 // If our client can't cope with us being out of date, we can't cope with
2209 // our dependency being missing.
2210 unsigned Capabilities = ClientLoadCapabilities;
2211 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2212 Capabilities &= ~ARR_Missing;
2213
Guy Benyei11169dd2012-12-18 14:30:41 +00002214 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002215 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2216 Loaded, StoredSize, StoredModTime,
2217 StoredSignature, Capabilities);
2218
2219 // If we diagnosed a problem, produce a backtrace.
2220 if (isDiagnosedResult(Result, Capabilities))
2221 Diag(diag::note_module_file_imported_by)
2222 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2223
2224 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002225 case Failure: return Failure;
2226 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002227 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002228 case OutOfDate: return OutOfDate;
2229 case VersionMismatch: return VersionMismatch;
2230 case ConfigurationMismatch: return ConfigurationMismatch;
2231 case HadErrors: return HadErrors;
2232 case Success: break;
2233 }
2234 }
2235 break;
2236 }
2237
2238 case LANGUAGE_OPTIONS: {
2239 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002240 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002241 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002242 ParseLanguageOptions(Record, Complain, *Listener,
2243 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002244 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002245 return ConfigurationMismatch;
2246 break;
2247 }
2248
2249 case TARGET_OPTIONS: {
2250 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2251 if (Listener && &F == *ModuleMgr.begin() &&
Chandler Carruth0d745bc2015-03-14 04:47:43 +00002252 ParseTargetOptions(Record, Complain, *Listener,
2253 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002254 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002255 return ConfigurationMismatch;
2256 break;
2257 }
2258
2259 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002260 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002261 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002262 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002263 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002264 !DisableValidation)
2265 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002266 break;
2267 }
2268
2269 case FILE_SYSTEM_OPTIONS: {
2270 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2271 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002272 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002273 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002274 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002275 return ConfigurationMismatch;
2276 break;
2277 }
2278
2279 case HEADER_SEARCH_OPTIONS: {
2280 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2281 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002282 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002283 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002284 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002285 return ConfigurationMismatch;
2286 break;
2287 }
2288
2289 case PREPROCESSOR_OPTIONS: {
2290 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2291 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002292 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002293 ParsePreprocessorOptions(Record, Complain, *Listener,
2294 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002295 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002296 return ConfigurationMismatch;
2297 break;
2298 }
2299
2300 case ORIGINAL_FILE:
2301 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002302 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002303 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002304 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002305 break;
2306
2307 case ORIGINAL_FILE_ID:
2308 F.OriginalSourceFileID = FileID::get(Record[0]);
2309 break;
2310
2311 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002312 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002313 break;
2314
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002315 case MODULE_NAME:
2316 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002317 if (Listener)
2318 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002319 break;
2320
Richard Smith223d3f22014-12-06 03:21:08 +00002321 case MODULE_DIRECTORY: {
2322 assert(!F.ModuleName.empty() &&
2323 "MODULE_DIRECTORY found before MODULE_NAME");
2324 // If we've already loaded a module map file covering this module, we may
2325 // have a better path for it (relative to the current build).
2326 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2327 if (M && M->Directory) {
2328 // If we're implicitly loading a module, the base directory can't
2329 // change between the build and use.
2330 if (F.Kind != MK_ExplicitModule) {
2331 const DirectoryEntry *BuildDir =
2332 PP.getFileManager().getDirectory(Blob);
2333 if (!BuildDir || BuildDir != M->Directory) {
2334 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2335 Diag(diag::err_imported_module_relocated)
2336 << F.ModuleName << Blob << M->Directory->getName();
2337 return OutOfDate;
2338 }
2339 }
2340 F.BaseDirectory = M->Directory->getName();
2341 } else {
2342 F.BaseDirectory = Blob;
2343 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002344 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002345 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002346
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002347 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002348 if (ASTReadResult Result =
2349 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2350 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002351 break;
2352
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002353 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002354 NumInputs = Record[0];
2355 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002356 F.InputFileOffsets =
2357 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002358 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002359 break;
2360 }
2361 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002362}
2363
Ben Langmuir2c9af442014-04-10 17:57:43 +00002364ASTReader::ASTReadResult
2365ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002366 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002367
2368 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2369 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002370 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 }
2372
2373 // Read all of the records and blocks for the AST file.
2374 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002375 while (1) {
2376 llvm::BitstreamEntry Entry = Stream.advance();
2377
2378 switch (Entry.Kind) {
2379 case llvm::BitstreamEntry::Error:
2380 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002381 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002382 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002383 // Outside of C++, we do not store a lookup map for the translation unit.
2384 // Instead, mark it as needing a lookup map to be built if this module
2385 // contains any declarations lexically within it (which it always does!).
2386 // This usually has no cost, since we very rarely need the lookup map for
2387 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002388 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002389 if (DC->hasExternalLexicalStorage() &&
2390 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002391 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002392
Ben Langmuir2c9af442014-04-10 17:57:43 +00002393 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002394 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002395 case llvm::BitstreamEntry::SubBlock:
2396 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002397 case DECLTYPES_BLOCK_ID:
2398 // We lazily load the decls block, but we want to set up the
2399 // DeclsCursor cursor to point into it. Clone our current bitcode
2400 // cursor to it, enter the block and read the abbrevs in that block.
2401 // With the main cursor, we just skip over it.
2402 F.DeclsCursor = Stream;
2403 if (Stream.SkipBlock() || // Skip with the main cursor.
2404 // Read the abbrevs.
2405 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2406 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002407 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002408 }
2409 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002410
Guy Benyei11169dd2012-12-18 14:30:41 +00002411 case PREPROCESSOR_BLOCK_ID:
2412 F.MacroCursor = Stream;
2413 if (!PP.getExternalSource())
2414 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002415
Guy Benyei11169dd2012-12-18 14:30:41 +00002416 if (Stream.SkipBlock() ||
2417 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2418 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002419 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002420 }
2421 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2422 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002423
Guy Benyei11169dd2012-12-18 14:30:41 +00002424 case PREPROCESSOR_DETAIL_BLOCK_ID:
2425 F.PreprocessorDetailCursor = Stream;
2426 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002427 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002428 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002429 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002430 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002431 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002432 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002433 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2434
Guy Benyei11169dd2012-12-18 14:30:41 +00002435 if (!PP.getPreprocessingRecord())
2436 PP.createPreprocessingRecord();
2437 if (!PP.getPreprocessingRecord()->getExternalSource())
2438 PP.getPreprocessingRecord()->SetExternalSource(*this);
2439 break;
2440
2441 case SOURCE_MANAGER_BLOCK_ID:
2442 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002443 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002444 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002445
Guy Benyei11169dd2012-12-18 14:30:41 +00002446 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002447 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2448 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002449 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002450
Guy Benyei11169dd2012-12-18 14:30:41 +00002451 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002452 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002453 if (Stream.SkipBlock() ||
2454 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2455 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002456 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002457 }
2458 CommentsCursors.push_back(std::make_pair(C, &F));
2459 break;
2460 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002461
Guy Benyei11169dd2012-12-18 14:30:41 +00002462 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002463 if (Stream.SkipBlock()) {
2464 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002465 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002466 }
2467 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002468 }
2469 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002470
2471 case llvm::BitstreamEntry::Record:
2472 // The interesting case.
2473 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002474 }
2475
2476 // Read and process a record.
2477 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002478 StringRef Blob;
2479 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002480 default: // Default behavior: ignore.
2481 break;
2482
2483 case TYPE_OFFSET: {
2484 if (F.LocalNumTypes != 0) {
2485 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002486 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002487 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002488 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002489 F.LocalNumTypes = Record[0];
2490 unsigned LocalBaseTypeIndex = Record[1];
2491 F.BaseTypeIndex = getTotalNumTypes();
2492
2493 if (F.LocalNumTypes > 0) {
2494 // Introduce the global -> local mapping for types within this module.
2495 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2496
2497 // Introduce the local -> global mapping for types within this module.
2498 F.TypeRemap.insertOrReplace(
2499 std::make_pair(LocalBaseTypeIndex,
2500 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002501
2502 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002503 }
2504 break;
2505 }
2506
2507 case DECL_OFFSET: {
2508 if (F.LocalNumDecls != 0) {
2509 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002510 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002511 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002512 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002513 F.LocalNumDecls = Record[0];
2514 unsigned LocalBaseDeclID = Record[1];
2515 F.BaseDeclID = getTotalNumDecls();
2516
2517 if (F.LocalNumDecls > 0) {
2518 // Introduce the global -> local mapping for declarations within this
2519 // module.
2520 GlobalDeclMap.insert(
2521 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2522
2523 // Introduce the local -> global mapping for declarations within this
2524 // module.
2525 F.DeclRemap.insertOrReplace(
2526 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2527
2528 // Introduce the global -> local mapping for declarations within this
2529 // module.
2530 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002531
Ben Langmuir52ca6782014-10-20 16:27:32 +00002532 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2533 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002534 break;
2535 }
2536
2537 case TU_UPDATE_LEXICAL: {
2538 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002539 LexicalContents Contents(
2540 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2541 Blob.data()),
2542 static_cast<unsigned int>(Blob.size() / 4));
2543 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002544 TU->setHasExternalLexicalStorage(true);
2545 break;
2546 }
2547
2548 case UPDATE_VISIBLE: {
2549 unsigned Idx = 0;
2550 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002551 auto *Data = (const unsigned char*)Blob.data();
2552 unsigned BucketOffset = Record[Idx++];
2553 PendingVisibleUpdates[ID].push_back(
2554 PendingVisibleUpdate{&F, Data, BucketOffset});
2555 // If we've already loaded the decl, perform the updates when we finish
2556 // loading this block.
2557 if (Decl *D = GetExistingDecl(ID))
2558 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002559 break;
2560 }
2561
2562 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002563 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002564 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002565 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2566 (const unsigned char *)F.IdentifierTableData + Record[0],
2567 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2568 (const unsigned char *)F.IdentifierTableData,
2569 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002570
2571 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2572 }
2573 break;
2574
2575 case IDENTIFIER_OFFSET: {
2576 if (F.LocalNumIdentifiers != 0) {
2577 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002578 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002579 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002580 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002581 F.LocalNumIdentifiers = Record[0];
2582 unsigned LocalBaseIdentifierID = Record[1];
2583 F.BaseIdentifierID = getTotalNumIdentifiers();
2584
2585 if (F.LocalNumIdentifiers > 0) {
2586 // Introduce the global -> local mapping for identifiers within this
2587 // module.
2588 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2589 &F));
2590
2591 // Introduce the local -> global mapping for identifiers within this
2592 // module.
2593 F.IdentifierRemap.insertOrReplace(
2594 std::make_pair(LocalBaseIdentifierID,
2595 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002596
Ben Langmuir52ca6782014-10-20 16:27:32 +00002597 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2598 + F.LocalNumIdentifiers);
2599 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 break;
2601 }
2602
Richard Smith33e0f7e2015-07-22 02:08:40 +00002603 case INTERESTING_IDENTIFIERS:
2604 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2605 break;
2606
Ben Langmuir332aafe2014-01-31 01:06:56 +00002607 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002608 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2609 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002610 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002611 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002612 break;
2613
2614 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002615 if (SpecialTypes.empty()) {
2616 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2617 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2618 break;
2619 }
2620
2621 if (SpecialTypes.size() != Record.size()) {
2622 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002623 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002624 }
2625
2626 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2627 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2628 if (!SpecialTypes[I])
2629 SpecialTypes[I] = ID;
2630 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2631 // merge step?
2632 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002633 break;
2634
2635 case STATISTICS:
2636 TotalNumStatements += Record[0];
2637 TotalNumMacros += Record[1];
2638 TotalLexicalDeclContexts += Record[2];
2639 TotalVisibleDeclContexts += Record[3];
2640 break;
2641
2642 case UNUSED_FILESCOPED_DECLS:
2643 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2644 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2645 break;
2646
2647 case DELEGATING_CTORS:
2648 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2649 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2650 break;
2651
2652 case WEAK_UNDECLARED_IDENTIFIERS:
2653 if (Record.size() % 4 != 0) {
2654 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002655 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002656 }
2657
2658 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2659 // files. This isn't the way to do it :)
2660 WeakUndeclaredIdentifiers.clear();
2661
2662 // Translate the weak, undeclared identifiers into global IDs.
2663 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2664 WeakUndeclaredIdentifiers.push_back(
2665 getGlobalIdentifierID(F, Record[I++]));
2666 WeakUndeclaredIdentifiers.push_back(
2667 getGlobalIdentifierID(F, Record[I++]));
2668 WeakUndeclaredIdentifiers.push_back(
2669 ReadSourceLocation(F, Record, I).getRawEncoding());
2670 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2671 }
2672 break;
2673
Guy Benyei11169dd2012-12-18 14:30:41 +00002674 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002675 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002676 F.LocalNumSelectors = Record[0];
2677 unsigned LocalBaseSelectorID = Record[1];
2678 F.BaseSelectorID = getTotalNumSelectors();
2679
2680 if (F.LocalNumSelectors > 0) {
2681 // Introduce the global -> local mapping for selectors within this
2682 // module.
2683 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2684
2685 // Introduce the local -> global mapping for selectors within this
2686 // module.
2687 F.SelectorRemap.insertOrReplace(
2688 std::make_pair(LocalBaseSelectorID,
2689 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002690
2691 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002692 }
2693 break;
2694 }
2695
2696 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002697 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002698 if (Record[0])
2699 F.SelectorLookupTable
2700 = ASTSelectorLookupTable::Create(
2701 F.SelectorLookupTableData + Record[0],
2702 F.SelectorLookupTableData,
2703 ASTSelectorLookupTrait(*this, F));
2704 TotalNumMethodPoolEntries += Record[1];
2705 break;
2706
2707 case REFERENCED_SELECTOR_POOL:
2708 if (!Record.empty()) {
2709 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2710 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2711 Record[Idx++]));
2712 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2713 getRawEncoding());
2714 }
2715 }
2716 break;
2717
2718 case PP_COUNTER_VALUE:
2719 if (!Record.empty() && Listener)
2720 Listener->ReadCounter(F, Record[0]);
2721 break;
2722
2723 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002724 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002725 F.NumFileSortedDecls = Record[0];
2726 break;
2727
2728 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002729 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002730 F.LocalNumSLocEntries = Record[0];
2731 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002732 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002733 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002734 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002735 if (!F.SLocEntryBaseID) {
2736 Error("ran out of source locations");
2737 break;
2738 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002739 // Make our entry in the range map. BaseID is negative and growing, so
2740 // we invert it. Because we invert it, though, we need the other end of
2741 // the range.
2742 unsigned RangeStart =
2743 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2744 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2745 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2746
2747 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2748 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2749 GlobalSLocOffsetMap.insert(
2750 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2751 - SLocSpaceSize,&F));
2752
2753 // Initialize the remapping table.
2754 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002755 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002756 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002757 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002758 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2759
2760 TotalNumSLocEntries += F.LocalNumSLocEntries;
2761 break;
2762 }
2763
2764 case MODULE_OFFSET_MAP: {
2765 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002766 const unsigned char *Data = (const unsigned char*)Blob.data();
2767 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002768
2769 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2770 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2771 F.SLocRemap.insert(std::make_pair(0U, 0));
2772 F.SLocRemap.insert(std::make_pair(2U, 1));
2773 }
2774
Guy Benyei11169dd2012-12-18 14:30:41 +00002775 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002776 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2777 RemapBuilder;
2778 RemapBuilder SLocRemap(F.SLocRemap);
2779 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2780 RemapBuilder MacroRemap(F.MacroRemap);
2781 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2782 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2783 RemapBuilder SelectorRemap(F.SelectorRemap);
2784 RemapBuilder DeclRemap(F.DeclRemap);
2785 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002786
2787 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002788 using namespace llvm::support;
2789 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002790 StringRef Name = StringRef((const char*)Data, Len);
2791 Data += Len;
2792 ModuleFile *OM = ModuleMgr.lookup(Name);
2793 if (!OM) {
2794 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002795 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002796 }
2797
Justin Bogner57ba0b22014-03-28 22:03:24 +00002798 uint32_t SLocOffset =
2799 endian::readNext<uint32_t, little, unaligned>(Data);
2800 uint32_t IdentifierIDOffset =
2801 endian::readNext<uint32_t, little, unaligned>(Data);
2802 uint32_t MacroIDOffset =
2803 endian::readNext<uint32_t, little, unaligned>(Data);
2804 uint32_t PreprocessedEntityIDOffset =
2805 endian::readNext<uint32_t, little, unaligned>(Data);
2806 uint32_t SubmoduleIDOffset =
2807 endian::readNext<uint32_t, little, unaligned>(Data);
2808 uint32_t SelectorIDOffset =
2809 endian::readNext<uint32_t, little, unaligned>(Data);
2810 uint32_t DeclIDOffset =
2811 endian::readNext<uint32_t, little, unaligned>(Data);
2812 uint32_t TypeIndexOffset =
2813 endian::readNext<uint32_t, little, unaligned>(Data);
2814
Ben Langmuir785180e2014-10-20 16:27:30 +00002815 uint32_t None = std::numeric_limits<uint32_t>::max();
2816
2817 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2818 RemapBuilder &Remap) {
2819 if (Offset != None)
2820 Remap.insert(std::make_pair(Offset,
2821 static_cast<int>(BaseOffset - Offset)));
2822 };
2823 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2824 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2825 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2826 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2827 PreprocessedEntityRemap);
2828 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2829 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2830 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2831 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002832
2833 // Global -> local mappings.
2834 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2835 }
2836 break;
2837 }
2838
2839 case SOURCE_MANAGER_LINE_TABLE:
2840 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002841 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002842 break;
2843
2844 case SOURCE_LOCATION_PRELOADS: {
2845 // Need to transform from the local view (1-based IDs) to the global view,
2846 // which is based off F.SLocEntryBaseID.
2847 if (!F.PreloadSLocEntries.empty()) {
2848 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002849 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002850 }
2851
2852 F.PreloadSLocEntries.swap(Record);
2853 break;
2854 }
2855
2856 case EXT_VECTOR_DECLS:
2857 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2858 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2859 break;
2860
2861 case VTABLE_USES:
2862 if (Record.size() % 3 != 0) {
2863 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002864 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002865 }
2866
2867 // Later tables overwrite earlier ones.
2868 // FIXME: Modules will have some trouble with this. This is clearly not
2869 // the right way to do this.
2870 VTableUses.clear();
2871
2872 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2873 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2874 VTableUses.push_back(
2875 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2876 VTableUses.push_back(Record[Idx++]);
2877 }
2878 break;
2879
Guy Benyei11169dd2012-12-18 14:30:41 +00002880 case PENDING_IMPLICIT_INSTANTIATIONS:
2881 if (PendingInstantiations.size() % 2 != 0) {
2882 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002883 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002884 }
2885
2886 if (Record.size() % 2 != 0) {
2887 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002888 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002889 }
2890
2891 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2892 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2893 PendingInstantiations.push_back(
2894 ReadSourceLocation(F, Record, I).getRawEncoding());
2895 }
2896 break;
2897
2898 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002899 if (Record.size() != 2) {
2900 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002901 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002902 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002903 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2904 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2905 break;
2906
2907 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002908 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2909 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2910 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002911
2912 unsigned LocalBasePreprocessedEntityID = Record[0];
2913
2914 unsigned StartingID;
2915 if (!PP.getPreprocessingRecord())
2916 PP.createPreprocessingRecord();
2917 if (!PP.getPreprocessingRecord()->getExternalSource())
2918 PP.getPreprocessingRecord()->SetExternalSource(*this);
2919 StartingID
2920 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00002921 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00002922 F.BasePreprocessedEntityID = StartingID;
2923
2924 if (F.NumPreprocessedEntities > 0) {
2925 // Introduce the global -> local mapping for preprocessed entities in
2926 // this module.
2927 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2928
2929 // Introduce the local -> global mapping for preprocessed entities in
2930 // this module.
2931 F.PreprocessedEntityRemap.insertOrReplace(
2932 std::make_pair(LocalBasePreprocessedEntityID,
2933 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2934 }
2935
2936 break;
2937 }
2938
2939 case DECL_UPDATE_OFFSETS: {
2940 if (Record.size() % 2 != 0) {
2941 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002942 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002943 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00002944 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
2945 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
2946 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
2947
2948 // If we've already loaded the decl, perform the updates when we finish
2949 // loading this block.
2950 if (Decl *D = GetExistingDecl(ID))
2951 PendingUpdateRecords.push_back(std::make_pair(ID, D));
2952 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002953 break;
2954 }
2955
2956 case DECL_REPLACEMENTS: {
2957 if (Record.size() % 3 != 0) {
2958 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002959 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002960 }
2961 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2962 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2963 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2964 break;
2965 }
2966
2967 case OBJC_CATEGORIES_MAP: {
2968 if (F.LocalNumObjCCategoriesInMap != 0) {
2969 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002970 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002971 }
2972
2973 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002974 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002975 break;
2976 }
2977
2978 case OBJC_CATEGORIES:
2979 F.ObjCCategories.swap(Record);
2980 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00002981
Guy Benyei11169dd2012-12-18 14:30:41 +00002982 case CXX_BASE_SPECIFIER_OFFSETS: {
2983 if (F.LocalNumCXXBaseSpecifiers != 0) {
2984 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002985 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002986 }
Richard Smithc2bb8182015-03-24 06:36:48 +00002987
Guy Benyei11169dd2012-12-18 14:30:41 +00002988 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002989 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00002990 break;
2991 }
2992
2993 case CXX_CTOR_INITIALIZERS_OFFSETS: {
2994 if (F.LocalNumCXXCtorInitializers != 0) {
2995 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
2996 return Failure;
2997 }
2998
2999 F.LocalNumCXXCtorInitializers = Record[0];
3000 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003001 break;
3002 }
3003
3004 case DIAG_PRAGMA_MAPPINGS:
3005 if (F.PragmaDiagMappings.empty())
3006 F.PragmaDiagMappings.swap(Record);
3007 else
3008 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3009 Record.begin(), Record.end());
3010 break;
3011
3012 case CUDA_SPECIAL_DECL_REFS:
3013 // Later tables overwrite earlier ones.
3014 // FIXME: Modules will have trouble with this.
3015 CUDASpecialDeclRefs.clear();
3016 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3017 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3018 break;
3019
3020 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003021 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003022 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003023 if (Record[0]) {
3024 F.HeaderFileInfoTable
3025 = HeaderFileInfoLookupTable::Create(
3026 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3027 (const unsigned char *)F.HeaderFileInfoTableData,
3028 HeaderFileInfoTrait(*this, F,
3029 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003030 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003031
3032 PP.getHeaderSearchInfo().SetExternalSource(this);
3033 if (!PP.getHeaderSearchInfo().getExternalLookup())
3034 PP.getHeaderSearchInfo().SetExternalLookup(this);
3035 }
3036 break;
3037 }
3038
3039 case FP_PRAGMA_OPTIONS:
3040 // Later tables overwrite earlier ones.
3041 FPPragmaOptions.swap(Record);
3042 break;
3043
3044 case OPENCL_EXTENSIONS:
3045 // Later tables overwrite earlier ones.
3046 OpenCLExtensions.swap(Record);
3047 break;
3048
3049 case TENTATIVE_DEFINITIONS:
3050 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3051 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3052 break;
3053
3054 case KNOWN_NAMESPACES:
3055 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3056 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3057 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003058
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003059 case UNDEFINED_BUT_USED:
3060 if (UndefinedButUsed.size() % 2 != 0) {
3061 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003062 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003063 }
3064
3065 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003066 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003067 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003068 }
3069 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003070 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3071 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003072 ReadSourceLocation(F, Record, I).getRawEncoding());
3073 }
3074 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003075 case DELETE_EXPRS_TO_ANALYZE:
3076 for (unsigned I = 0, N = Record.size(); I != N;) {
3077 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3078 const uint64_t Count = Record[I++];
3079 DelayedDeleteExprs.push_back(Count);
3080 for (uint64_t C = 0; C < Count; ++C) {
3081 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3082 bool IsArrayForm = Record[I++] == 1;
3083 DelayedDeleteExprs.push_back(IsArrayForm);
3084 }
3085 }
3086 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003087
Guy Benyei11169dd2012-12-18 14:30:41 +00003088 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003089 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003090 // If we aren't loading a module (which has its own exports), make
3091 // all of the imported modules visible.
3092 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003093 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3094 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3095 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3096 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003097 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003098 }
3099 }
3100 break;
3101 }
3102
3103 case LOCAL_REDECLARATIONS: {
3104 F.RedeclarationChains.swap(Record);
3105 break;
3106 }
3107
3108 case LOCAL_REDECLARATIONS_MAP: {
3109 if (F.LocalNumRedeclarationsInMap != 0) {
3110 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003111 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003112 }
3113
3114 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003115 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003116 break;
3117 }
3118
Guy Benyei11169dd2012-12-18 14:30:41 +00003119 case MACRO_OFFSET: {
3120 if (F.LocalNumMacros != 0) {
3121 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003122 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003123 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003124 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003125 F.LocalNumMacros = Record[0];
3126 unsigned LocalBaseMacroID = Record[1];
3127 F.BaseMacroID = getTotalNumMacros();
3128
3129 if (F.LocalNumMacros > 0) {
3130 // Introduce the global -> local mapping for macros within this module.
3131 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3132
3133 // Introduce the local -> global mapping for macros within this module.
3134 F.MacroRemap.insertOrReplace(
3135 std::make_pair(LocalBaseMacroID,
3136 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003137
3138 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003139 }
3140 break;
3141 }
3142
Richard Smithe40f2ba2013-08-07 21:41:30 +00003143 case LATE_PARSED_TEMPLATE: {
3144 LateParsedTemplates.append(Record.begin(), Record.end());
3145 break;
3146 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003147
3148 case OPTIMIZE_PRAGMA_OPTIONS:
3149 if (Record.size() != 1) {
3150 Error("invalid pragma optimize record");
3151 return Failure;
3152 }
3153 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3154 break;
Nico Weber72889432014-09-06 01:25:55 +00003155
3156 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3157 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3158 UnusedLocalTypedefNameCandidates.push_back(
3159 getGlobalDeclID(F, Record[I]));
3160 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003161 }
3162 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003163}
3164
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003165ASTReader::ASTReadResult
3166ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3167 const ModuleFile *ImportedBy,
3168 unsigned ClientLoadCapabilities) {
3169 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003170 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003171
Richard Smithe842a472014-10-22 02:05:46 +00003172 if (F.Kind == MK_ExplicitModule) {
3173 // For an explicitly-loaded module, we don't care whether the original
3174 // module map file exists or matches.
3175 return Success;
3176 }
3177
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003178 // Try to resolve ModuleName in the current header search context and
3179 // verify that it is found in the same module map file as we saved. If the
3180 // top-level AST file is a main file, skip this check because there is no
3181 // usable header search context.
3182 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003183 "MODULE_NAME should come before MODULE_MAP_FILE");
3184 if (F.Kind == MK_ImplicitModule &&
3185 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3186 // An implicitly-loaded module file should have its module listed in some
3187 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003188 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003189 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3190 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3191 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003192 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003193 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3194 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3195 // This module was defined by an imported (explicit) module.
3196 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3197 << ASTFE->getName();
3198 else
3199 // This module was built with a different module map.
3200 Diag(diag::err_imported_module_not_found)
3201 << F.ModuleName << F.FileName << ImportedBy->FileName
3202 << F.ModuleMapPath;
3203 }
3204 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003205 }
3206
Richard Smithe842a472014-10-22 02:05:46 +00003207 assert(M->Name == F.ModuleName && "found module with different name");
3208
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003209 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003210 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003211 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3212 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003213 assert(ImportedBy && "top-level import should be verified");
3214 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3215 Diag(diag::err_imported_module_modmap_changed)
3216 << F.ModuleName << ImportedBy->FileName
3217 << ModMap->getName() << F.ModuleMapPath;
3218 return OutOfDate;
3219 }
3220
3221 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3222 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3223 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003224 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003225 const FileEntry *F =
3226 FileMgr.getFile(Filename, false, false);
3227 if (F == nullptr) {
3228 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3229 Error("could not find file '" + Filename +"' referenced by AST file");
3230 return OutOfDate;
3231 }
3232 AdditionalStoredMaps.insert(F);
3233 }
3234
3235 // Check any additional module map files (e.g. module.private.modulemap)
3236 // that are not in the pcm.
3237 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3238 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3239 // Remove files that match
3240 // Note: SmallPtrSet::erase is really remove
3241 if (!AdditionalStoredMaps.erase(ModMap)) {
3242 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3243 Diag(diag::err_module_different_modmap)
3244 << F.ModuleName << /*new*/0 << ModMap->getName();
3245 return OutOfDate;
3246 }
3247 }
3248 }
3249
3250 // Check any additional module map files that are in the pcm, but not
3251 // found in header search. Cases that match are already removed.
3252 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3253 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3254 Diag(diag::err_module_different_modmap)
3255 << F.ModuleName << /*not new*/1 << ModMap->getName();
3256 return OutOfDate;
3257 }
3258 }
3259
3260 if (Listener)
3261 Listener->ReadModuleMapFile(F.ModuleMapPath);
3262 return Success;
3263}
3264
3265
Douglas Gregorc1489562013-02-12 23:36:21 +00003266/// \brief Move the given method to the back of the global list of methods.
3267static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3268 // Find the entry for this selector in the method pool.
3269 Sema::GlobalMethodPool::iterator Known
3270 = S.MethodPool.find(Method->getSelector());
3271 if (Known == S.MethodPool.end())
3272 return;
3273
3274 // Retrieve the appropriate method list.
3275 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3276 : Known->second.second;
3277 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003278 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003279 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003280 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003281 Found = true;
3282 } else {
3283 // Keep searching.
3284 continue;
3285 }
3286 }
3287
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003288 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003289 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003290 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003291 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003292 }
3293}
3294
Richard Smithde711422015-04-23 21:20:19 +00003295void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003296 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003297 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003298 bool wasHidden = D->Hidden;
3299 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003300
Richard Smith49f906a2014-03-01 00:08:04 +00003301 if (wasHidden && SemaObj) {
3302 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3303 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003304 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003305 }
3306 }
3307}
3308
Richard Smith49f906a2014-03-01 00:08:04 +00003309void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003310 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003311 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003312 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003313 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003314 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003315 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003316 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003317
3318 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003319 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003320 // there is nothing more to do.
3321 continue;
3322 }
Richard Smith49f906a2014-03-01 00:08:04 +00003323
Guy Benyei11169dd2012-12-18 14:30:41 +00003324 if (!Mod->isAvailable()) {
3325 // Modules that aren't available cannot be made visible.
3326 continue;
3327 }
3328
3329 // Update the module's name visibility.
3330 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003331
Guy Benyei11169dd2012-12-18 14:30:41 +00003332 // If we've already deserialized any names from this module,
3333 // mark them as visible.
3334 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3335 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003336 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003337 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003338 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003339 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3340 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003341 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003342
Guy Benyei11169dd2012-12-18 14:30:41 +00003343 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003344 SmallVector<Module *, 16> Exports;
3345 Mod->getExportedModules(Exports);
3346 for (SmallVectorImpl<Module *>::iterator
3347 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3348 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003349 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003350 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003351 }
3352 }
3353}
3354
Douglas Gregore060e572013-01-25 01:03:03 +00003355bool ASTReader::loadGlobalIndex() {
3356 if (GlobalIndex)
3357 return false;
3358
3359 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3360 !Context.getLangOpts().Modules)
3361 return true;
3362
3363 // Try to load the global index.
3364 TriedLoadingGlobalIndex = true;
3365 StringRef ModuleCachePath
3366 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3367 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003368 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003369 if (!Result.first)
3370 return true;
3371
3372 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003373 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003374 return false;
3375}
3376
3377bool ASTReader::isGlobalIndexUnavailable() const {
3378 return Context.getLangOpts().Modules && UseGlobalIndex &&
3379 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3380}
3381
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003382static void updateModuleTimestamp(ModuleFile &MF) {
3383 // Overwrite the timestamp file contents so that file's mtime changes.
3384 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003385 std::error_code EC;
3386 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3387 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003388 return;
3389 OS << "Timestamp file\n";
3390}
3391
Guy Benyei11169dd2012-12-18 14:30:41 +00003392ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3393 ModuleKind Type,
3394 SourceLocation ImportLoc,
3395 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003396 llvm::SaveAndRestore<SourceLocation>
3397 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3398
Richard Smithd1c46742014-04-30 02:24:17 +00003399 // Defer any pending actions until we get to the end of reading the AST file.
3400 Deserializing AnASTFile(this);
3401
Guy Benyei11169dd2012-12-18 14:30:41 +00003402 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003403 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003404
3405 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003406 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003407 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003408 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003409 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003410 ClientLoadCapabilities)) {
3411 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003412 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003413 case OutOfDate:
3414 case VersionMismatch:
3415 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003416 case HadErrors: {
3417 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3418 for (const ImportedModule &IM : Loaded)
3419 LoadedSet.insert(IM.Mod);
3420
Douglas Gregor7029ce12013-03-19 00:28:20 +00003421 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003422 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003423 Context.getLangOpts().Modules
3424 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003425 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003426
3427 // If we find that any modules are unusable, the global index is going
3428 // to be out-of-date. Just remove it.
3429 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003430 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003431 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003432 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003433 case Success:
3434 break;
3435 }
3436
3437 // Here comes stuff that we only do once the entire chain is loaded.
3438
3439 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003440 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3441 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003442 M != MEnd; ++M) {
3443 ModuleFile &F = *M->Mod;
3444
3445 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003446 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3447 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003448
3449 // Once read, set the ModuleFile bit base offset and update the size in
3450 // bits of all files we've seen.
3451 F.GlobalBitOffset = TotalModulesSizeInBits;
3452 TotalModulesSizeInBits += F.SizeInBits;
3453 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3454
3455 // Preload SLocEntries.
3456 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3457 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3458 // Load it through the SourceManager and don't call ReadSLocEntry()
3459 // directly because the entry may have already been loaded in which case
3460 // calling ReadSLocEntry() directly would trigger an assertion in
3461 // SourceManager.
3462 SourceMgr.getLoadedSLocEntryByID(Index);
3463 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003464
3465 // Preload all the pending interesting identifiers by marking them out of
3466 // date.
3467 for (auto Offset : F.PreloadIdentifierOffsets) {
3468 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3469 F.IdentifierTableData + Offset);
3470
3471 ASTIdentifierLookupTrait Trait(*this, F);
3472 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3473 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
3474 PP.getIdentifierTable().getOwn(Key).setOutOfDate(true);
3475 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003476 }
3477
Douglas Gregor603cd862013-03-22 18:50:14 +00003478 // Setup the import locations and notify the module manager that we've
3479 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003480 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3481 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003482 M != MEnd; ++M) {
3483 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003484
3485 ModuleMgr.moduleFileAccepted(&F);
3486
3487 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003488 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003489 if (!M->ImportedBy)
3490 F.ImportLoc = M->ImportLoc;
3491 else
3492 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3493 M->ImportLoc.getRawEncoding());
3494 }
3495
Richard Smith33e0f7e2015-07-22 02:08:40 +00003496 if (!Context.getLangOpts().CPlusPlus ||
3497 (Type != MK_ImplicitModule && Type != MK_ExplicitModule)) {
3498 // Mark all of the identifiers in the identifier table as being out of date,
3499 // so that various accessors know to check the loaded modules when the
3500 // identifier is used.
3501 //
3502 // For C++ modules, we don't need information on many identifiers (just
3503 // those that provide macros or are poisoned), so we mark all of
3504 // the interesting ones via PreloadIdentifierOffsets.
3505 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3506 IdEnd = PP.getIdentifierTable().end();
3507 Id != IdEnd; ++Id)
3508 Id->second->setOutOfDate(true);
3509 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003510
3511 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003512 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3513 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003514 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3515 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003516
3517 switch (Unresolved.Kind) {
3518 case UnresolvedModuleRef::Conflict:
3519 if (ResolvedMod) {
3520 Module::Conflict Conflict;
3521 Conflict.Other = ResolvedMod;
3522 Conflict.Message = Unresolved.String.str();
3523 Unresolved.Mod->Conflicts.push_back(Conflict);
3524 }
3525 continue;
3526
3527 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003528 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003529 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003530 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003531
Douglas Gregorfb912652013-03-20 21:10:35 +00003532 case UnresolvedModuleRef::Export:
3533 if (ResolvedMod || Unresolved.IsWildcard)
3534 Unresolved.Mod->Exports.push_back(
3535 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3536 continue;
3537 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003538 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003539 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003540
3541 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3542 // Might be unnecessary as use declarations are only used to build the
3543 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003544
3545 InitializeContext();
3546
Richard Smith3d8e97e2013-10-18 06:54:39 +00003547 if (SemaObj)
3548 UpdateSema();
3549
Guy Benyei11169dd2012-12-18 14:30:41 +00003550 if (DeserializationListener)
3551 DeserializationListener->ReaderInitialized(this);
3552
3553 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3554 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3555 PrimaryModule.OriginalSourceFileID
3556 = FileID::get(PrimaryModule.SLocEntryBaseID
3557 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3558
3559 // If this AST file is a precompiled preamble, then set the
3560 // preamble file ID of the source manager to the file source file
3561 // from which the preamble was built.
3562 if (Type == MK_Preamble) {
3563 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3564 } else if (Type == MK_MainFile) {
3565 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3566 }
3567 }
3568
3569 // For any Objective-C class definitions we have already loaded, make sure
3570 // that we load any additional categories.
3571 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3572 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3573 ObjCClassesLoaded[I],
3574 PreviousGeneration);
3575 }
Douglas Gregore060e572013-01-25 01:03:03 +00003576
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003577 if (PP.getHeaderSearchInfo()
3578 .getHeaderSearchOpts()
3579 .ModulesValidateOncePerBuildSession) {
3580 // Now we are certain that the module and all modules it depends on are
3581 // up to date. Create or update timestamp files for modules that are
3582 // located in the module cache (not for PCH files that could be anywhere
3583 // in the filesystem).
3584 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3585 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003586 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003587 updateModuleTimestamp(*M.Mod);
3588 }
3589 }
3590 }
3591
Guy Benyei11169dd2012-12-18 14:30:41 +00003592 return Success;
3593}
3594
Ben Langmuir487ea142014-10-23 18:05:36 +00003595static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3596
Ben Langmuir70a1b812015-03-24 04:43:52 +00003597/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3598static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3599 return Stream.Read(8) == 'C' &&
3600 Stream.Read(8) == 'P' &&
3601 Stream.Read(8) == 'C' &&
3602 Stream.Read(8) == 'H';
3603}
3604
Richard Smith0f99d6a2015-08-09 08:48:41 +00003605static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3606 switch (Kind) {
3607 case MK_PCH:
3608 return 0; // PCH
3609 case MK_ImplicitModule:
3610 case MK_ExplicitModule:
3611 return 1; // module
3612 case MK_MainFile:
3613 case MK_Preamble:
3614 return 2; // main source file
3615 }
3616 llvm_unreachable("unknown module kind");
3617}
3618
Guy Benyei11169dd2012-12-18 14:30:41 +00003619ASTReader::ASTReadResult
3620ASTReader::ReadASTCore(StringRef FileName,
3621 ModuleKind Type,
3622 SourceLocation ImportLoc,
3623 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003624 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003625 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003626 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003627 unsigned ClientLoadCapabilities) {
3628 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003629 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003630 ModuleManager::AddModuleResult AddResult
3631 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003632 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003633 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003634 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003635
Douglas Gregor7029ce12013-03-19 00:28:20 +00003636 switch (AddResult) {
3637 case ModuleManager::AlreadyLoaded:
3638 return Success;
3639
3640 case ModuleManager::NewlyLoaded:
3641 // Load module file below.
3642 break;
3643
3644 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003645 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003646 // it.
3647 if (ClientLoadCapabilities & ARR_Missing)
3648 return Missing;
3649
3650 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003651 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
3652 << FileName << ErrorStr.empty()
3653 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003654 return Failure;
3655
3656 case ModuleManager::OutOfDate:
3657 // We couldn't load the module file because it is out-of-date. If the
3658 // client can handle out-of-date, return it.
3659 if (ClientLoadCapabilities & ARR_OutOfDate)
3660 return OutOfDate;
3661
3662 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003663 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
3664 << FileName << ErrorStr.empty()
3665 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003666 return Failure;
3667 }
3668
Douglas Gregor7029ce12013-03-19 00:28:20 +00003669 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003670
3671 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3672 // module?
3673 if (FileName != "-") {
3674 CurrentDir = llvm::sys::path::parent_path(FileName);
3675 if (CurrentDir.empty()) CurrentDir = ".";
3676 }
3677
3678 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003679 BitstreamCursor &Stream = F.Stream;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003680 PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003681 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003682 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3683
Guy Benyei11169dd2012-12-18 14:30:41 +00003684 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003685 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003686 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3687 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003688 return Failure;
3689 }
3690
3691 // This is used for compatibility with older PCH formats.
3692 bool HaveReadControlBlock = false;
3693
Chris Lattnerefa77172013-01-20 00:00:22 +00003694 while (1) {
3695 llvm::BitstreamEntry Entry = Stream.advance();
3696
3697 switch (Entry.Kind) {
3698 case llvm::BitstreamEntry::Error:
3699 case llvm::BitstreamEntry::EndBlock:
3700 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003701 Error("invalid record at top-level of AST file");
3702 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003703
3704 case llvm::BitstreamEntry::SubBlock:
3705 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003706 }
3707
Guy Benyei11169dd2012-12-18 14:30:41 +00003708 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003709 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003710 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3711 if (Stream.ReadBlockInfoBlock()) {
3712 Error("malformed BlockInfoBlock in AST file");
3713 return Failure;
3714 }
3715 break;
3716 case CONTROL_BLOCK_ID:
3717 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003718 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003719 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003720 // Check that we didn't try to load a non-module AST file as a module.
3721 //
3722 // FIXME: Should we also perform the converse check? Loading a module as
3723 // a PCH file sort of works, but it's a bit wonky.
3724 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule) &&
3725 F.ModuleName.empty()) {
3726 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3727 if (Result != OutOfDate ||
3728 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3729 Diag(diag::err_module_file_not_module) << FileName;
3730 return Result;
3731 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003732 break;
3733
3734 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003735 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003736 case OutOfDate: return OutOfDate;
3737 case VersionMismatch: return VersionMismatch;
3738 case ConfigurationMismatch: return ConfigurationMismatch;
3739 case HadErrors: return HadErrors;
3740 }
3741 break;
3742 case AST_BLOCK_ID:
3743 if (!HaveReadControlBlock) {
3744 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003745 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003746 return VersionMismatch;
3747 }
3748
3749 // Record that we've loaded this module.
3750 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3751 return Success;
3752
3753 default:
3754 if (Stream.SkipBlock()) {
3755 Error("malformed block record in AST file");
3756 return Failure;
3757 }
3758 break;
3759 }
3760 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003761}
3762
Richard Smitha7e2cc62015-05-01 01:53:09 +00003763void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003764 // If there's a listener, notify them that we "read" the translation unit.
3765 if (DeserializationListener)
3766 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3767 Context.getTranslationUnitDecl());
3768
Guy Benyei11169dd2012-12-18 14:30:41 +00003769 // FIXME: Find a better way to deal with collisions between these
3770 // built-in types. Right now, we just ignore the problem.
3771
3772 // Load the special types.
3773 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3774 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3775 if (!Context.CFConstantStringTypeDecl)
3776 Context.setCFConstantStringType(GetType(String));
3777 }
3778
3779 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3780 QualType FileType = GetType(File);
3781 if (FileType.isNull()) {
3782 Error("FILE type is NULL");
3783 return;
3784 }
3785
3786 if (!Context.FILEDecl) {
3787 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3788 Context.setFILEDecl(Typedef->getDecl());
3789 else {
3790 const TagType *Tag = FileType->getAs<TagType>();
3791 if (!Tag) {
3792 Error("Invalid FILE type in AST file");
3793 return;
3794 }
3795 Context.setFILEDecl(Tag->getDecl());
3796 }
3797 }
3798 }
3799
3800 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3801 QualType Jmp_bufType = GetType(Jmp_buf);
3802 if (Jmp_bufType.isNull()) {
3803 Error("jmp_buf type is NULL");
3804 return;
3805 }
3806
3807 if (!Context.jmp_bufDecl) {
3808 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3809 Context.setjmp_bufDecl(Typedef->getDecl());
3810 else {
3811 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3812 if (!Tag) {
3813 Error("Invalid jmp_buf type in AST file");
3814 return;
3815 }
3816 Context.setjmp_bufDecl(Tag->getDecl());
3817 }
3818 }
3819 }
3820
3821 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3822 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3823 if (Sigjmp_bufType.isNull()) {
3824 Error("sigjmp_buf type is NULL");
3825 return;
3826 }
3827
3828 if (!Context.sigjmp_bufDecl) {
3829 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3830 Context.setsigjmp_bufDecl(Typedef->getDecl());
3831 else {
3832 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3833 assert(Tag && "Invalid sigjmp_buf type in AST file");
3834 Context.setsigjmp_bufDecl(Tag->getDecl());
3835 }
3836 }
3837 }
3838
3839 if (unsigned ObjCIdRedef
3840 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3841 if (Context.ObjCIdRedefinitionType.isNull())
3842 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3843 }
3844
3845 if (unsigned ObjCClassRedef
3846 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3847 if (Context.ObjCClassRedefinitionType.isNull())
3848 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3849 }
3850
3851 if (unsigned ObjCSelRedef
3852 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3853 if (Context.ObjCSelRedefinitionType.isNull())
3854 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3855 }
3856
3857 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3858 QualType Ucontext_tType = GetType(Ucontext_t);
3859 if (Ucontext_tType.isNull()) {
3860 Error("ucontext_t type is NULL");
3861 return;
3862 }
3863
3864 if (!Context.ucontext_tDecl) {
3865 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3866 Context.setucontext_tDecl(Typedef->getDecl());
3867 else {
3868 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3869 assert(Tag && "Invalid ucontext_t type in AST file");
3870 Context.setucontext_tDecl(Tag->getDecl());
3871 }
3872 }
3873 }
3874 }
3875
3876 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3877
3878 // If there were any CUDA special declarations, deserialize them.
3879 if (!CUDASpecialDeclRefs.empty()) {
3880 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3881 Context.setcudaConfigureCallDecl(
3882 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3883 }
Richard Smith56be7542014-03-21 00:33:59 +00003884
Guy Benyei11169dd2012-12-18 14:30:41 +00003885 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00003886 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00003887 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00003888 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003889 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003890 /*ImportLoc=*/Import.ImportLoc);
3891 PP.makeModuleVisible(Imported, Import.ImportLoc);
3892 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003893 }
3894 ImportedModules.clear();
3895}
3896
3897void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00003898 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00003899}
3900
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003901/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3902/// cursor into the start of the given block ID, returning false on success and
3903/// true on failure.
3904static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003905 while (1) {
3906 llvm::BitstreamEntry Entry = Cursor.advance();
3907 switch (Entry.Kind) {
3908 case llvm::BitstreamEntry::Error:
3909 case llvm::BitstreamEntry::EndBlock:
3910 return true;
3911
3912 case llvm::BitstreamEntry::Record:
3913 // Ignore top-level records.
3914 Cursor.skipRecord(Entry.ID);
3915 break;
3916
3917 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003918 if (Entry.ID == BlockID) {
3919 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003920 return true;
3921 // Found it!
3922 return false;
3923 }
3924
3925 if (Cursor.SkipBlock())
3926 return true;
3927 }
3928 }
3929}
3930
Ben Langmuir70a1b812015-03-24 04:43:52 +00003931/// \brief Reads and return the signature record from \p StreamFile's control
3932/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00003933static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
3934 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00003935 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00003936 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00003937
3938 // Scan for the CONTROL_BLOCK_ID block.
3939 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
3940 return 0;
3941
3942 // Scan for SIGNATURE inside the control block.
3943 ASTReader::RecordData Record;
3944 while (1) {
3945 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3946 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
3947 Entry.Kind != llvm::BitstreamEntry::Record)
3948 return 0;
3949
3950 Record.clear();
3951 StringRef Blob;
3952 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
3953 return Record[0];
3954 }
3955}
3956
Guy Benyei11169dd2012-12-18 14:30:41 +00003957/// \brief Retrieve the name of the original source file name
3958/// directly from the AST file, without actually loading the AST
3959/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003960std::string ASTReader::getOriginalSourceFile(
3961 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003962 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003963 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00003964 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00003965 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00003966 Diags.Report(diag::err_fe_unable_to_read_pch_file)
3967 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00003968 return std::string();
3969 }
3970
3971 // Initialize the stream
3972 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003973 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00003974 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003975
3976 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003977 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003978 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3979 return std::string();
3980 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003981
Chris Lattnere7b154b2013-01-19 21:39:22 +00003982 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003983 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003984 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3985 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003986 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003987
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003988 // Scan for ORIGINAL_FILE inside the control block.
3989 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003990 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003991 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003992 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3993 return std::string();
3994
3995 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3996 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3997 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003998 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003999
Guy Benyei11169dd2012-12-18 14:30:41 +00004000 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004001 StringRef Blob;
4002 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4003 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004004 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004005}
4006
4007namespace {
4008 class SimplePCHValidator : public ASTReaderListener {
4009 const LangOptions &ExistingLangOpts;
4010 const TargetOptions &ExistingTargetOpts;
4011 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004012 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004013 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004014
Guy Benyei11169dd2012-12-18 14:30:41 +00004015 public:
4016 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4017 const TargetOptions &ExistingTargetOpts,
4018 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004019 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004020 FileManager &FileMgr)
4021 : ExistingLangOpts(ExistingLangOpts),
4022 ExistingTargetOpts(ExistingTargetOpts),
4023 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004024 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004025 FileMgr(FileMgr)
4026 {
4027 }
4028
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004029 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4030 bool AllowCompatibleDifferences) override {
4031 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4032 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004033 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004034 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4035 bool AllowCompatibleDifferences) override {
4036 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4037 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004038 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004039 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4040 StringRef SpecificModuleCachePath,
4041 bool Complain) override {
4042 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4043 ExistingModuleCachePath,
4044 nullptr, ExistingLangOpts);
4045 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004046 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4047 bool Complain,
4048 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004049 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004050 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004051 }
4052 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004053}
Guy Benyei11169dd2012-12-18 14:30:41 +00004054
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004055bool ASTReader::readASTFileControlBlock(
4056 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004057 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004058 ASTReaderListener &Listener) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004059 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004060 // FIXME: This allows use of the VFS; we do not allow use of the
4061 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004062 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004063 if (!Buffer) {
4064 return true;
4065 }
4066
4067 // Initialize the stream
4068 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004069 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004070 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004071
4072 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004073 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004074 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004075
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004076 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004077 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004078 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004079
4080 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004081 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004082 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004083 BitstreamCursor InputFilesCursor;
4084 if (NeedsInputFiles) {
4085 InputFilesCursor = Stream;
4086 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4087 return true;
4088
4089 // Read the abbreviations
4090 while (true) {
4091 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4092 unsigned Code = InputFilesCursor.ReadCode();
4093
4094 // We expect all abbrevs to be at the start of the block.
4095 if (Code != llvm::bitc::DEFINE_ABBREV) {
4096 InputFilesCursor.JumpToBit(Offset);
4097 break;
4098 }
4099 InputFilesCursor.ReadAbbrevRecord();
4100 }
4101 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004102
4103 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004104 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004105 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004106 while (1) {
4107 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4108 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4109 return false;
4110
4111 if (Entry.Kind != llvm::BitstreamEntry::Record)
4112 return true;
4113
Guy Benyei11169dd2012-12-18 14:30:41 +00004114 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004115 StringRef Blob;
4116 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004117 switch ((ControlRecordTypes)RecCode) {
4118 case METADATA: {
4119 if (Record[0] != VERSION_MAJOR)
4120 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004121
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004122 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004123 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004124
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004125 break;
4126 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004127 case MODULE_NAME:
4128 Listener.ReadModuleName(Blob);
4129 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004130 case MODULE_DIRECTORY:
4131 ModuleDir = Blob;
4132 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004133 case MODULE_MAP_FILE: {
4134 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004135 auto Path = ReadString(Record, Idx);
4136 ResolveImportedPath(Path, ModuleDir);
4137 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004138 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004139 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004140 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004141 if (ParseLanguageOptions(Record, false, Listener,
4142 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004143 return true;
4144 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004145
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004146 case TARGET_OPTIONS:
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004147 if (ParseTargetOptions(Record, false, Listener,
4148 /*AllowCompatibleConfigurationMismatch*/ false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004149 return true;
4150 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004151
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004152 case DIAGNOSTIC_OPTIONS:
4153 if (ParseDiagnosticOptions(Record, false, Listener))
4154 return true;
4155 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004156
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004157 case FILE_SYSTEM_OPTIONS:
4158 if (ParseFileSystemOptions(Record, false, Listener))
4159 return true;
4160 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004161
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004162 case HEADER_SEARCH_OPTIONS:
4163 if (ParseHeaderSearchOptions(Record, false, Listener))
4164 return true;
4165 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004166
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004167 case PREPROCESSOR_OPTIONS: {
4168 std::string IgnoredSuggestedPredefines;
4169 if (ParsePreprocessorOptions(Record, false, Listener,
4170 IgnoredSuggestedPredefines))
4171 return true;
4172 break;
4173 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004174
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004175 case INPUT_FILE_OFFSETS: {
4176 if (!NeedsInputFiles)
4177 break;
4178
4179 unsigned NumInputFiles = Record[0];
4180 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004181 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004182 for (unsigned I = 0; I != NumInputFiles; ++I) {
4183 // Go find this input file.
4184 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004185
4186 if (isSystemFile && !NeedsSystemInputFiles)
4187 break; // the rest are system input files
4188
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004189 BitstreamCursor &Cursor = InputFilesCursor;
4190 SavedStreamPosition SavedPosition(Cursor);
4191 Cursor.JumpToBit(InputFileOffs[I]);
4192
4193 unsigned Code = Cursor.ReadCode();
4194 RecordData Record;
4195 StringRef Blob;
4196 bool shouldContinue = false;
4197 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4198 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004199 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004200 std::string Filename = Blob;
4201 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004202 shouldContinue = Listener.visitInputFile(
4203 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004204 break;
4205 }
4206 if (!shouldContinue)
4207 break;
4208 }
4209 break;
4210 }
4211
Richard Smithd4b230b2014-10-27 23:01:16 +00004212 case IMPORTS: {
4213 if (!NeedsImports)
4214 break;
4215
4216 unsigned Idx = 0, N = Record.size();
4217 while (Idx < N) {
4218 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004219 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004220 std::string Filename = ReadString(Record, Idx);
4221 ResolveImportedPath(Filename, ModuleDir);
4222 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004223 }
4224 break;
4225 }
4226
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004227 default:
4228 // No other validation to perform.
4229 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004230 }
4231 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004232}
4233
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004234bool ASTReader::isAcceptableASTFile(
4235 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004236 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004237 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4238 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004239 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4240 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004241 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004242 validator);
Guy Benyei11169dd2012-12-18 14:30:41 +00004243}
4244
Ben Langmuir2c9af442014-04-10 17:57:43 +00004245ASTReader::ASTReadResult
4246ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004247 // Enter the submodule block.
4248 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4249 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004250 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004251 }
4252
4253 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4254 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004255 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004256 RecordData Record;
4257 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004258 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4259
4260 switch (Entry.Kind) {
4261 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4262 case llvm::BitstreamEntry::Error:
4263 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004264 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004265 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004266 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004267 case llvm::BitstreamEntry::Record:
4268 // The interesting case.
4269 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004270 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004271
Guy Benyei11169dd2012-12-18 14:30:41 +00004272 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004273 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004274 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004275 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4276
4277 if ((Kind == SUBMODULE_METADATA) != First) {
4278 Error("submodule metadata record should be at beginning of block");
4279 return Failure;
4280 }
4281 First = false;
4282
4283 // Submodule information is only valid if we have a current module.
4284 // FIXME: Should we error on these cases?
4285 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4286 Kind != SUBMODULE_DEFINITION)
4287 continue;
4288
4289 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004290 default: // Default behavior: ignore.
4291 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004292
Richard Smith03478d92014-10-23 22:12:14 +00004293 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004294 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004295 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004296 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004297 }
Richard Smith03478d92014-10-23 22:12:14 +00004298
Chris Lattner0e6c9402013-01-20 02:38:54 +00004299 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004300 unsigned Idx = 0;
4301 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4302 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4303 bool IsFramework = Record[Idx++];
4304 bool IsExplicit = Record[Idx++];
4305 bool IsSystem = Record[Idx++];
4306 bool IsExternC = Record[Idx++];
4307 bool InferSubmodules = Record[Idx++];
4308 bool InferExplicitSubmodules = Record[Idx++];
4309 bool InferExportWildcard = Record[Idx++];
4310 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004311
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004312 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004313 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004314 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004315
Guy Benyei11169dd2012-12-18 14:30:41 +00004316 // Retrieve this (sub)module from the module map, creating it if
4317 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004318 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004319 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004320
4321 // FIXME: set the definition loc for CurrentModule, or call
4322 // ModMap.setInferredModuleAllowedBy()
4323
Guy Benyei11169dd2012-12-18 14:30:41 +00004324 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4325 if (GlobalIndex >= SubmodulesLoaded.size() ||
4326 SubmodulesLoaded[GlobalIndex]) {
4327 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004328 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004329 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004330
Douglas Gregor7029ce12013-03-19 00:28:20 +00004331 if (!ParentModule) {
4332 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4333 if (CurFile != F.File) {
4334 if (!Diags.isDiagnosticInFlight()) {
4335 Diag(diag::err_module_file_conflict)
4336 << CurrentModule->getTopLevelModuleName()
4337 << CurFile->getName()
4338 << F.File->getName();
4339 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004340 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004341 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004342 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004343
4344 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004345 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004346
Adrian Prantl15bcf702015-06-30 17:39:43 +00004347 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004348 CurrentModule->IsFromModuleFile = true;
4349 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004350 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004351 CurrentModule->InferSubmodules = InferSubmodules;
4352 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4353 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004354 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004355 if (DeserializationListener)
4356 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4357
4358 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004359
Douglas Gregorfb912652013-03-20 21:10:35 +00004360 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004361 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004362 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004363 CurrentModule->UnresolvedConflicts.clear();
4364 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004365 break;
4366 }
4367
4368 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004369 std::string Filename = Blob;
4370 ResolveImportedPath(F, Filename);
4371 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004372 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004373 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4374 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004375 // This can be a spurious difference caused by changing the VFS to
4376 // point to a different copy of the file, and it is too late to
4377 // to rebuild safely.
4378 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4379 // after input file validation only real problems would remain and we
4380 // could just error. For now, assume it's okay.
4381 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004382 }
4383 }
4384 break;
4385 }
4386
Richard Smith202210b2014-10-24 20:23:01 +00004387 case SUBMODULE_HEADER:
4388 case SUBMODULE_EXCLUDED_HEADER:
4389 case SUBMODULE_PRIVATE_HEADER:
4390 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004391 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4392 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004393 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004394
Richard Smith202210b2014-10-24 20:23:01 +00004395 case SUBMODULE_TEXTUAL_HEADER:
4396 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4397 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4398 // them here.
4399 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004400
Guy Benyei11169dd2012-12-18 14:30:41 +00004401 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004402 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004403 break;
4404 }
4405
4406 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004407 std::string Dirname = Blob;
4408 ResolveImportedPath(F, Dirname);
4409 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004410 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004411 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4412 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004413 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4414 Error("mismatched umbrella directories in submodule");
4415 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004416 }
4417 }
4418 break;
4419 }
4420
4421 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004422 F.BaseSubmoduleID = getTotalNumSubmodules();
4423 F.LocalNumSubmodules = Record[0];
4424 unsigned LocalBaseSubmoduleID = Record[1];
4425 if (F.LocalNumSubmodules > 0) {
4426 // Introduce the global -> local mapping for submodules within this
4427 // module.
4428 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4429
4430 // Introduce the local -> global mapping for submodules within this
4431 // module.
4432 F.SubmoduleRemap.insertOrReplace(
4433 std::make_pair(LocalBaseSubmoduleID,
4434 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004435
Ben Langmuir52ca6782014-10-20 16:27:32 +00004436 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4437 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004438 break;
4439 }
4440
4441 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004442 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004443 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004444 Unresolved.File = &F;
4445 Unresolved.Mod = CurrentModule;
4446 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004447 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004448 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004449 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004450 }
4451 break;
4452 }
4453
4454 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004455 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004456 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004457 Unresolved.File = &F;
4458 Unresolved.Mod = CurrentModule;
4459 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004460 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004461 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004462 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004463 }
4464
4465 // Once we've loaded the set of exports, there's no reason to keep
4466 // the parsed, unresolved exports around.
4467 CurrentModule->UnresolvedExports.clear();
4468 break;
4469 }
4470 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004471 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004472 Context.getTargetInfo());
4473 break;
4474 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004475
4476 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004477 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004478 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004479 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004480
4481 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004482 CurrentModule->ConfigMacros.push_back(Blob.str());
4483 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004484
4485 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004486 UnresolvedModuleRef Unresolved;
4487 Unresolved.File = &F;
4488 Unresolved.Mod = CurrentModule;
4489 Unresolved.ID = Record[0];
4490 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4491 Unresolved.IsWildcard = false;
4492 Unresolved.String = Blob;
4493 UnresolvedModuleRefs.push_back(Unresolved);
4494 break;
4495 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004496 }
4497 }
4498}
4499
4500/// \brief Parse the record that corresponds to a LangOptions data
4501/// structure.
4502///
4503/// This routine parses the language options from the AST file and then gives
4504/// them to the AST listener if one is set.
4505///
4506/// \returns true if the listener deems the file unacceptable, false otherwise.
4507bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4508 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004509 ASTReaderListener &Listener,
4510 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004511 LangOptions LangOpts;
4512 unsigned Idx = 0;
4513#define LANGOPT(Name, Bits, Default, Description) \
4514 LangOpts.Name = Record[Idx++];
4515#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4516 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4517#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004518#define SANITIZER(NAME, ID) \
4519 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004520#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004521
Ben Langmuircd98cb72015-06-23 18:20:18 +00004522 for (unsigned N = Record[Idx++]; N; --N)
4523 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4524
Guy Benyei11169dd2012-12-18 14:30:41 +00004525 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4526 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4527 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004528
Ben Langmuird4a667a2015-06-23 18:20:23 +00004529 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004530
4531 // Comment options.
4532 for (unsigned N = Record[Idx++]; N; --N) {
4533 LangOpts.CommentOpts.BlockCommandNames.push_back(
4534 ReadString(Record, Idx));
4535 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004536 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004537
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004538 return Listener.ReadLanguageOptions(LangOpts, Complain,
4539 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004540}
4541
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004542bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4543 ASTReaderListener &Listener,
4544 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 unsigned Idx = 0;
4546 TargetOptions TargetOpts;
4547 TargetOpts.Triple = ReadString(Record, Idx);
4548 TargetOpts.CPU = ReadString(Record, Idx);
4549 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004550 for (unsigned N = Record[Idx++]; N; --N) {
4551 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4552 }
4553 for (unsigned N = Record[Idx++]; N; --N) {
4554 TargetOpts.Features.push_back(ReadString(Record, Idx));
4555 }
4556
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004557 return Listener.ReadTargetOptions(TargetOpts, Complain,
4558 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004559}
4560
4561bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4562 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004563 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004564 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004565#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004566#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004567 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004568#include "clang/Basic/DiagnosticOptions.def"
4569
Richard Smith3be1cb22014-08-07 00:24:21 +00004570 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004571 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004572 for (unsigned N = Record[Idx++]; N; --N)
4573 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004574
4575 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4576}
4577
4578bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4579 ASTReaderListener &Listener) {
4580 FileSystemOptions FSOpts;
4581 unsigned Idx = 0;
4582 FSOpts.WorkingDir = ReadString(Record, Idx);
4583 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4584}
4585
4586bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4587 bool Complain,
4588 ASTReaderListener &Listener) {
4589 HeaderSearchOptions HSOpts;
4590 unsigned Idx = 0;
4591 HSOpts.Sysroot = ReadString(Record, Idx);
4592
4593 // Include entries.
4594 for (unsigned N = Record[Idx++]; N; --N) {
4595 std::string Path = ReadString(Record, Idx);
4596 frontend::IncludeDirGroup Group
4597 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004598 bool IsFramework = Record[Idx++];
4599 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004600 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4601 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004602 }
4603
4604 // System header prefixes.
4605 for (unsigned N = Record[Idx++]; N; --N) {
4606 std::string Prefix = ReadString(Record, Idx);
4607 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004608 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004609 }
4610
4611 HSOpts.ResourceDir = ReadString(Record, Idx);
4612 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004613 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004614 HSOpts.DisableModuleHash = Record[Idx++];
4615 HSOpts.UseBuiltinIncludes = Record[Idx++];
4616 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4617 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4618 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004619 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004620
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004621 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4622 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004623}
4624
4625bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4626 bool Complain,
4627 ASTReaderListener &Listener,
4628 std::string &SuggestedPredefines) {
4629 PreprocessorOptions PPOpts;
4630 unsigned Idx = 0;
4631
4632 // Macro definitions/undefs
4633 for (unsigned N = Record[Idx++]; N; --N) {
4634 std::string Macro = ReadString(Record, Idx);
4635 bool IsUndef = Record[Idx++];
4636 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4637 }
4638
4639 // Includes
4640 for (unsigned N = Record[Idx++]; N; --N) {
4641 PPOpts.Includes.push_back(ReadString(Record, Idx));
4642 }
4643
4644 // Macro Includes
4645 for (unsigned N = Record[Idx++]; N; --N) {
4646 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4647 }
4648
4649 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004650 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004651 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4652 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4653 PPOpts.ObjCXXARCStandardLibrary =
4654 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4655 SuggestedPredefines.clear();
4656 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4657 SuggestedPredefines);
4658}
4659
4660std::pair<ModuleFile *, unsigned>
4661ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4662 GlobalPreprocessedEntityMapType::iterator
4663 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4664 assert(I != GlobalPreprocessedEntityMap.end() &&
4665 "Corrupted global preprocessed entity map");
4666 ModuleFile *M = I->second;
4667 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4668 return std::make_pair(M, LocalIndex);
4669}
4670
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004671llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004672ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4673 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4674 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4675 Mod.NumPreprocessedEntities);
4676
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004677 return llvm::make_range(PreprocessingRecord::iterator(),
4678 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004679}
4680
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004681llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004682ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004683 return llvm::make_range(
4684 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4685 ModuleDeclIterator(this, &Mod,
4686 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004687}
4688
4689PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4690 PreprocessedEntityID PPID = Index+1;
4691 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4692 ModuleFile &M = *PPInfo.first;
4693 unsigned LocalIndex = PPInfo.second;
4694 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4695
Guy Benyei11169dd2012-12-18 14:30:41 +00004696 if (!PP.getPreprocessingRecord()) {
4697 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004698 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004699 }
4700
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004701 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4702 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4703
4704 llvm::BitstreamEntry Entry =
4705 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4706 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004707 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004708
Guy Benyei11169dd2012-12-18 14:30:41 +00004709 // Read the record.
4710 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4711 ReadSourceLocation(M, PPOffs.End));
4712 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004713 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004714 RecordData Record;
4715 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004716 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4717 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004718 switch (RecType) {
4719 case PPD_MACRO_EXPANSION: {
4720 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004721 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004722 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004723 if (isBuiltin)
4724 Name = getLocalIdentifier(M, Record[1]);
4725 else {
Richard Smith66a81862015-05-04 02:25:31 +00004726 PreprocessedEntityID GlobalID =
4727 getGlobalPreprocessedEntityID(M, Record[1]);
4728 Def = cast<MacroDefinitionRecord>(
4729 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004730 }
4731
4732 MacroExpansion *ME;
4733 if (isBuiltin)
4734 ME = new (PPRec) MacroExpansion(Name, Range);
4735 else
4736 ME = new (PPRec) MacroExpansion(Def, Range);
4737
4738 return ME;
4739 }
4740
4741 case PPD_MACRO_DEFINITION: {
4742 // Decode the identifier info and then check again; if the macro is
4743 // still defined and associated with the identifier,
4744 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004745 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004746
4747 if (DeserializationListener)
4748 DeserializationListener->MacroDefinitionRead(PPID, MD);
4749
4750 return MD;
4751 }
4752
4753 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004754 const char *FullFileNameStart = Blob.data() + Record[0];
4755 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004756 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004757 if (!FullFileName.empty())
4758 File = PP.getFileManager().getFile(FullFileName);
4759
4760 // FIXME: Stable encoding
4761 InclusionDirective::InclusionKind Kind
4762 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4763 InclusionDirective *ID
4764 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004765 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004766 Record[1], Record[3],
4767 File,
4768 Range);
4769 return ID;
4770 }
4771 }
4772
4773 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4774}
4775
4776/// \brief \arg SLocMapI points at a chunk of a module that contains no
4777/// preprocessed entities or the entities it contains are not the ones we are
4778/// looking for. Find the next module that contains entities and return the ID
4779/// of the first entry.
4780PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4781 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4782 ++SLocMapI;
4783 for (GlobalSLocOffsetMapType::const_iterator
4784 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4785 ModuleFile &M = *SLocMapI->second;
4786 if (M.NumPreprocessedEntities)
4787 return M.BasePreprocessedEntityID;
4788 }
4789
4790 return getTotalNumPreprocessedEntities();
4791}
4792
4793namespace {
4794
4795template <unsigned PPEntityOffset::*PPLoc>
4796struct PPEntityComp {
4797 const ASTReader &Reader;
4798 ModuleFile &M;
4799
4800 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4801
4802 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4803 SourceLocation LHS = getLoc(L);
4804 SourceLocation RHS = getLoc(R);
4805 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4806 }
4807
4808 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4809 SourceLocation LHS = getLoc(L);
4810 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4811 }
4812
4813 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4814 SourceLocation RHS = getLoc(R);
4815 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4816 }
4817
4818 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4819 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4820 }
4821};
4822
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004823}
Guy Benyei11169dd2012-12-18 14:30:41 +00004824
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004825PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4826 bool EndsAfter) const {
4827 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004828 return getTotalNumPreprocessedEntities();
4829
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004830 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4831 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004832 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4833 "Corrupted global sloc offset map");
4834
4835 if (SLocMapI->second->NumPreprocessedEntities == 0)
4836 return findNextPreprocessedEntity(SLocMapI);
4837
4838 ModuleFile &M = *SLocMapI->second;
4839 typedef const PPEntityOffset *pp_iterator;
4840 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4841 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4842
4843 size_t Count = M.NumPreprocessedEntities;
4844 size_t Half;
4845 pp_iterator First = pp_begin;
4846 pp_iterator PPI;
4847
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004848 if (EndsAfter) {
4849 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4850 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4851 } else {
4852 // Do a binary search manually instead of using std::lower_bound because
4853 // The end locations of entities may be unordered (when a macro expansion
4854 // is inside another macro argument), but for this case it is not important
4855 // whether we get the first macro expansion or its containing macro.
4856 while (Count > 0) {
4857 Half = Count / 2;
4858 PPI = First;
4859 std::advance(PPI, Half);
4860 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4861 Loc)) {
4862 First = PPI;
4863 ++First;
4864 Count = Count - Half - 1;
4865 } else
4866 Count = Half;
4867 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004868 }
4869
4870 if (PPI == pp_end)
4871 return findNextPreprocessedEntity(SLocMapI);
4872
4873 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4874}
4875
Guy Benyei11169dd2012-12-18 14:30:41 +00004876/// \brief Returns a pair of [Begin, End) indices of preallocated
4877/// preprocessed entities that \arg Range encompasses.
4878std::pair<unsigned, unsigned>
4879 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4880 if (Range.isInvalid())
4881 return std::make_pair(0,0);
4882 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4883
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004884 PreprocessedEntityID BeginID =
4885 findPreprocessedEntity(Range.getBegin(), false);
4886 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004887 return std::make_pair(BeginID, EndID);
4888}
4889
4890/// \brief Optionally returns true or false if the preallocated preprocessed
4891/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004892Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004893 FileID FID) {
4894 if (FID.isInvalid())
4895 return false;
4896
4897 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4898 ModuleFile &M = *PPInfo.first;
4899 unsigned LocalIndex = PPInfo.second;
4900 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4901
4902 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4903 if (Loc.isInvalid())
4904 return false;
4905
4906 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4907 return true;
4908 else
4909 return false;
4910}
4911
4912namespace {
4913 /// \brief Visitor used to search for information about a header file.
4914 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004915 const FileEntry *FE;
4916
David Blaikie05785d12013-02-20 22:23:23 +00004917 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004918
4919 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004920 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4921 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004922
4923 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004924 HeaderFileInfoLookupTable *Table
4925 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4926 if (!Table)
4927 return false;
4928
4929 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00004930 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004931 if (Pos == Table->end())
4932 return false;
4933
Richard Smithbdf2d932015-07-30 03:37:16 +00004934 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00004935 return true;
4936 }
4937
David Blaikie05785d12013-02-20 22:23:23 +00004938 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004939 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004940}
Guy Benyei11169dd2012-12-18 14:30:41 +00004941
4942HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004943 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004944 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004945 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004946 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004947
4948 return HeaderFileInfo();
4949}
4950
4951void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4952 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004953 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004954 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4955 ModuleFile &F = *(*I);
4956 unsigned Idx = 0;
4957 DiagStates.clear();
4958 assert(!Diag.DiagStates.empty());
4959 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4960 while (Idx < F.PragmaDiagMappings.size()) {
4961 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4962 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4963 if (DiagStateID != 0) {
4964 Diag.DiagStatePoints.push_back(
4965 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4966 FullSourceLoc(Loc, SourceMgr)));
4967 continue;
4968 }
4969
4970 assert(DiagStateID == 0);
4971 // A new DiagState was created here.
4972 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4973 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4974 DiagStates.push_back(NewState);
4975 Diag.DiagStatePoints.push_back(
4976 DiagnosticsEngine::DiagStatePoint(NewState,
4977 FullSourceLoc(Loc, SourceMgr)));
4978 while (1) {
4979 assert(Idx < F.PragmaDiagMappings.size() &&
4980 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4981 if (Idx >= F.PragmaDiagMappings.size()) {
4982 break; // Something is messed up but at least avoid infinite loop in
4983 // release build.
4984 }
4985 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4986 if (DiagID == (unsigned)-1) {
4987 break; // no more diag/map pairs for this location.
4988 }
Alp Tokerc726c362014-06-10 09:31:37 +00004989 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
4990 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
4991 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00004992 }
4993 }
4994 }
4995}
4996
4997/// \brief Get the correct cursor and offset for loading a type.
4998ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4999 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5000 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5001 ModuleFile *M = I->second;
5002 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5003}
5004
5005/// \brief Read and return the type with the given index..
5006///
5007/// The index is the type ID, shifted and minus the number of predefs. This
5008/// routine actually reads the record corresponding to the type at the given
5009/// location. It is a helper routine for GetType, which deals with reading type
5010/// IDs.
5011QualType ASTReader::readTypeRecord(unsigned Index) {
5012 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005013 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005014
5015 // Keep track of where we are in the stream, then jump back there
5016 // after reading this type.
5017 SavedStreamPosition SavedPosition(DeclsCursor);
5018
5019 ReadingKindTracker ReadingKind(Read_Type, *this);
5020
5021 // Note that we are loading a type record.
5022 Deserializing AType(this);
5023
5024 unsigned Idx = 0;
5025 DeclsCursor.JumpToBit(Loc.Offset);
5026 RecordData Record;
5027 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005028 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005029 case TYPE_EXT_QUAL: {
5030 if (Record.size() != 2) {
5031 Error("Incorrect encoding of extended qualifier type");
5032 return QualType();
5033 }
5034 QualType Base = readType(*Loc.F, Record, Idx);
5035 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5036 return Context.getQualifiedType(Base, Quals);
5037 }
5038
5039 case TYPE_COMPLEX: {
5040 if (Record.size() != 1) {
5041 Error("Incorrect encoding of complex type");
5042 return QualType();
5043 }
5044 QualType ElemType = readType(*Loc.F, Record, Idx);
5045 return Context.getComplexType(ElemType);
5046 }
5047
5048 case TYPE_POINTER: {
5049 if (Record.size() != 1) {
5050 Error("Incorrect encoding of pointer type");
5051 return QualType();
5052 }
5053 QualType PointeeType = readType(*Loc.F, Record, Idx);
5054 return Context.getPointerType(PointeeType);
5055 }
5056
Reid Kleckner8a365022013-06-24 17:51:48 +00005057 case TYPE_DECAYED: {
5058 if (Record.size() != 1) {
5059 Error("Incorrect encoding of decayed type");
5060 return QualType();
5061 }
5062 QualType OriginalType = readType(*Loc.F, Record, Idx);
5063 QualType DT = Context.getAdjustedParameterType(OriginalType);
5064 if (!isa<DecayedType>(DT))
5065 Error("Decayed type does not decay");
5066 return DT;
5067 }
5068
Reid Kleckner0503a872013-12-05 01:23:43 +00005069 case TYPE_ADJUSTED: {
5070 if (Record.size() != 2) {
5071 Error("Incorrect encoding of adjusted type");
5072 return QualType();
5073 }
5074 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5075 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5076 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5077 }
5078
Guy Benyei11169dd2012-12-18 14:30:41 +00005079 case TYPE_BLOCK_POINTER: {
5080 if (Record.size() != 1) {
5081 Error("Incorrect encoding of block pointer type");
5082 return QualType();
5083 }
5084 QualType PointeeType = readType(*Loc.F, Record, Idx);
5085 return Context.getBlockPointerType(PointeeType);
5086 }
5087
5088 case TYPE_LVALUE_REFERENCE: {
5089 if (Record.size() != 2) {
5090 Error("Incorrect encoding of lvalue reference type");
5091 return QualType();
5092 }
5093 QualType PointeeType = readType(*Loc.F, Record, Idx);
5094 return Context.getLValueReferenceType(PointeeType, Record[1]);
5095 }
5096
5097 case TYPE_RVALUE_REFERENCE: {
5098 if (Record.size() != 1) {
5099 Error("Incorrect encoding of rvalue reference type");
5100 return QualType();
5101 }
5102 QualType PointeeType = readType(*Loc.F, Record, Idx);
5103 return Context.getRValueReferenceType(PointeeType);
5104 }
5105
5106 case TYPE_MEMBER_POINTER: {
5107 if (Record.size() != 2) {
5108 Error("Incorrect encoding of member pointer type");
5109 return QualType();
5110 }
5111 QualType PointeeType = readType(*Loc.F, Record, Idx);
5112 QualType ClassType = readType(*Loc.F, Record, Idx);
5113 if (PointeeType.isNull() || ClassType.isNull())
5114 return QualType();
5115
5116 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5117 }
5118
5119 case TYPE_CONSTANT_ARRAY: {
5120 QualType ElementType = readType(*Loc.F, Record, Idx);
5121 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5122 unsigned IndexTypeQuals = Record[2];
5123 unsigned Idx = 3;
5124 llvm::APInt Size = ReadAPInt(Record, Idx);
5125 return Context.getConstantArrayType(ElementType, Size,
5126 ASM, IndexTypeQuals);
5127 }
5128
5129 case TYPE_INCOMPLETE_ARRAY: {
5130 QualType ElementType = readType(*Loc.F, Record, Idx);
5131 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5132 unsigned IndexTypeQuals = Record[2];
5133 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5134 }
5135
5136 case TYPE_VARIABLE_ARRAY: {
5137 QualType ElementType = readType(*Loc.F, Record, Idx);
5138 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5139 unsigned IndexTypeQuals = Record[2];
5140 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5141 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5142 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5143 ASM, IndexTypeQuals,
5144 SourceRange(LBLoc, RBLoc));
5145 }
5146
5147 case TYPE_VECTOR: {
5148 if (Record.size() != 3) {
5149 Error("incorrect encoding of vector type in AST file");
5150 return QualType();
5151 }
5152
5153 QualType ElementType = readType(*Loc.F, Record, Idx);
5154 unsigned NumElements = Record[1];
5155 unsigned VecKind = Record[2];
5156 return Context.getVectorType(ElementType, NumElements,
5157 (VectorType::VectorKind)VecKind);
5158 }
5159
5160 case TYPE_EXT_VECTOR: {
5161 if (Record.size() != 3) {
5162 Error("incorrect encoding of extended vector type in AST file");
5163 return QualType();
5164 }
5165
5166 QualType ElementType = readType(*Loc.F, Record, Idx);
5167 unsigned NumElements = Record[1];
5168 return Context.getExtVectorType(ElementType, NumElements);
5169 }
5170
5171 case TYPE_FUNCTION_NO_PROTO: {
5172 if (Record.size() != 6) {
5173 Error("incorrect encoding of no-proto function type");
5174 return QualType();
5175 }
5176 QualType ResultType = readType(*Loc.F, Record, Idx);
5177 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5178 (CallingConv)Record[4], Record[5]);
5179 return Context.getFunctionNoProtoType(ResultType, Info);
5180 }
5181
5182 case TYPE_FUNCTION_PROTO: {
5183 QualType ResultType = readType(*Loc.F, Record, Idx);
5184
5185 FunctionProtoType::ExtProtoInfo EPI;
5186 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5187 /*hasregparm*/ Record[2],
5188 /*regparm*/ Record[3],
5189 static_cast<CallingConv>(Record[4]),
5190 /*produces*/ Record[5]);
5191
5192 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005193
5194 EPI.Variadic = Record[Idx++];
5195 EPI.HasTrailingReturn = Record[Idx++];
5196 EPI.TypeQuals = Record[Idx++];
5197 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005198 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005199 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005200
5201 unsigned NumParams = Record[Idx++];
5202 SmallVector<QualType, 16> ParamTypes;
5203 for (unsigned I = 0; I != NumParams; ++I)
5204 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5205
Jordan Rose5c382722013-03-08 21:51:21 +00005206 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005207 }
5208
5209 case TYPE_UNRESOLVED_USING: {
5210 unsigned Idx = 0;
5211 return Context.getTypeDeclType(
5212 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5213 }
5214
5215 case TYPE_TYPEDEF: {
5216 if (Record.size() != 2) {
5217 Error("incorrect encoding of typedef type");
5218 return QualType();
5219 }
5220 unsigned Idx = 0;
5221 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5222 QualType Canonical = readType(*Loc.F, Record, Idx);
5223 if (!Canonical.isNull())
5224 Canonical = Context.getCanonicalType(Canonical);
5225 return Context.getTypedefType(Decl, Canonical);
5226 }
5227
5228 case TYPE_TYPEOF_EXPR:
5229 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5230
5231 case TYPE_TYPEOF: {
5232 if (Record.size() != 1) {
5233 Error("incorrect encoding of typeof(type) in AST file");
5234 return QualType();
5235 }
5236 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5237 return Context.getTypeOfType(UnderlyingType);
5238 }
5239
5240 case TYPE_DECLTYPE: {
5241 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5242 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5243 }
5244
5245 case TYPE_UNARY_TRANSFORM: {
5246 QualType BaseType = readType(*Loc.F, Record, Idx);
5247 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5248 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5249 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5250 }
5251
Richard Smith74aeef52013-04-26 16:15:35 +00005252 case TYPE_AUTO: {
5253 QualType Deduced = readType(*Loc.F, Record, Idx);
5254 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005255 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005256 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005257 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005258
5259 case TYPE_RECORD: {
5260 if (Record.size() != 2) {
5261 Error("incorrect encoding of record type");
5262 return QualType();
5263 }
5264 unsigned Idx = 0;
5265 bool IsDependent = Record[Idx++];
5266 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5267 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5268 QualType T = Context.getRecordType(RD);
5269 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5270 return T;
5271 }
5272
5273 case TYPE_ENUM: {
5274 if (Record.size() != 2) {
5275 Error("incorrect encoding of enum type");
5276 return QualType();
5277 }
5278 unsigned Idx = 0;
5279 bool IsDependent = Record[Idx++];
5280 QualType T
5281 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5282 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5283 return T;
5284 }
5285
5286 case TYPE_ATTRIBUTED: {
5287 if (Record.size() != 3) {
5288 Error("incorrect encoding of attributed type");
5289 return QualType();
5290 }
5291 QualType modifiedType = readType(*Loc.F, Record, Idx);
5292 QualType equivalentType = readType(*Loc.F, Record, Idx);
5293 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5294 return Context.getAttributedType(kind, modifiedType, equivalentType);
5295 }
5296
5297 case TYPE_PAREN: {
5298 if (Record.size() != 1) {
5299 Error("incorrect encoding of paren type");
5300 return QualType();
5301 }
5302 QualType InnerType = readType(*Loc.F, Record, Idx);
5303 return Context.getParenType(InnerType);
5304 }
5305
5306 case TYPE_PACK_EXPANSION: {
5307 if (Record.size() != 2) {
5308 Error("incorrect encoding of pack expansion type");
5309 return QualType();
5310 }
5311 QualType Pattern = readType(*Loc.F, Record, Idx);
5312 if (Pattern.isNull())
5313 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005314 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005315 if (Record[1])
5316 NumExpansions = Record[1] - 1;
5317 return Context.getPackExpansionType(Pattern, NumExpansions);
5318 }
5319
5320 case TYPE_ELABORATED: {
5321 unsigned Idx = 0;
5322 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5323 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5324 QualType NamedType = readType(*Loc.F, Record, Idx);
5325 return Context.getElaboratedType(Keyword, NNS, NamedType);
5326 }
5327
5328 case TYPE_OBJC_INTERFACE: {
5329 unsigned Idx = 0;
5330 ObjCInterfaceDecl *ItfD
5331 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5332 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5333 }
5334
5335 case TYPE_OBJC_OBJECT: {
5336 unsigned Idx = 0;
5337 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005338 unsigned NumTypeArgs = Record[Idx++];
5339 SmallVector<QualType, 4> TypeArgs;
5340 for (unsigned I = 0; I != NumTypeArgs; ++I)
5341 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005342 unsigned NumProtos = Record[Idx++];
5343 SmallVector<ObjCProtocolDecl*, 4> Protos;
5344 for (unsigned I = 0; I != NumProtos; ++I)
5345 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005346 bool IsKindOf = Record[Idx++];
5347 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005348 }
5349
5350 case TYPE_OBJC_OBJECT_POINTER: {
5351 unsigned Idx = 0;
5352 QualType Pointee = readType(*Loc.F, Record, Idx);
5353 return Context.getObjCObjectPointerType(Pointee);
5354 }
5355
5356 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5357 unsigned Idx = 0;
5358 QualType Parm = readType(*Loc.F, Record, Idx);
5359 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005360 return Context.getSubstTemplateTypeParmType(
5361 cast<TemplateTypeParmType>(Parm),
5362 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005363 }
5364
5365 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5366 unsigned Idx = 0;
5367 QualType Parm = readType(*Loc.F, Record, Idx);
5368 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5369 return Context.getSubstTemplateTypeParmPackType(
5370 cast<TemplateTypeParmType>(Parm),
5371 ArgPack);
5372 }
5373
5374 case TYPE_INJECTED_CLASS_NAME: {
5375 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5376 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5377 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5378 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005379 const Type *T = nullptr;
5380 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5381 if (const Type *Existing = DI->getTypeForDecl()) {
5382 T = Existing;
5383 break;
5384 }
5385 }
5386 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005387 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005388 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5389 DI->setTypeForDecl(T);
5390 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005391 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005392 }
5393
5394 case TYPE_TEMPLATE_TYPE_PARM: {
5395 unsigned Idx = 0;
5396 unsigned Depth = Record[Idx++];
5397 unsigned Index = Record[Idx++];
5398 bool Pack = Record[Idx++];
5399 TemplateTypeParmDecl *D
5400 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5401 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5402 }
5403
5404 case TYPE_DEPENDENT_NAME: {
5405 unsigned Idx = 0;
5406 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5407 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005408 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005409 QualType Canon = readType(*Loc.F, Record, Idx);
5410 if (!Canon.isNull())
5411 Canon = Context.getCanonicalType(Canon);
5412 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5413 }
5414
5415 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5416 unsigned Idx = 0;
5417 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5418 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005419 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005420 unsigned NumArgs = Record[Idx++];
5421 SmallVector<TemplateArgument, 8> Args;
5422 Args.reserve(NumArgs);
5423 while (NumArgs--)
5424 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5425 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5426 Args.size(), Args.data());
5427 }
5428
5429 case TYPE_DEPENDENT_SIZED_ARRAY: {
5430 unsigned Idx = 0;
5431
5432 // ArrayType
5433 QualType ElementType = readType(*Loc.F, Record, Idx);
5434 ArrayType::ArraySizeModifier ASM
5435 = (ArrayType::ArraySizeModifier)Record[Idx++];
5436 unsigned IndexTypeQuals = Record[Idx++];
5437
5438 // DependentSizedArrayType
5439 Expr *NumElts = ReadExpr(*Loc.F);
5440 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5441
5442 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5443 IndexTypeQuals, Brackets);
5444 }
5445
5446 case TYPE_TEMPLATE_SPECIALIZATION: {
5447 unsigned Idx = 0;
5448 bool IsDependent = Record[Idx++];
5449 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5450 SmallVector<TemplateArgument, 8> Args;
5451 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5452 QualType Underlying = readType(*Loc.F, Record, Idx);
5453 QualType T;
5454 if (Underlying.isNull())
5455 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5456 Args.size());
5457 else
5458 T = Context.getTemplateSpecializationType(Name, Args.data(),
5459 Args.size(), Underlying);
5460 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5461 return T;
5462 }
5463
5464 case TYPE_ATOMIC: {
5465 if (Record.size() != 1) {
5466 Error("Incorrect encoding of atomic type");
5467 return QualType();
5468 }
5469 QualType ValueType = readType(*Loc.F, Record, Idx);
5470 return Context.getAtomicType(ValueType);
5471 }
5472 }
5473 llvm_unreachable("Invalid TypeCode!");
5474}
5475
Richard Smith564417a2014-03-20 21:47:22 +00005476void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5477 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005478 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005479 const RecordData &Record, unsigned &Idx) {
5480 ExceptionSpecificationType EST =
5481 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005482 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005483 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005484 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005485 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005486 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005487 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005488 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005489 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005490 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5491 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005492 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005493 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005494 }
5495}
5496
Guy Benyei11169dd2012-12-18 14:30:41 +00005497class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5498 ASTReader &Reader;
5499 ModuleFile &F;
5500 const ASTReader::RecordData &Record;
5501 unsigned &Idx;
5502
5503 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5504 unsigned &I) {
5505 return Reader.ReadSourceLocation(F, R, I);
5506 }
5507
5508 template<typename T>
5509 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5510 return Reader.ReadDeclAs<T>(F, Record, Idx);
5511 }
5512
5513public:
5514 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5515 const ASTReader::RecordData &Record, unsigned &Idx)
5516 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5517 { }
5518
5519 // We want compile-time assurance that we've enumerated all of
5520 // these, so unfortunately we have to declare them first, then
5521 // define them out-of-line.
5522#define ABSTRACT_TYPELOC(CLASS, PARENT)
5523#define TYPELOC(CLASS, PARENT) \
5524 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5525#include "clang/AST/TypeLocNodes.def"
5526
5527 void VisitFunctionTypeLoc(FunctionTypeLoc);
5528 void VisitArrayTypeLoc(ArrayTypeLoc);
5529};
5530
5531void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5532 // nothing to do
5533}
5534void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5535 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5536 if (TL.needsExtraLocalData()) {
5537 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5538 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5539 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5540 TL.setModeAttr(Record[Idx++]);
5541 }
5542}
5543void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5544 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5545}
5546void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5547 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5548}
Reid Kleckner8a365022013-06-24 17:51:48 +00005549void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5550 // nothing to do
5551}
Reid Kleckner0503a872013-12-05 01:23:43 +00005552void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5553 // nothing to do
5554}
Guy Benyei11169dd2012-12-18 14:30:41 +00005555void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5556 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5557}
5558void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5559 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5560}
5561void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5562 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5563}
5564void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5565 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5566 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5567}
5568void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5569 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5570 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5571 if (Record[Idx++])
5572 TL.setSizeExpr(Reader.ReadExpr(F));
5573 else
Craig Toppera13603a2014-05-22 05:54:18 +00005574 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005575}
5576void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5577 VisitArrayTypeLoc(TL);
5578}
5579void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5580 VisitArrayTypeLoc(TL);
5581}
5582void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5583 VisitArrayTypeLoc(TL);
5584}
5585void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5586 DependentSizedArrayTypeLoc TL) {
5587 VisitArrayTypeLoc(TL);
5588}
5589void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5590 DependentSizedExtVectorTypeLoc TL) {
5591 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5592}
5593void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5594 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5595}
5596void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5597 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5598}
5599void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5600 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5601 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5602 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5603 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005604 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5605 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005606 }
5607}
5608void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5609 VisitFunctionTypeLoc(TL);
5610}
5611void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5612 VisitFunctionTypeLoc(TL);
5613}
5614void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5615 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5616}
5617void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5618 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5619}
5620void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5621 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5622 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5623 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5624}
5625void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5626 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5627 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5628 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5629 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5630}
5631void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5632 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5633}
5634void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5635 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5636 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5637 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5638 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5639}
5640void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5641 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5642}
5643void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5644 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5645}
5646void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5647 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5648}
5649void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5650 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5651 if (TL.hasAttrOperand()) {
5652 SourceRange range;
5653 range.setBegin(ReadSourceLocation(Record, Idx));
5654 range.setEnd(ReadSourceLocation(Record, Idx));
5655 TL.setAttrOperandParensRange(range);
5656 }
5657 if (TL.hasAttrExprOperand()) {
5658 if (Record[Idx++])
5659 TL.setAttrExprOperand(Reader.ReadExpr(F));
5660 else
Craig Toppera13603a2014-05-22 05:54:18 +00005661 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005662 } else if (TL.hasAttrEnumOperand())
5663 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5664}
5665void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5666 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5667}
5668void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5669 SubstTemplateTypeParmTypeLoc TL) {
5670 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5671}
5672void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5673 SubstTemplateTypeParmPackTypeLoc TL) {
5674 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5675}
5676void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5677 TemplateSpecializationTypeLoc TL) {
5678 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5679 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5680 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5681 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5682 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5683 TL.setArgLocInfo(i,
5684 Reader.GetTemplateArgumentLocInfo(F,
5685 TL.getTypePtr()->getArg(i).getKind(),
5686 Record, Idx));
5687}
5688void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5689 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5690 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5691}
5692void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5693 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5694 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5695}
5696void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5697 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5698}
5699void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5700 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5701 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5702 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5703}
5704void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5705 DependentTemplateSpecializationTypeLoc TL) {
5706 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5707 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5708 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5709 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5710 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5711 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5712 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5713 TL.setArgLocInfo(I,
5714 Reader.GetTemplateArgumentLocInfo(F,
5715 TL.getTypePtr()->getArg(I).getKind(),
5716 Record, Idx));
5717}
5718void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5719 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5720}
5721void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5722 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5723}
5724void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5725 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005726 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5727 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5728 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5729 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5730 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5731 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005732 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5733 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5734}
5735void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5736 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5737}
5738void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5739 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5740 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5741 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5742}
5743
5744TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5745 const RecordData &Record,
5746 unsigned &Idx) {
5747 QualType InfoTy = readType(F, Record, Idx);
5748 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005749 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005750
5751 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5752 TypeLocReader TLR(*this, F, Record, Idx);
5753 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5754 TLR.Visit(TL);
5755 return TInfo;
5756}
5757
5758QualType ASTReader::GetType(TypeID ID) {
5759 unsigned FastQuals = ID & Qualifiers::FastMask;
5760 unsigned Index = ID >> Qualifiers::FastWidth;
5761
5762 if (Index < NUM_PREDEF_TYPE_IDS) {
5763 QualType T;
5764 switch ((PredefinedTypeIDs)Index) {
5765 case PREDEF_TYPE_NULL_ID: return QualType();
5766 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5767 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5768
5769 case PREDEF_TYPE_CHAR_U_ID:
5770 case PREDEF_TYPE_CHAR_S_ID:
5771 // FIXME: Check that the signedness of CharTy is correct!
5772 T = Context.CharTy;
5773 break;
5774
5775 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5776 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5777 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5778 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5779 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5780 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5781 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5782 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5783 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5784 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5785 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5786 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5787 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5788 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5789 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5790 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5791 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5792 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5793 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5794 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5795 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5796 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5797 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5798 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5799 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5800 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5801 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5802 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005803 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5804 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5805 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5806 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5807 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5808 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005809 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005810 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005811 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5812
5813 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5814 T = Context.getAutoRRefDeductType();
5815 break;
5816
5817 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5818 T = Context.ARCUnbridgedCastTy;
5819 break;
5820
Guy Benyei11169dd2012-12-18 14:30:41 +00005821 case PREDEF_TYPE_BUILTIN_FN:
5822 T = Context.BuiltinFnTy;
5823 break;
5824 }
5825
5826 assert(!T.isNull() && "Unknown predefined type");
5827 return T.withFastQualifiers(FastQuals);
5828 }
5829
5830 Index -= NUM_PREDEF_TYPE_IDS;
5831 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5832 if (TypesLoaded[Index].isNull()) {
5833 TypesLoaded[Index] = readTypeRecord(Index);
5834 if (TypesLoaded[Index].isNull())
5835 return QualType();
5836
5837 TypesLoaded[Index]->setFromAST();
5838 if (DeserializationListener)
5839 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5840 TypesLoaded[Index]);
5841 }
5842
5843 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5844}
5845
5846QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5847 return GetType(getGlobalTypeID(F, LocalID));
5848}
5849
5850serialization::TypeID
5851ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5852 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5853 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5854
5855 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5856 return LocalID;
5857
5858 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5859 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5860 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5861
5862 unsigned GlobalIndex = LocalIndex + I->second;
5863 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5864}
5865
5866TemplateArgumentLocInfo
5867ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5868 TemplateArgument::ArgKind Kind,
5869 const RecordData &Record,
5870 unsigned &Index) {
5871 switch (Kind) {
5872 case TemplateArgument::Expression:
5873 return ReadExpr(F);
5874 case TemplateArgument::Type:
5875 return GetTypeSourceInfo(F, Record, Index);
5876 case TemplateArgument::Template: {
5877 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5878 Index);
5879 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5880 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5881 SourceLocation());
5882 }
5883 case TemplateArgument::TemplateExpansion: {
5884 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5885 Index);
5886 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5887 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5888 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5889 EllipsisLoc);
5890 }
5891 case TemplateArgument::Null:
5892 case TemplateArgument::Integral:
5893 case TemplateArgument::Declaration:
5894 case TemplateArgument::NullPtr:
5895 case TemplateArgument::Pack:
5896 // FIXME: Is this right?
5897 return TemplateArgumentLocInfo();
5898 }
5899 llvm_unreachable("unexpected template argument loc");
5900}
5901
5902TemplateArgumentLoc
5903ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5904 const RecordData &Record, unsigned &Index) {
5905 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5906
5907 if (Arg.getKind() == TemplateArgument::Expression) {
5908 if (Record[Index++]) // bool InfoHasSameExpr.
5909 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5910 }
5911 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5912 Record, Index));
5913}
5914
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005915const ASTTemplateArgumentListInfo*
5916ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5917 const RecordData &Record,
5918 unsigned &Index) {
5919 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5920 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5921 unsigned NumArgsAsWritten = Record[Index++];
5922 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5923 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5924 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5925 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5926}
5927
Guy Benyei11169dd2012-12-18 14:30:41 +00005928Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5929 return GetDecl(ID);
5930}
5931
Richard Smith50895422015-01-31 03:04:55 +00005932template<typename TemplateSpecializationDecl>
5933static void completeRedeclChainForTemplateSpecialization(Decl *D) {
5934 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
5935 TSD->getSpecializedTemplate()->LoadLazySpecializations();
5936}
5937
Richard Smith053f6c62014-05-16 23:01:30 +00005938void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005939 if (NumCurrentElementsDeserializing) {
5940 // We arrange to not care about the complete redeclaration chain while we're
5941 // deserializing. Just remember that the AST has marked this one as complete
5942 // but that it's not actually complete yet, so we know we still need to
5943 // complete it later.
5944 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5945 return;
5946 }
5947
Richard Smith053f6c62014-05-16 23:01:30 +00005948 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5949
Richard Smith053f6c62014-05-16 23:01:30 +00005950 // If this is a named declaration, complete it by looking it up
5951 // within its context.
5952 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00005953 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00005954 // all mergeable entities within it.
5955 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5956 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5957 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00005958 if (!getContext().getLangOpts().CPlusPlus &&
5959 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00005960 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00005961 // the identifier instead. (For C++ modules, we don't store decls
5962 // in the serialized identifier table, so we do the lookup in the TU.)
5963 auto *II = Name.getAsIdentifierInfo();
5964 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00005965 if (II->isOutOfDate())
5966 updateOutOfDateIdentifier(*II);
5967 } else
5968 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00005969 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00005970 // Find all declarations of this kind from the relevant context.
5971 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
5972 auto *DC = cast<DeclContext>(DCDecl);
5973 SmallVector<Decl*, 8> Decls;
5974 FindExternalLexicalDecls(
5975 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
5976 }
Richard Smith053f6c62014-05-16 23:01:30 +00005977 }
5978 }
Richard Smith50895422015-01-31 03:04:55 +00005979
5980 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
5981 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
5982 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
5983 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
5984 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5985 if (auto *Template = FD->getPrimaryTemplate())
5986 Template->LoadLazySpecializations();
5987 }
Richard Smith053f6c62014-05-16 23:01:30 +00005988}
5989
Richard Smithc2bb8182015-03-24 06:36:48 +00005990uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
5991 const RecordData &Record,
5992 unsigned &Idx) {
5993 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
5994 Error("malformed AST file: missing C++ ctor initializers");
5995 return 0;
5996 }
5997
5998 unsigned LocalID = Record[Idx++];
5999 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
6000}
6001
6002CXXCtorInitializer **
6003ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6004 RecordLocation Loc = getLocalBitOffset(Offset);
6005 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6006 SavedStreamPosition SavedPosition(Cursor);
6007 Cursor.JumpToBit(Loc.Offset);
6008 ReadingKindTracker ReadingKind(Read_Decl, *this);
6009
6010 RecordData Record;
6011 unsigned Code = Cursor.ReadCode();
6012 unsigned RecCode = Cursor.readRecord(Code, Record);
6013 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6014 Error("malformed AST file: missing C++ ctor initializers");
6015 return nullptr;
6016 }
6017
6018 unsigned Idx = 0;
6019 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6020}
6021
Richard Smithcd45dbc2014-04-19 03:48:30 +00006022uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6023 const RecordData &Record,
6024 unsigned &Idx) {
6025 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6026 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006027 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006028 }
6029
Guy Benyei11169dd2012-12-18 14:30:41 +00006030 unsigned LocalID = Record[Idx++];
6031 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6032}
6033
6034CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6035 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006036 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006037 SavedStreamPosition SavedPosition(Cursor);
6038 Cursor.JumpToBit(Loc.Offset);
6039 ReadingKindTracker ReadingKind(Read_Decl, *this);
6040 RecordData Record;
6041 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006042 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006043 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006044 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006045 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006046 }
6047
6048 unsigned Idx = 0;
6049 unsigned NumBases = Record[Idx++];
6050 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6051 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6052 for (unsigned I = 0; I != NumBases; ++I)
6053 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6054 return Bases;
6055}
6056
6057serialization::DeclID
6058ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6059 if (LocalID < NUM_PREDEF_DECL_IDS)
6060 return LocalID;
6061
6062 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6063 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6064 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6065
6066 return LocalID + I->second;
6067}
6068
6069bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6070 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006071 // Predefined decls aren't from any module.
6072 if (ID < NUM_PREDEF_DECL_IDS)
6073 return false;
6074
Richard Smithbcda1a92015-07-12 23:51:20 +00006075 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6076 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006077}
6078
Douglas Gregor9f782892013-01-21 15:25:38 +00006079ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006080 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006081 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006082 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6083 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6084 return I->second;
6085}
6086
6087SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6088 if (ID < NUM_PREDEF_DECL_IDS)
6089 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006090
Guy Benyei11169dd2012-12-18 14:30:41 +00006091 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6092
6093 if (Index > DeclsLoaded.size()) {
6094 Error("declaration ID out-of-range for AST file");
6095 return SourceLocation();
6096 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006097
Guy Benyei11169dd2012-12-18 14:30:41 +00006098 if (Decl *D = DeclsLoaded[Index])
6099 return D->getLocation();
6100
6101 unsigned RawLocation = 0;
6102 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6103 return ReadSourceLocation(*Rec.F, RawLocation);
6104}
6105
Richard Smithfe620d22015-03-05 23:24:12 +00006106static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6107 switch (ID) {
6108 case PREDEF_DECL_NULL_ID:
6109 return nullptr;
6110
6111 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6112 return Context.getTranslationUnitDecl();
6113
6114 case PREDEF_DECL_OBJC_ID_ID:
6115 return Context.getObjCIdDecl();
6116
6117 case PREDEF_DECL_OBJC_SEL_ID:
6118 return Context.getObjCSelDecl();
6119
6120 case PREDEF_DECL_OBJC_CLASS_ID:
6121 return Context.getObjCClassDecl();
6122
6123 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6124 return Context.getObjCProtocolDecl();
6125
6126 case PREDEF_DECL_INT_128_ID:
6127 return Context.getInt128Decl();
6128
6129 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6130 return Context.getUInt128Decl();
6131
6132 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6133 return Context.getObjCInstanceTypeDecl();
6134
6135 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6136 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006137
Richard Smith9b88a4c2015-07-27 05:40:23 +00006138 case PREDEF_DECL_VA_LIST_TAG:
6139 return Context.getVaListTagDecl();
6140
Richard Smithf19e1272015-03-07 00:04:49 +00006141 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6142 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006143 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006144 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006145}
6146
Richard Smithcd45dbc2014-04-19 03:48:30 +00006147Decl *ASTReader::GetExistingDecl(DeclID ID) {
6148 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006149 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6150 if (D) {
6151 // Track that we have merged the declaration with ID \p ID into the
6152 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006153 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006154 if (Merged.empty())
6155 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006156 }
Richard Smithfe620d22015-03-05 23:24:12 +00006157 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006158 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006159
Guy Benyei11169dd2012-12-18 14:30:41 +00006160 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6161
6162 if (Index >= DeclsLoaded.size()) {
6163 assert(0 && "declaration ID out-of-range for AST file");
6164 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006165 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006166 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006167
6168 return DeclsLoaded[Index];
6169}
6170
6171Decl *ASTReader::GetDecl(DeclID ID) {
6172 if (ID < NUM_PREDEF_DECL_IDS)
6173 return GetExistingDecl(ID);
6174
6175 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6176
6177 if (Index >= DeclsLoaded.size()) {
6178 assert(0 && "declaration ID out-of-range for AST file");
6179 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006180 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006181 }
6182
Guy Benyei11169dd2012-12-18 14:30:41 +00006183 if (!DeclsLoaded[Index]) {
6184 ReadDeclRecord(ID);
6185 if (DeserializationListener)
6186 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6187 }
6188
6189 return DeclsLoaded[Index];
6190}
6191
6192DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6193 DeclID GlobalID) {
6194 if (GlobalID < NUM_PREDEF_DECL_IDS)
6195 return GlobalID;
6196
6197 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6198 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6199 ModuleFile *Owner = I->second;
6200
6201 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6202 = M.GlobalToLocalDeclIDs.find(Owner);
6203 if (Pos == M.GlobalToLocalDeclIDs.end())
6204 return 0;
6205
6206 return GlobalID - Owner->BaseDeclID + Pos->second;
6207}
6208
6209serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6210 const RecordData &Record,
6211 unsigned &Idx) {
6212 if (Idx >= Record.size()) {
6213 Error("Corrupted AST file");
6214 return 0;
6215 }
6216
6217 return getGlobalDeclID(F, Record[Idx++]);
6218}
6219
6220/// \brief Resolve the offset of a statement into a statement.
6221///
6222/// This operation will read a new statement from the external
6223/// source each time it is called, and is meant to be used via a
6224/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6225Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6226 // Switch case IDs are per Decl.
6227 ClearSwitchCaseIDs();
6228
6229 // Offset here is a global offset across the entire chain.
6230 RecordLocation Loc = getLocalBitOffset(Offset);
6231 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6232 return ReadStmtFromStream(*Loc.F);
6233}
6234
Richard Smith3cb15722015-08-05 22:41:45 +00006235void ASTReader::FindExternalLexicalDecls(
6236 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6237 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006238 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6239
Richard Smith9ccdd932015-08-06 22:14:12 +00006240 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006241 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6242 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6243 auto K = (Decl::Kind)+LexicalDecls[I];
6244 if (!IsKindWeWant(K))
6245 continue;
6246
6247 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6248
6249 // Don't add predefined declarations to the lexical context more
6250 // than once.
6251 if (ID < NUM_PREDEF_DECL_IDS) {
6252 if (PredefsVisited[ID])
6253 continue;
6254
6255 PredefsVisited[ID] = true;
6256 }
6257
6258 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006259 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006260 if (!DC->isDeclInLexicalTraversal(D))
6261 Decls.push_back(D);
6262 }
6263 }
6264 };
6265
6266 if (isa<TranslationUnitDecl>(DC)) {
6267 for (auto Lexical : TULexicalDecls)
6268 Visit(Lexical.first, Lexical.second);
6269 } else {
6270 auto I = LexicalDecls.find(DC);
6271 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006272 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006273 }
6274
Guy Benyei11169dd2012-12-18 14:30:41 +00006275 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006276}
6277
6278namespace {
6279
6280class DeclIDComp {
6281 ASTReader &Reader;
6282 ModuleFile &Mod;
6283
6284public:
6285 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6286
6287 bool operator()(LocalDeclID L, LocalDeclID R) const {
6288 SourceLocation LHS = getLocation(L);
6289 SourceLocation RHS = getLocation(R);
6290 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6291 }
6292
6293 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6294 SourceLocation RHS = getLocation(R);
6295 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6296 }
6297
6298 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6299 SourceLocation LHS = getLocation(L);
6300 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6301 }
6302
6303 SourceLocation getLocation(LocalDeclID ID) const {
6304 return Reader.getSourceManager().getFileLoc(
6305 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6306 }
6307};
6308
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006309}
Guy Benyei11169dd2012-12-18 14:30:41 +00006310
6311void ASTReader::FindFileRegionDecls(FileID File,
6312 unsigned Offset, unsigned Length,
6313 SmallVectorImpl<Decl *> &Decls) {
6314 SourceManager &SM = getSourceManager();
6315
6316 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6317 if (I == FileDeclIDs.end())
6318 return;
6319
6320 FileDeclsInfo &DInfo = I->second;
6321 if (DInfo.Decls.empty())
6322 return;
6323
6324 SourceLocation
6325 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6326 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6327
6328 DeclIDComp DIDComp(*this, *DInfo.Mod);
6329 ArrayRef<serialization::LocalDeclID>::iterator
6330 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6331 BeginLoc, DIDComp);
6332 if (BeginIt != DInfo.Decls.begin())
6333 --BeginIt;
6334
6335 // If we are pointing at a top-level decl inside an objc container, we need
6336 // to backtrack until we find it otherwise we will fail to report that the
6337 // region overlaps with an objc container.
6338 while (BeginIt != DInfo.Decls.begin() &&
6339 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6340 ->isTopLevelDeclInObjCContainer())
6341 --BeginIt;
6342
6343 ArrayRef<serialization::LocalDeclID>::iterator
6344 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6345 EndLoc, DIDComp);
6346 if (EndIt != DInfo.Decls.end())
6347 ++EndIt;
6348
6349 for (ArrayRef<serialization::LocalDeclID>::iterator
6350 DIt = BeginIt; DIt != EndIt; ++DIt)
6351 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6352}
6353
Richard Smith3b637412015-07-14 18:42:41 +00006354/// \brief Retrieve the "definitive" module file for the definition of the
6355/// given declaration context, if there is one.
6356///
6357/// The "definitive" module file is the only place where we need to look to
6358/// find information about the declarations within the given declaration
6359/// context. For example, C++ and Objective-C classes, C structs/unions, and
6360/// Objective-C protocols, categories, and extensions are all defined in a
6361/// single place in the source code, so they have definitive module files
6362/// associated with them. C++ namespaces, on the other hand, can have
6363/// definitions in multiple different module files.
6364///
6365/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6366/// NDEBUG checking.
6367static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6368 ASTReader &Reader) {
6369 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6370 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
6371
6372 return nullptr;
6373}
6374
Guy Benyei11169dd2012-12-18 14:30:41 +00006375namespace {
6376 /// \brief ModuleFile visitor used to perform name lookup into a
6377 /// declaration context.
6378 class DeclContextNameLookupVisitor {
6379 ASTReader &Reader;
Richard Smithf13c68d2015-08-06 21:05:21 +00006380 const DeclContext *Context;
Guy Benyei11169dd2012-12-18 14:30:41 +00006381 DeclarationName Name;
Richard Smith3b637412015-07-14 18:42:41 +00006382 ASTDeclContextNameLookupTrait::DeclNameKey NameKey;
6383 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00006384 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006385 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006386
6387 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006388 DeclContextNameLookupVisitor(ASTReader &Reader,
Richard Smithf13c68d2015-08-06 21:05:21 +00006389 const DeclContext *Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00006390 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006391 SmallVectorImpl<NamedDecl *> &Decls,
6392 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
Richard Smithf13c68d2015-08-06 21:05:21 +00006393 : Reader(Reader), Context(Context), Name(Name),
Richard Smith3b637412015-07-14 18:42:41 +00006394 NameKey(ASTDeclContextNameLookupTrait::GetInternalKey(Name)),
6395 NameHash(ASTDeclContextNameLookupTrait::ComputeHash(NameKey)),
6396 Decls(Decls), DeclSet(DeclSet) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006397
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006398 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006399 // Check whether we have any visible declaration information for
6400 // this context in this module.
Richard Smithf13c68d2015-08-06 21:05:21 +00006401 auto Info = M.DeclContextInfos.find(Context);
6402 if (Info == M.DeclContextInfos.end() || !Info->second.NameLookupTableData)
Guy Benyei11169dd2012-12-18 14:30:41 +00006403 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006404
Guy Benyei11169dd2012-12-18 14:30:41 +00006405 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006406 ASTDeclContextNameLookupTable *LookupTable =
Richard Smithf13c68d2015-08-06 21:05:21 +00006407 Info->second.NameLookupTableData;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006408 ASTDeclContextNameLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00006409 LookupTable->find_hashed(NameKey, NameHash);
Guy Benyei11169dd2012-12-18 14:30:41 +00006410 if (Pos == LookupTable->end())
6411 return false;
6412
6413 bool FoundAnything = false;
6414 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6415 for (; Data.first != Data.second; ++Data.first) {
Richard Smithbdf2d932015-07-30 03:37:16 +00006416 NamedDecl *ND = Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
Guy Benyei11169dd2012-12-18 14:30:41 +00006417 if (!ND)
6418 continue;
6419
Richard Smithbdf2d932015-07-30 03:37:16 +00006420 if (ND->getDeclName() != Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006421 // A name might be null because the decl's redeclarable part is
6422 // currently read before reading its name. The lookup is triggered by
6423 // building that decl (likely indirectly), and so it is later in the
6424 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006425 // FIXME: This should not happen; deserializing declarations should
6426 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006427 continue;
6428 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006429
Guy Benyei11169dd2012-12-18 14:30:41 +00006430 // Record this declaration.
6431 FoundAnything = true;
Richard Smithbdf2d932015-07-30 03:37:16 +00006432 if (DeclSet.insert(ND).second)
6433 Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006434 }
6435
6436 return FoundAnything;
6437 }
6438 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006439}
Guy Benyei11169dd2012-12-18 14:30:41 +00006440
Richard Smith9ce12e32013-02-07 03:30:24 +00006441bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006442ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6443 DeclarationName Name) {
6444 assert(DC->hasExternalVisibleStorage() &&
6445 "DeclContext has no visible decls in storage");
6446 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006447 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006448
Richard Smith8c913ec2014-08-14 02:21:01 +00006449 Deserializing LookupResults(this);
6450
Guy Benyei11169dd2012-12-18 14:30:41 +00006451 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006452 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006453
Richard Smithf13c68d2015-08-06 21:05:21 +00006454 DeclContextNameLookupVisitor Visitor(*this, DC, Name, Decls, DeclSet);
Richard Smith8c913ec2014-08-14 02:21:01 +00006455
Richard Smithf13c68d2015-08-06 21:05:21 +00006456 // If we can definitively determine which module file to look into,
6457 // only look there. Otherwise, look in all module files.
6458 if (ModuleFile *Definitive = getDefinitiveModuleFileFor(DC, *this))
6459 Visitor(*Definitive);
6460 else
6461 ModuleMgr.visit(Visitor);
Richard Smithcd45dbc2014-04-19 03:48:30 +00006462
Guy Benyei11169dd2012-12-18 14:30:41 +00006463 ++NumVisibleDeclContextsRead;
6464 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006465 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006466}
6467
6468namespace {
6469 /// \brief ModuleFile visitor used to retrieve all visible names in a
6470 /// declaration context.
6471 class DeclContextAllNamesVisitor {
6472 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006473 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006474 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006475 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006476 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006477
6478 public:
6479 DeclContextAllNamesVisitor(ASTReader &Reader,
6480 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006481 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006482 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006483
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006484 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006485 // Check whether we have any visible declaration information for
6486 // this context in this module.
6487 ModuleFile::DeclContextInfosMap::iterator Info;
6488 bool FoundInfo = false;
Richard Smithbdf2d932015-07-30 03:37:16 +00006489 for (unsigned I = 0, N = Contexts.size(); I != N; ++I) {
6490 Info = M.DeclContextInfos.find(Contexts[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006491 if (Info != M.DeclContextInfos.end() &&
6492 Info->second.NameLookupTableData) {
6493 FoundInfo = true;
6494 break;
6495 }
6496 }
6497
6498 if (!FoundInfo)
6499 return false;
6500
Richard Smith52e3fba2014-03-11 07:17:35 +00006501 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006502 Info->second.NameLookupTableData;
6503 bool FoundAnything = false;
6504 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006505 I = LookupTable->data_begin(), E = LookupTable->data_end();
6506 I != E;
6507 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006508 ASTDeclContextNameLookupTrait::data_type Data = *I;
6509 for (; Data.first != Data.second; ++Data.first) {
Richard Smithbdf2d932015-07-30 03:37:16 +00006510 NamedDecl *ND = Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
Guy Benyei11169dd2012-12-18 14:30:41 +00006511 if (!ND)
6512 continue;
6513
6514 // Record this declaration.
6515 FoundAnything = true;
Richard Smithbdf2d932015-07-30 03:37:16 +00006516 if (DeclSet.insert(ND).second)
6517 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006518 }
6519 }
6520
Richard Smithbdf2d932015-07-30 03:37:16 +00006521 return FoundAnything && !VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006522 }
6523 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006524}
Guy Benyei11169dd2012-12-18 14:30:41 +00006525
6526void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6527 if (!DC->hasExternalVisibleStorage())
6528 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006529 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006530
6531 // Compute the declaration contexts we need to look into. Multiple such
6532 // declaration contexts occur when two declaration contexts from disjoint
6533 // modules get merged, e.g., when two namespaces with the same name are
6534 // independently defined in separate modules.
6535 SmallVector<const DeclContext *, 2> Contexts;
6536 Contexts.push_back(DC);
6537
6538 if (DC->isNamespace()) {
Richard Smith5fc18a92015-07-12 23:43:21 +00006539 KeyDeclsMap::iterator Key =
6540 KeyDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6541 if (Key != KeyDecls.end()) {
6542 for (unsigned I = 0, N = Key->second.size(); I != N; ++I)
6543 Contexts.push_back(cast<DeclContext>(GetDecl(Key->second[I])));
Guy Benyei11169dd2012-12-18 14:30:41 +00006544 }
6545 }
6546
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006547 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6548 /*VisitAll=*/DC->isFileContext());
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006549 ModuleMgr.visit(Visitor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006550 ++NumVisibleDeclContextsRead;
6551
Craig Topper79be4cd2013-07-05 04:33:53 +00006552 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006553 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6554 }
6555 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6556}
6557
6558/// \brief Under non-PCH compilation the consumer receives the objc methods
6559/// before receiving the implementation, and codegen depends on this.
6560/// We simulate this by deserializing and passing to consumer the methods of the
6561/// implementation before passing the deserialized implementation decl.
6562static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6563 ASTConsumer *Consumer) {
6564 assert(ImplD && Consumer);
6565
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006566 for (auto *I : ImplD->methods())
6567 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006568
6569 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6570}
6571
6572void ASTReader::PassInterestingDeclsToConsumer() {
6573 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006574
6575 if (PassingDeclsToConsumer)
6576 return;
6577
6578 // Guard variable to avoid recursively redoing the process of passing
6579 // decls to consumer.
6580 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6581 true);
6582
Richard Smith9e2341d2015-03-23 03:25:59 +00006583 // Ensure that we've loaded all potentially-interesting declarations
6584 // that need to be eagerly loaded.
6585 for (auto ID : EagerlyDeserializedDecls)
6586 GetDecl(ID);
6587 EagerlyDeserializedDecls.clear();
6588
Guy Benyei11169dd2012-12-18 14:30:41 +00006589 while (!InterestingDecls.empty()) {
6590 Decl *D = InterestingDecls.front();
6591 InterestingDecls.pop_front();
6592
6593 PassInterestingDeclToConsumer(D);
6594 }
6595}
6596
6597void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6598 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6599 PassObjCImplDeclToConsumer(ImplD, Consumer);
6600 else
6601 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6602}
6603
6604void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6605 this->Consumer = Consumer;
6606
Richard Smith9e2341d2015-03-23 03:25:59 +00006607 if (Consumer)
6608 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006609
6610 if (DeserializationListener)
6611 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006612}
6613
6614void ASTReader::PrintStats() {
6615 std::fprintf(stderr, "*** AST File Statistics:\n");
6616
6617 unsigned NumTypesLoaded
6618 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6619 QualType());
6620 unsigned NumDeclsLoaded
6621 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006622 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006623 unsigned NumIdentifiersLoaded
6624 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6625 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006626 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006627 unsigned NumMacrosLoaded
6628 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6629 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006630 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006631 unsigned NumSelectorsLoaded
6632 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6633 SelectorsLoaded.end(),
6634 Selector());
6635
6636 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6637 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6638 NumSLocEntriesRead, TotalNumSLocEntries,
6639 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6640 if (!TypesLoaded.empty())
6641 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6642 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6643 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6644 if (!DeclsLoaded.empty())
6645 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6646 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6647 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6648 if (!IdentifiersLoaded.empty())
6649 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6650 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6651 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6652 if (!MacrosLoaded.empty())
6653 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6654 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6655 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6656 if (!SelectorsLoaded.empty())
6657 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6658 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6659 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6660 if (TotalNumStatements)
6661 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6662 NumStatementsRead, TotalNumStatements,
6663 ((float)NumStatementsRead/TotalNumStatements * 100));
6664 if (TotalNumMacros)
6665 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6666 NumMacrosRead, TotalNumMacros,
6667 ((float)NumMacrosRead/TotalNumMacros * 100));
6668 if (TotalLexicalDeclContexts)
6669 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6670 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6671 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6672 * 100));
6673 if (TotalVisibleDeclContexts)
6674 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6675 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6676 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6677 * 100));
6678 if (TotalNumMethodPoolEntries) {
6679 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6680 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6681 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6682 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006683 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006684 if (NumMethodPoolLookups) {
6685 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6686 NumMethodPoolHits, NumMethodPoolLookups,
6687 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6688 }
6689 if (NumMethodPoolTableLookups) {
6690 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6691 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6692 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6693 * 100.0));
6694 }
6695
Douglas Gregor00a50f72013-01-25 00:38:33 +00006696 if (NumIdentifierLookupHits) {
6697 std::fprintf(stderr,
6698 " %u / %u identifier table lookups succeeded (%f%%)\n",
6699 NumIdentifierLookupHits, NumIdentifierLookups,
6700 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6701 }
6702
Douglas Gregore060e572013-01-25 01:03:03 +00006703 if (GlobalIndex) {
6704 std::fprintf(stderr, "\n");
6705 GlobalIndex->printStats();
6706 }
6707
Guy Benyei11169dd2012-12-18 14:30:41 +00006708 std::fprintf(stderr, "\n");
6709 dump();
6710 std::fprintf(stderr, "\n");
6711}
6712
6713template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6714static void
6715dumpModuleIDMap(StringRef Name,
6716 const ContinuousRangeMap<Key, ModuleFile *,
6717 InitialCapacity> &Map) {
6718 if (Map.begin() == Map.end())
6719 return;
6720
6721 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6722 llvm::errs() << Name << ":\n";
6723 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6724 I != IEnd; ++I) {
6725 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6726 << "\n";
6727 }
6728}
6729
6730void ASTReader::dump() {
6731 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6732 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6733 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6734 dumpModuleIDMap("Global type map", GlobalTypeMap);
6735 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6736 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6737 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6738 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6739 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6740 dumpModuleIDMap("Global preprocessed entity map",
6741 GlobalPreprocessedEntityMap);
6742
6743 llvm::errs() << "\n*** PCH/Modules Loaded:";
6744 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6745 MEnd = ModuleMgr.end();
6746 M != MEnd; ++M)
6747 (*M)->dump();
6748}
6749
6750/// Return the amount of memory used by memory buffers, breaking down
6751/// by heap-backed versus mmap'ed memory.
6752void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6753 for (ModuleConstIterator I = ModuleMgr.begin(),
6754 E = ModuleMgr.end(); I != E; ++I) {
6755 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6756 size_t bytes = buf->getBufferSize();
6757 switch (buf->getBufferKind()) {
6758 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6759 sizes.malloc_bytes += bytes;
6760 break;
6761 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6762 sizes.mmap_bytes += bytes;
6763 break;
6764 }
6765 }
6766 }
6767}
6768
6769void ASTReader::InitializeSema(Sema &S) {
6770 SemaObj = &S;
6771 S.addExternalSource(this);
6772
6773 // Makes sure any declarations that were deserialized "too early"
6774 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006775 for (uint64_t ID : PreloadedDeclIDs) {
6776 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6777 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006778 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006779 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006780
Richard Smith3d8e97e2013-10-18 06:54:39 +00006781 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006782 if (!FPPragmaOptions.empty()) {
6783 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6784 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6785 }
6786
Richard Smith3d8e97e2013-10-18 06:54:39 +00006787 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006788 if (!OpenCLExtensions.empty()) {
6789 unsigned I = 0;
6790#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6791#include "clang/Basic/OpenCLExtensions.def"
6792
6793 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6794 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006795
6796 UpdateSema();
6797}
6798
6799void ASTReader::UpdateSema() {
6800 assert(SemaObj && "no Sema to update");
6801
6802 // Load the offsets of the declarations that Sema references.
6803 // They will be lazily deserialized when needed.
6804 if (!SemaDeclRefs.empty()) {
6805 assert(SemaDeclRefs.size() % 2 == 0);
6806 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6807 if (!SemaObj->StdNamespace)
6808 SemaObj->StdNamespace = SemaDeclRefs[I];
6809 if (!SemaObj->StdBadAlloc)
6810 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6811 }
6812 SemaDeclRefs.clear();
6813 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006814
6815 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6816 // encountered the pragma in the source.
6817 if(OptimizeOffPragmaLocation.isValid())
6818 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006819}
6820
Richard Smitha8d5b6a2015-07-17 19:51:03 +00006821IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006822 // Note that we are loading an identifier.
6823 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006824
Douglas Gregor7211ac12013-01-25 23:32:03 +00006825 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006826 NumIdentifierLookups,
6827 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006828
6829 // We don't need to do identifier table lookups in C++ modules (we preload
6830 // all interesting declarations, and don't need to use the scope for name
6831 // lookups). Perform the lookup in PCH files, though, since we don't build
6832 // a complete initial identifier table if we're carrying on from a PCH.
6833 if (Context.getLangOpts().CPlusPlus) {
6834 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006835 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00006836 break;
6837 } else {
6838 // If there is a global index, look there first to determine which modules
6839 // provably do not have any results for this identifier.
6840 GlobalModuleIndex::HitSet Hits;
6841 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
6842 if (!loadGlobalIndex()) {
6843 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6844 HitsPtr = &Hits;
6845 }
6846 }
6847
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006848 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006849 }
6850
Guy Benyei11169dd2012-12-18 14:30:41 +00006851 IdentifierInfo *II = Visitor.getIdentifierInfo();
6852 markIdentifierUpToDate(II);
6853 return II;
6854}
6855
6856namespace clang {
6857 /// \brief An identifier-lookup iterator that enumerates all of the
6858 /// identifiers stored within a set of AST files.
6859 class ASTIdentifierIterator : public IdentifierIterator {
6860 /// \brief The AST reader whose identifiers are being enumerated.
6861 const ASTReader &Reader;
6862
6863 /// \brief The current index into the chain of AST files stored in
6864 /// the AST reader.
6865 unsigned Index;
6866
6867 /// \brief The current position within the identifier lookup table
6868 /// of the current AST file.
6869 ASTIdentifierLookupTable::key_iterator Current;
6870
6871 /// \brief The end position within the identifier lookup table of
6872 /// the current AST file.
6873 ASTIdentifierLookupTable::key_iterator End;
6874
6875 public:
6876 explicit ASTIdentifierIterator(const ASTReader &Reader);
6877
Craig Topper3e89dfe2014-03-13 02:13:41 +00006878 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006879 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006880}
Guy Benyei11169dd2012-12-18 14:30:41 +00006881
6882ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6883 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6884 ASTIdentifierLookupTable *IdTable
6885 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6886 Current = IdTable->key_begin();
6887 End = IdTable->key_end();
6888}
6889
6890StringRef ASTIdentifierIterator::Next() {
6891 while (Current == End) {
6892 // If we have exhausted all of our AST files, we're done.
6893 if (Index == 0)
6894 return StringRef();
6895
6896 --Index;
6897 ASTIdentifierLookupTable *IdTable
6898 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6899 IdentifierLookupTable;
6900 Current = IdTable->key_begin();
6901 End = IdTable->key_end();
6902 }
6903
6904 // We have any identifiers remaining in the current AST file; return
6905 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006906 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006907 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006908 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006909}
6910
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006911IdentifierIterator *ASTReader::getIdentifiers() {
6912 if (!loadGlobalIndex())
6913 return GlobalIndex->createIdentifierIterator();
6914
Guy Benyei11169dd2012-12-18 14:30:41 +00006915 return new ASTIdentifierIterator(*this);
6916}
6917
6918namespace clang { namespace serialization {
6919 class ReadMethodPoolVisitor {
6920 ASTReader &Reader;
6921 Selector Sel;
6922 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006923 unsigned InstanceBits;
6924 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006925 bool InstanceHasMoreThanOneDecl;
6926 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006927 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6928 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006929
6930 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00006931 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00006932 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00006933 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00006934 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
6935 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00006936
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006937 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006938 if (!M.SelectorLookupTable)
6939 return false;
6940
6941 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00006942 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00006943 return true;
6944
Richard Smithbdf2d932015-07-30 03:37:16 +00006945 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006946 ASTSelectorLookupTable *PoolTable
6947 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00006948 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00006949 if (Pos == PoolTable->end())
6950 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006951
Richard Smithbdf2d932015-07-30 03:37:16 +00006952 ++Reader.NumMethodPoolTableHits;
6953 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006954 // FIXME: Not quite happy with the statistics here. We probably should
6955 // disable this tracking when called via LoadSelector.
6956 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00006957 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006958 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00006959 if (Reader.DeserializationListener)
6960 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006961
Richard Smithbdf2d932015-07-30 03:37:16 +00006962 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6963 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
6964 InstanceBits = Data.InstanceBits;
6965 FactoryBits = Data.FactoryBits;
6966 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
6967 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00006968 return true;
6969 }
6970
6971 /// \brief Retrieve the instance methods found by this visitor.
6972 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6973 return InstanceMethods;
6974 }
6975
6976 /// \brief Retrieve the instance methods found by this visitor.
6977 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6978 return FactoryMethods;
6979 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006980
6981 unsigned getInstanceBits() const { return InstanceBits; }
6982 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00006983 bool instanceHasMoreThanOneDecl() const {
6984 return InstanceHasMoreThanOneDecl;
6985 }
6986 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006987 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006988} } // end namespace clang::serialization
Guy Benyei11169dd2012-12-18 14:30:41 +00006989
6990/// \brief Add the given set of methods to the method list.
6991static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6992 ObjCMethodList &List) {
6993 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6994 S.addMethodToGlobalList(&List, Methods[I]);
6995 }
6996}
6997
6998void ASTReader::ReadMethodPool(Selector Sel) {
6999 // Get the selector generation and update it to the current generation.
7000 unsigned &Generation = SelectorGeneration[Sel];
7001 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007002 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007003
7004 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007005 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007006 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007007 ModuleMgr.visit(Visitor);
7008
Guy Benyei11169dd2012-12-18 14:30:41 +00007009 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007010 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007011 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007012
7013 ++NumMethodPoolHits;
7014
Guy Benyei11169dd2012-12-18 14:30:41 +00007015 if (!getSema())
7016 return;
7017
7018 Sema &S = *getSema();
7019 Sema::GlobalMethodPool::iterator Pos
7020 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007021
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007022 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007023 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007024 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007025 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007026
7027 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7028 // when building a module we keep every method individually and may need to
7029 // update hasMoreThanOneDecl as we add the methods.
7030 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7031 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007032}
7033
7034void ASTReader::ReadKnownNamespaces(
7035 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7036 Namespaces.clear();
7037
7038 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7039 if (NamespaceDecl *Namespace
7040 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7041 Namespaces.push_back(Namespace);
7042 }
7043}
7044
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007045void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007046 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007047 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7048 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007049 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007050 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007051 Undefined.insert(std::make_pair(D, Loc));
7052 }
7053}
Nick Lewycky8334af82013-01-26 00:35:08 +00007054
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007055void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7056 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7057 Exprs) {
7058 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7059 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7060 uint64_t Count = DelayedDeleteExprs[Idx++];
7061 for (uint64_t C = 0; C < Count; ++C) {
7062 SourceLocation DeleteLoc =
7063 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7064 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7065 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7066 }
7067 }
7068}
7069
Guy Benyei11169dd2012-12-18 14:30:41 +00007070void ASTReader::ReadTentativeDefinitions(
7071 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7072 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7073 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7074 if (Var)
7075 TentativeDefs.push_back(Var);
7076 }
7077 TentativeDefinitions.clear();
7078}
7079
7080void ASTReader::ReadUnusedFileScopedDecls(
7081 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7082 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7083 DeclaratorDecl *D
7084 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7085 if (D)
7086 Decls.push_back(D);
7087 }
7088 UnusedFileScopedDecls.clear();
7089}
7090
7091void ASTReader::ReadDelegatingConstructors(
7092 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7093 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7094 CXXConstructorDecl *D
7095 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7096 if (D)
7097 Decls.push_back(D);
7098 }
7099 DelegatingCtorDecls.clear();
7100}
7101
7102void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7103 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7104 TypedefNameDecl *D
7105 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7106 if (D)
7107 Decls.push_back(D);
7108 }
7109 ExtVectorDecls.clear();
7110}
7111
Nico Weber72889432014-09-06 01:25:55 +00007112void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7113 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7114 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7115 ++I) {
7116 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7117 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7118 if (D)
7119 Decls.insert(D);
7120 }
7121 UnusedLocalTypedefNameCandidates.clear();
7122}
7123
Guy Benyei11169dd2012-12-18 14:30:41 +00007124void ASTReader::ReadReferencedSelectors(
7125 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7126 if (ReferencedSelectorsData.empty())
7127 return;
7128
7129 // If there are @selector references added them to its pool. This is for
7130 // implementation of -Wselector.
7131 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7132 unsigned I = 0;
7133 while (I < DataSize) {
7134 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7135 SourceLocation SelLoc
7136 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7137 Sels.push_back(std::make_pair(Sel, SelLoc));
7138 }
7139 ReferencedSelectorsData.clear();
7140}
7141
7142void ASTReader::ReadWeakUndeclaredIdentifiers(
7143 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7144 if (WeakUndeclaredIdentifiers.empty())
7145 return;
7146
7147 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7148 IdentifierInfo *WeakId
7149 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7150 IdentifierInfo *AliasId
7151 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7152 SourceLocation Loc
7153 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7154 bool Used = WeakUndeclaredIdentifiers[I++];
7155 WeakInfo WI(AliasId, Loc);
7156 WI.setUsed(Used);
7157 WeakIDs.push_back(std::make_pair(WeakId, WI));
7158 }
7159 WeakUndeclaredIdentifiers.clear();
7160}
7161
7162void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7163 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7164 ExternalVTableUse VT;
7165 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7166 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7167 VT.DefinitionRequired = VTableUses[Idx++];
7168 VTables.push_back(VT);
7169 }
7170
7171 VTableUses.clear();
7172}
7173
7174void ASTReader::ReadPendingInstantiations(
7175 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7176 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7177 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7178 SourceLocation Loc
7179 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7180
7181 Pending.push_back(std::make_pair(D, Loc));
7182 }
7183 PendingInstantiations.clear();
7184}
7185
Richard Smithe40f2ba2013-08-07 21:41:30 +00007186void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007187 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007188 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7189 /* In loop */) {
7190 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7191
7192 LateParsedTemplate *LT = new LateParsedTemplate;
7193 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7194
7195 ModuleFile *F = getOwningModuleFile(LT->D);
7196 assert(F && "No module");
7197
7198 unsigned TokN = LateParsedTemplates[Idx++];
7199 LT->Toks.reserve(TokN);
7200 for (unsigned T = 0; T < TokN; ++T)
7201 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7202
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007203 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007204 }
7205
7206 LateParsedTemplates.clear();
7207}
7208
Guy Benyei11169dd2012-12-18 14:30:41 +00007209void ASTReader::LoadSelector(Selector Sel) {
7210 // It would be complicated to avoid reading the methods anyway. So don't.
7211 ReadMethodPool(Sel);
7212}
7213
7214void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7215 assert(ID && "Non-zero identifier ID required");
7216 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7217 IdentifiersLoaded[ID - 1] = II;
7218 if (DeserializationListener)
7219 DeserializationListener->IdentifierRead(ID, II);
7220}
7221
7222/// \brief Set the globally-visible declarations associated with the given
7223/// identifier.
7224///
7225/// If the AST reader is currently in a state where the given declaration IDs
7226/// cannot safely be resolved, they are queued until it is safe to resolve
7227/// them.
7228///
7229/// \param II an IdentifierInfo that refers to one or more globally-visible
7230/// declarations.
7231///
7232/// \param DeclIDs the set of declaration IDs with the name @p II that are
7233/// visible at global scope.
7234///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007235/// \param Decls if non-null, this vector will be populated with the set of
7236/// deserialized declarations. These declarations will not be pushed into
7237/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007238void
7239ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7240 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007241 SmallVectorImpl<Decl *> *Decls) {
7242 if (NumCurrentElementsDeserializing && !Decls) {
7243 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007244 return;
7245 }
7246
7247 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007248 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007249 // Queue this declaration so that it will be added to the
7250 // translation unit scope and identifier's declaration chain
7251 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007252 PreloadedDeclIDs.push_back(DeclIDs[I]);
7253 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007254 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007255
7256 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7257
7258 // If we're simply supposed to record the declarations, do so now.
7259 if (Decls) {
7260 Decls->push_back(D);
7261 continue;
7262 }
7263
7264 // Introduce this declaration into the translation-unit scope
7265 // and add it to the declaration chain for this identifier, so
7266 // that (unqualified) name lookup will find it.
7267 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007268 }
7269}
7270
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007271IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007272 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007273 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007274
7275 if (IdentifiersLoaded.empty()) {
7276 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007277 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007278 }
7279
7280 ID -= 1;
7281 if (!IdentifiersLoaded[ID]) {
7282 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7283 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7284 ModuleFile *M = I->second;
7285 unsigned Index = ID - M->BaseIdentifierID;
7286 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7287
7288 // All of the strings in the AST file are preceded by a 16-bit length.
7289 // Extract that 16-bit length to avoid having to execute strlen().
7290 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7291 // unsigned integers. This is important to avoid integer overflow when
7292 // we cast them to 'unsigned'.
7293 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7294 unsigned StrLen = (((unsigned) StrLenPtr[0])
7295 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007296 IdentifiersLoaded[ID]
7297 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007298 if (DeserializationListener)
7299 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7300 }
7301
7302 return IdentifiersLoaded[ID];
7303}
7304
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007305IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7306 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007307}
7308
7309IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7310 if (LocalID < NUM_PREDEF_IDENT_IDS)
7311 return LocalID;
7312
7313 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7314 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7315 assert(I != M.IdentifierRemap.end()
7316 && "Invalid index into identifier index remap");
7317
7318 return LocalID + I->second;
7319}
7320
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007321MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007322 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007323 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007324
7325 if (MacrosLoaded.empty()) {
7326 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007327 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007328 }
7329
7330 ID -= NUM_PREDEF_MACRO_IDS;
7331 if (!MacrosLoaded[ID]) {
7332 GlobalMacroMapType::iterator I
7333 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7334 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7335 ModuleFile *M = I->second;
7336 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007337 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7338
7339 if (DeserializationListener)
7340 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7341 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007342 }
7343
7344 return MacrosLoaded[ID];
7345}
7346
7347MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7348 if (LocalID < NUM_PREDEF_MACRO_IDS)
7349 return LocalID;
7350
7351 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7352 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7353 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7354
7355 return LocalID + I->second;
7356}
7357
7358serialization::SubmoduleID
7359ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7360 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7361 return LocalID;
7362
7363 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7364 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7365 assert(I != M.SubmoduleRemap.end()
7366 && "Invalid index into submodule index remap");
7367
7368 return LocalID + I->second;
7369}
7370
7371Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7372 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7373 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007374 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007375 }
7376
7377 if (GlobalID > SubmodulesLoaded.size()) {
7378 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007379 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007380 }
7381
7382 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7383}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007384
7385Module *ASTReader::getModule(unsigned ID) {
7386 return getSubmodule(ID);
7387}
7388
Adrian Prantl15bcf702015-06-30 17:39:43 +00007389ExternalASTSource::ASTSourceDescriptor
7390ASTReader::getSourceDescriptor(const Module &M) {
7391 StringRef Dir, Filename;
7392 if (M.Directory)
7393 Dir = M.Directory->getName();
7394 if (auto *File = M.getASTFile())
7395 Filename = File->getName();
7396 return ASTReader::ASTSourceDescriptor{
7397 M.getFullModuleName(), Dir, Filename,
7398 M.Signature
7399 };
7400}
7401
7402llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7403ASTReader::getSourceDescriptor(unsigned ID) {
7404 if (const Module *M = getSubmodule(ID))
7405 return getSourceDescriptor(*M);
7406
7407 // If there is only a single PCH, return it instead.
7408 // Chained PCH are not suported.
7409 if (ModuleMgr.size() == 1) {
7410 ModuleFile &MF = ModuleMgr.getPrimaryModule();
7411 return ASTReader::ASTSourceDescriptor{
7412 MF.OriginalSourceFileName, MF.OriginalDir,
7413 MF.FileName,
7414 MF.Signature
7415 };
7416 }
7417 return None;
7418}
7419
Guy Benyei11169dd2012-12-18 14:30:41 +00007420Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7421 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7422}
7423
7424Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7425 if (ID == 0)
7426 return Selector();
7427
7428 if (ID > SelectorsLoaded.size()) {
7429 Error("selector ID out of range in AST file");
7430 return Selector();
7431 }
7432
Craig Toppera13603a2014-05-22 05:54:18 +00007433 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007434 // Load this selector from the selector table.
7435 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7436 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7437 ModuleFile &M = *I->second;
7438 ASTSelectorLookupTrait Trait(*this, M);
7439 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7440 SelectorsLoaded[ID - 1] =
7441 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7442 if (DeserializationListener)
7443 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7444 }
7445
7446 return SelectorsLoaded[ID - 1];
7447}
7448
7449Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7450 return DecodeSelector(ID);
7451}
7452
7453uint32_t ASTReader::GetNumExternalSelectors() {
7454 // ID 0 (the null selector) is considered an external selector.
7455 return getTotalNumSelectors() + 1;
7456}
7457
7458serialization::SelectorID
7459ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7460 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7461 return LocalID;
7462
7463 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7464 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7465 assert(I != M.SelectorRemap.end()
7466 && "Invalid index into selector index remap");
7467
7468 return LocalID + I->second;
7469}
7470
7471DeclarationName
7472ASTReader::ReadDeclarationName(ModuleFile &F,
7473 const RecordData &Record, unsigned &Idx) {
7474 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7475 switch (Kind) {
7476 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007477 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007478
7479 case DeclarationName::ObjCZeroArgSelector:
7480 case DeclarationName::ObjCOneArgSelector:
7481 case DeclarationName::ObjCMultiArgSelector:
7482 return DeclarationName(ReadSelector(F, Record, Idx));
7483
7484 case DeclarationName::CXXConstructorName:
7485 return Context.DeclarationNames.getCXXConstructorName(
7486 Context.getCanonicalType(readType(F, Record, Idx)));
7487
7488 case DeclarationName::CXXDestructorName:
7489 return Context.DeclarationNames.getCXXDestructorName(
7490 Context.getCanonicalType(readType(F, Record, Idx)));
7491
7492 case DeclarationName::CXXConversionFunctionName:
7493 return Context.DeclarationNames.getCXXConversionFunctionName(
7494 Context.getCanonicalType(readType(F, Record, Idx)));
7495
7496 case DeclarationName::CXXOperatorName:
7497 return Context.DeclarationNames.getCXXOperatorName(
7498 (OverloadedOperatorKind)Record[Idx++]);
7499
7500 case DeclarationName::CXXLiteralOperatorName:
7501 return Context.DeclarationNames.getCXXLiteralOperatorName(
7502 GetIdentifierInfo(F, Record, Idx));
7503
7504 case DeclarationName::CXXUsingDirective:
7505 return DeclarationName::getUsingDirectiveName();
7506 }
7507
7508 llvm_unreachable("Invalid NameKind!");
7509}
7510
7511void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7512 DeclarationNameLoc &DNLoc,
7513 DeclarationName Name,
7514 const RecordData &Record, unsigned &Idx) {
7515 switch (Name.getNameKind()) {
7516 case DeclarationName::CXXConstructorName:
7517 case DeclarationName::CXXDestructorName:
7518 case DeclarationName::CXXConversionFunctionName:
7519 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7520 break;
7521
7522 case DeclarationName::CXXOperatorName:
7523 DNLoc.CXXOperatorName.BeginOpNameLoc
7524 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7525 DNLoc.CXXOperatorName.EndOpNameLoc
7526 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7527 break;
7528
7529 case DeclarationName::CXXLiteralOperatorName:
7530 DNLoc.CXXLiteralOperatorName.OpNameLoc
7531 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7532 break;
7533
7534 case DeclarationName::Identifier:
7535 case DeclarationName::ObjCZeroArgSelector:
7536 case DeclarationName::ObjCOneArgSelector:
7537 case DeclarationName::ObjCMultiArgSelector:
7538 case DeclarationName::CXXUsingDirective:
7539 break;
7540 }
7541}
7542
7543void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7544 DeclarationNameInfo &NameInfo,
7545 const RecordData &Record, unsigned &Idx) {
7546 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7547 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7548 DeclarationNameLoc DNLoc;
7549 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7550 NameInfo.setInfo(DNLoc);
7551}
7552
7553void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7554 const RecordData &Record, unsigned &Idx) {
7555 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7556 unsigned NumTPLists = Record[Idx++];
7557 Info.NumTemplParamLists = NumTPLists;
7558 if (NumTPLists) {
7559 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7560 for (unsigned i=0; i != NumTPLists; ++i)
7561 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7562 }
7563}
7564
7565TemplateName
7566ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7567 unsigned &Idx) {
7568 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7569 switch (Kind) {
7570 case TemplateName::Template:
7571 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7572
7573 case TemplateName::OverloadedTemplate: {
7574 unsigned size = Record[Idx++];
7575 UnresolvedSet<8> Decls;
7576 while (size--)
7577 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7578
7579 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7580 }
7581
7582 case TemplateName::QualifiedTemplate: {
7583 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7584 bool hasTemplKeyword = Record[Idx++];
7585 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7586 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7587 }
7588
7589 case TemplateName::DependentTemplate: {
7590 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7591 if (Record[Idx++]) // isIdentifier
7592 return Context.getDependentTemplateName(NNS,
7593 GetIdentifierInfo(F, Record,
7594 Idx));
7595 return Context.getDependentTemplateName(NNS,
7596 (OverloadedOperatorKind)Record[Idx++]);
7597 }
7598
7599 case TemplateName::SubstTemplateTemplateParm: {
7600 TemplateTemplateParmDecl *param
7601 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7602 if (!param) return TemplateName();
7603 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7604 return Context.getSubstTemplateTemplateParm(param, replacement);
7605 }
7606
7607 case TemplateName::SubstTemplateTemplateParmPack: {
7608 TemplateTemplateParmDecl *Param
7609 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7610 if (!Param)
7611 return TemplateName();
7612
7613 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7614 if (ArgPack.getKind() != TemplateArgument::Pack)
7615 return TemplateName();
7616
7617 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7618 }
7619 }
7620
7621 llvm_unreachable("Unhandled template name kind!");
7622}
7623
Richard Smith2bb3c342015-08-09 01:05:31 +00007624TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
7625 const RecordData &Record,
7626 unsigned &Idx,
7627 bool Canonicalize) {
7628 if (Canonicalize) {
7629 // The caller wants a canonical template argument. Sometimes the AST only
7630 // wants template arguments in canonical form (particularly as the template
7631 // argument lists of template specializations) so ensure we preserve that
7632 // canonical form across serialization.
7633 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
7634 return Context.getCanonicalTemplateArgument(Arg);
7635 }
7636
Guy Benyei11169dd2012-12-18 14:30:41 +00007637 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7638 switch (Kind) {
7639 case TemplateArgument::Null:
7640 return TemplateArgument();
7641 case TemplateArgument::Type:
7642 return TemplateArgument(readType(F, Record, Idx));
7643 case TemplateArgument::Declaration: {
7644 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007645 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007646 }
7647 case TemplateArgument::NullPtr:
7648 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7649 case TemplateArgument::Integral: {
7650 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7651 QualType T = readType(F, Record, Idx);
7652 return TemplateArgument(Context, Value, T);
7653 }
7654 case TemplateArgument::Template:
7655 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7656 case TemplateArgument::TemplateExpansion: {
7657 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007658 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007659 if (unsigned NumExpansions = Record[Idx++])
7660 NumTemplateExpansions = NumExpansions - 1;
7661 return TemplateArgument(Name, NumTemplateExpansions);
7662 }
7663 case TemplateArgument::Expression:
7664 return TemplateArgument(ReadExpr(F));
7665 case TemplateArgument::Pack: {
7666 unsigned NumArgs = Record[Idx++];
7667 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7668 for (unsigned I = 0; I != NumArgs; ++I)
7669 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00007670 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00007671 }
7672 }
7673
7674 llvm_unreachable("Unhandled template argument kind!");
7675}
7676
7677TemplateParameterList *
7678ASTReader::ReadTemplateParameterList(ModuleFile &F,
7679 const RecordData &Record, unsigned &Idx) {
7680 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7681 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7682 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7683
7684 unsigned NumParams = Record[Idx++];
7685 SmallVector<NamedDecl *, 16> Params;
7686 Params.reserve(NumParams);
7687 while (NumParams--)
7688 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7689
7690 TemplateParameterList* TemplateParams =
7691 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7692 Params.data(), Params.size(), RAngleLoc);
7693 return TemplateParams;
7694}
7695
7696void
7697ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007698ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007699 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00007700 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007701 unsigned NumTemplateArgs = Record[Idx++];
7702 TemplArgs.reserve(NumTemplateArgs);
7703 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00007704 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00007705}
7706
7707/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007708void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007709 const RecordData &Record, unsigned &Idx) {
7710 unsigned NumDecls = Record[Idx++];
7711 Set.reserve(Context, NumDecls);
7712 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007713 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007714 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007715 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007716 }
7717}
7718
7719CXXBaseSpecifier
7720ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7721 const RecordData &Record, unsigned &Idx) {
7722 bool isVirtual = static_cast<bool>(Record[Idx++]);
7723 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7724 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7725 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7726 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7727 SourceRange Range = ReadSourceRange(F, Record, Idx);
7728 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7729 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7730 EllipsisLoc);
7731 Result.setInheritConstructors(inheritConstructors);
7732 return Result;
7733}
7734
Richard Smithc2bb8182015-03-24 06:36:48 +00007735CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007736ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7737 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007738 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007739 assert(NumInitializers && "wrote ctor initializers but have no inits");
7740 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7741 for (unsigned i = 0; i != NumInitializers; ++i) {
7742 TypeSourceInfo *TInfo = nullptr;
7743 bool IsBaseVirtual = false;
7744 FieldDecl *Member = nullptr;
7745 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007746
Richard Smithc2bb8182015-03-24 06:36:48 +00007747 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7748 switch (Type) {
7749 case CTOR_INITIALIZER_BASE:
7750 TInfo = GetTypeSourceInfo(F, Record, Idx);
7751 IsBaseVirtual = Record[Idx++];
7752 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007753
Richard Smithc2bb8182015-03-24 06:36:48 +00007754 case CTOR_INITIALIZER_DELEGATING:
7755 TInfo = GetTypeSourceInfo(F, Record, Idx);
7756 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007757
Richard Smithc2bb8182015-03-24 06:36:48 +00007758 case CTOR_INITIALIZER_MEMBER:
7759 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7760 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007761
Richard Smithc2bb8182015-03-24 06:36:48 +00007762 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7763 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7764 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007765 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007766
7767 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7768 Expr *Init = ReadExpr(F);
7769 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7770 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7771 bool IsWritten = Record[Idx++];
7772 unsigned SourceOrderOrNumArrayIndices;
7773 SmallVector<VarDecl *, 8> Indices;
7774 if (IsWritten) {
7775 SourceOrderOrNumArrayIndices = Record[Idx++];
7776 } else {
7777 SourceOrderOrNumArrayIndices = Record[Idx++];
7778 Indices.reserve(SourceOrderOrNumArrayIndices);
7779 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7780 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7781 }
7782
7783 CXXCtorInitializer *BOMInit;
7784 if (Type == CTOR_INITIALIZER_BASE) {
7785 BOMInit = new (Context)
7786 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7787 RParenLoc, MemberOrEllipsisLoc);
7788 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7789 BOMInit = new (Context)
7790 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7791 } else if (IsWritten) {
7792 if (Member)
7793 BOMInit = new (Context) CXXCtorInitializer(
7794 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7795 else
7796 BOMInit = new (Context)
7797 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7798 LParenLoc, Init, RParenLoc);
7799 } else {
7800 if (IndirectMember) {
7801 assert(Indices.empty() && "Indirect field improperly initialized");
7802 BOMInit = new (Context)
7803 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7804 LParenLoc, Init, RParenLoc);
7805 } else {
7806 BOMInit = CXXCtorInitializer::Create(
7807 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7808 Indices.data(), Indices.size());
7809 }
7810 }
7811
7812 if (IsWritten)
7813 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7814 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007815 }
7816
Richard Smithc2bb8182015-03-24 06:36:48 +00007817 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007818}
7819
7820NestedNameSpecifier *
7821ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7822 const RecordData &Record, unsigned &Idx) {
7823 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007824 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007825 for (unsigned I = 0; I != N; ++I) {
7826 NestedNameSpecifier::SpecifierKind Kind
7827 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7828 switch (Kind) {
7829 case NestedNameSpecifier::Identifier: {
7830 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7831 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7832 break;
7833 }
7834
7835 case NestedNameSpecifier::Namespace: {
7836 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7837 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7838 break;
7839 }
7840
7841 case NestedNameSpecifier::NamespaceAlias: {
7842 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7843 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7844 break;
7845 }
7846
7847 case NestedNameSpecifier::TypeSpec:
7848 case NestedNameSpecifier::TypeSpecWithTemplate: {
7849 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7850 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007851 return nullptr;
7852
Guy Benyei11169dd2012-12-18 14:30:41 +00007853 bool Template = Record[Idx++];
7854 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7855 break;
7856 }
7857
7858 case NestedNameSpecifier::Global: {
7859 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7860 // No associated value, and there can't be a prefix.
7861 break;
7862 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007863
7864 case NestedNameSpecifier::Super: {
7865 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7866 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7867 break;
7868 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007869 }
7870 Prev = NNS;
7871 }
7872 return NNS;
7873}
7874
7875NestedNameSpecifierLoc
7876ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7877 unsigned &Idx) {
7878 unsigned N = Record[Idx++];
7879 NestedNameSpecifierLocBuilder Builder;
7880 for (unsigned I = 0; I != N; ++I) {
7881 NestedNameSpecifier::SpecifierKind Kind
7882 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7883 switch (Kind) {
7884 case NestedNameSpecifier::Identifier: {
7885 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7886 SourceRange Range = ReadSourceRange(F, Record, Idx);
7887 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7888 break;
7889 }
7890
7891 case NestedNameSpecifier::Namespace: {
7892 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7893 SourceRange Range = ReadSourceRange(F, Record, Idx);
7894 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7895 break;
7896 }
7897
7898 case NestedNameSpecifier::NamespaceAlias: {
7899 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7900 SourceRange Range = ReadSourceRange(F, Record, Idx);
7901 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7902 break;
7903 }
7904
7905 case NestedNameSpecifier::TypeSpec:
7906 case NestedNameSpecifier::TypeSpecWithTemplate: {
7907 bool Template = Record[Idx++];
7908 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7909 if (!T)
7910 return NestedNameSpecifierLoc();
7911 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7912
7913 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7914 Builder.Extend(Context,
7915 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7916 T->getTypeLoc(), ColonColonLoc);
7917 break;
7918 }
7919
7920 case NestedNameSpecifier::Global: {
7921 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7922 Builder.MakeGlobal(Context, ColonColonLoc);
7923 break;
7924 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007925
7926 case NestedNameSpecifier::Super: {
7927 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7928 SourceRange Range = ReadSourceRange(F, Record, Idx);
7929 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
7930 break;
7931 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007932 }
7933 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007934
Guy Benyei11169dd2012-12-18 14:30:41 +00007935 return Builder.getWithLocInContext(Context);
7936}
7937
7938SourceRange
7939ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7940 unsigned &Idx) {
7941 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7942 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7943 return SourceRange(beg, end);
7944}
7945
7946/// \brief Read an integral value
7947llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7948 unsigned BitWidth = Record[Idx++];
7949 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7950 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7951 Idx += NumWords;
7952 return Result;
7953}
7954
7955/// \brief Read a signed integral value
7956llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7957 bool isUnsigned = Record[Idx++];
7958 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7959}
7960
7961/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007962llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7963 const llvm::fltSemantics &Sem,
7964 unsigned &Idx) {
7965 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007966}
7967
7968// \brief Read a string
7969std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7970 unsigned Len = Record[Idx++];
7971 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7972 Idx += Len;
7973 return Result;
7974}
7975
Richard Smith7ed1bc92014-12-05 22:42:13 +00007976std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
7977 unsigned &Idx) {
7978 std::string Filename = ReadString(Record, Idx);
7979 ResolveImportedPath(F, Filename);
7980 return Filename;
7981}
7982
Guy Benyei11169dd2012-12-18 14:30:41 +00007983VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7984 unsigned &Idx) {
7985 unsigned Major = Record[Idx++];
7986 unsigned Minor = Record[Idx++];
7987 unsigned Subminor = Record[Idx++];
7988 if (Minor == 0)
7989 return VersionTuple(Major);
7990 if (Subminor == 0)
7991 return VersionTuple(Major, Minor - 1);
7992 return VersionTuple(Major, Minor - 1, Subminor - 1);
7993}
7994
7995CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7996 const RecordData &Record,
7997 unsigned &Idx) {
7998 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7999 return CXXTemporary::Create(Context, Decl);
8000}
8001
8002DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008003 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008004}
8005
8006DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8007 return Diags.Report(Loc, DiagID);
8008}
8009
8010/// \brief Retrieve the identifier table associated with the
8011/// preprocessor.
8012IdentifierTable &ASTReader::getIdentifierTable() {
8013 return PP.getIdentifierTable();
8014}
8015
8016/// \brief Record that the given ID maps to the given switch-case
8017/// statement.
8018void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008019 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008020 "Already have a SwitchCase with this ID");
8021 (*CurrSwitchCaseStmts)[ID] = SC;
8022}
8023
8024/// \brief Retrieve the switch-case statement with the given ID.
8025SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008026 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008027 return (*CurrSwitchCaseStmts)[ID];
8028}
8029
8030void ASTReader::ClearSwitchCaseIDs() {
8031 CurrSwitchCaseStmts->clear();
8032}
8033
8034void ASTReader::ReadComments() {
8035 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008036 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008037 serialization::ModuleFile *> >::iterator
8038 I = CommentsCursors.begin(),
8039 E = CommentsCursors.end();
8040 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008041 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008042 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008043 serialization::ModuleFile &F = *I->second;
8044 SavedStreamPosition SavedPosition(Cursor);
8045
8046 RecordData Record;
8047 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008048 llvm::BitstreamEntry Entry =
8049 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008050
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008051 switch (Entry.Kind) {
8052 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8053 case llvm::BitstreamEntry::Error:
8054 Error("malformed block record in AST file");
8055 return;
8056 case llvm::BitstreamEntry::EndBlock:
8057 goto NextCursor;
8058 case llvm::BitstreamEntry::Record:
8059 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008060 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008061 }
8062
8063 // Read a record.
8064 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008065 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008066 case COMMENTS_RAW_COMMENT: {
8067 unsigned Idx = 0;
8068 SourceRange SR = ReadSourceRange(F, Record, Idx);
8069 RawComment::CommentKind Kind =
8070 (RawComment::CommentKind) Record[Idx++];
8071 bool IsTrailingComment = Record[Idx++];
8072 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008073 Comments.push_back(new (Context) RawComment(
8074 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8075 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008076 break;
8077 }
8078 }
8079 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008080 NextCursor:
8081 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008082 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008083}
8084
Richard Smithcd45dbc2014-04-19 03:48:30 +00008085std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8086 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008087 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008088 return M->getFullModuleName();
8089
8090 // Otherwise, use the name of the top-level module the decl is within.
8091 if (ModuleFile *M = getOwningModuleFile(D))
8092 return M->ModuleName;
8093
8094 // Not from a module.
8095 return "";
8096}
8097
Guy Benyei11169dd2012-12-18 14:30:41 +00008098void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008099 while (!PendingIdentifierInfos.empty() ||
8100 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008101 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008102 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008103 // If any identifiers with corresponding top-level declarations have
8104 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008105 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8106 TopLevelDeclsMap;
8107 TopLevelDeclsMap TopLevelDecls;
8108
Guy Benyei11169dd2012-12-18 14:30:41 +00008109 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008110 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008111 SmallVector<uint32_t, 4> DeclIDs =
8112 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008113 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008114
8115 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008116 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008117
Richard Smith851072e2014-05-19 20:59:20 +00008118 // For each decl chain that we wanted to complete while deserializing, mark
8119 // it as "still needs to be completed".
8120 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8121 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8122 }
8123 PendingIncompleteDeclChains.clear();
8124
Guy Benyei11169dd2012-12-18 14:30:41 +00008125 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008126 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithe687bf82015-03-16 20:54:07 +00008127 loadPendingDeclChain(PendingDeclChains[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008128 PendingDeclChains.clear();
8129
Richard Smith9b88a4c2015-07-27 05:40:23 +00008130 assert(RedeclsDeserialized.empty() && "some redecls not wired up");
8131
Douglas Gregor6168bd22013-02-18 15:53:43 +00008132 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008133 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8134 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008135 IdentifierInfo *II = TLD->first;
8136 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008137 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008138 }
8139 }
8140
Guy Benyei11169dd2012-12-18 14:30:41 +00008141 // Load any pending macro definitions.
8142 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008143 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8144 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8145 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8146 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008147 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008148 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008149 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008150 if (Info.M->Kind != MK_ImplicitModule &&
8151 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008152 resolvePendingMacro(II, Info);
8153 }
8154 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008155 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008156 ++IDIdx) {
8157 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008158 if (Info.M->Kind == MK_ImplicitModule ||
8159 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008160 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008161 }
8162 }
8163 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008164
8165 // Wire up the DeclContexts for Decls that we delayed setting until
8166 // recursive loading is completed.
8167 while (!PendingDeclContextInfos.empty()) {
8168 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8169 PendingDeclContextInfos.pop_front();
8170 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8171 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8172 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8173 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008174
Richard Smithd1c46742014-04-30 02:24:17 +00008175 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008176 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008177 auto Update = PendingUpdateRecords.pop_back_val();
8178 ReadingKindTracker ReadingKind(Read_Decl, *this);
8179 loadDeclUpdateRecords(Update.first, Update.second);
8180 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008181 }
Richard Smith8a639892015-01-24 01:07:20 +00008182
8183 // At this point, all update records for loaded decls are in place, so any
8184 // fake class definitions should have become real.
8185 assert(PendingFakeDefinitionData.empty() &&
8186 "faked up a class definition but never saw the real one");
8187
Guy Benyei11169dd2012-12-18 14:30:41 +00008188 // If we deserialized any C++ or Objective-C class definitions, any
8189 // Objective-C protocol definitions, or any redeclarable templates, make sure
8190 // that all redeclarations point to the definitions. Note that this can only
8191 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008192 for (Decl *D : PendingDefinitions) {
8193 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008194 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008195 // Make sure that the TagType points at the definition.
8196 const_cast<TagType*>(TagT)->decl = TD;
8197 }
Richard Smith8ce51082015-03-11 01:44:51 +00008198
Craig Topperc6914d02014-08-25 04:15:02 +00008199 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008200 for (auto *R = getMostRecentExistingDecl(RD); R;
8201 R = R->getPreviousDecl()) {
8202 assert((R == D) ==
8203 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008204 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008205 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008206 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008207 }
8208
8209 continue;
8210 }
Richard Smith8ce51082015-03-11 01:44:51 +00008211
Craig Topperc6914d02014-08-25 04:15:02 +00008212 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008213 // Make sure that the ObjCInterfaceType points at the definition.
8214 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8215 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008216
8217 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8218 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8219
Guy Benyei11169dd2012-12-18 14:30:41 +00008220 continue;
8221 }
Richard Smith8ce51082015-03-11 01:44:51 +00008222
Craig Topperc6914d02014-08-25 04:15:02 +00008223 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008224 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8225 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8226
Guy Benyei11169dd2012-12-18 14:30:41 +00008227 continue;
8228 }
Richard Smith8ce51082015-03-11 01:44:51 +00008229
Craig Topperc6914d02014-08-25 04:15:02 +00008230 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008231 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8232 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008233 }
8234 PendingDefinitions.clear();
8235
8236 // Load the bodies of any functions or methods we've encountered. We do
8237 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00008238 // have been fully wired up (hasBody relies on this).
8239 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00008240 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8241 PBEnd = PendingBodies.end();
8242 PB != PBEnd; ++PB) {
8243 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8244 // FIXME: Check for =delete/=default?
8245 // FIXME: Complain about ODR violations here?
8246 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8247 FD->setLazyBody(PB->second);
8248 continue;
8249 }
8250
8251 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8252 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8253 MD->setLazyBody(PB->second);
8254 }
8255 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008256
8257 // Do some cleanup.
8258 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8259 getContext().deduplicateMergedDefinitonsFor(ND);
8260 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008261}
8262
8263void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008264 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8265 return;
8266
Richard Smitha0ce9c42014-07-29 23:23:27 +00008267 // Trigger the import of the full definition of each class that had any
8268 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008269 // These updates may in turn find and diagnose some ODR failures, so take
8270 // ownership of the set first.
8271 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8272 PendingOdrMergeFailures.clear();
8273 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008274 Merge.first->buildLookup();
8275 Merge.first->decls_begin();
8276 Merge.first->bases_begin();
8277 Merge.first->vbases_begin();
8278 for (auto *RD : Merge.second) {
8279 RD->decls_begin();
8280 RD->bases_begin();
8281 RD->vbases_begin();
8282 }
8283 }
8284
8285 // For each declaration from a merged context, check that the canonical
8286 // definition of that context also contains a declaration of the same
8287 // entity.
8288 //
8289 // Caution: this loop does things that might invalidate iterators into
8290 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8291 while (!PendingOdrMergeChecks.empty()) {
8292 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8293
8294 // FIXME: Skip over implicit declarations for now. This matters for things
8295 // like implicitly-declared special member functions. This isn't entirely
8296 // correct; we can end up with multiple unmerged declarations of the same
8297 // implicit entity.
8298 if (D->isImplicit())
8299 continue;
8300
8301 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008302
8303 bool Found = false;
8304 const Decl *DCanon = D->getCanonicalDecl();
8305
Richard Smith01bdb7a2014-08-28 05:44:07 +00008306 for (auto RI : D->redecls()) {
8307 if (RI->getLexicalDeclContext() == CanonDef) {
8308 Found = true;
8309 break;
8310 }
8311 }
8312 if (Found)
8313 continue;
8314
Richard Smith0f4e2c42015-08-06 04:23:48 +00008315 // Quick check failed, time to do the slow thing. Note, we can't just
8316 // look up the name of D in CanonDef here, because the member that is
8317 // in CanonDef might not be found by name lookup (it might have been
8318 // replaced by a more recent declaration in the lookup table), and we
8319 // can't necessarily find it in the redeclaration chain because it might
8320 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008321 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008322 for (auto *CanonMember : CanonDef->decls()) {
8323 if (CanonMember->getCanonicalDecl() == DCanon) {
8324 // This can happen if the declaration is merely mergeable and not
8325 // actually redeclarable (we looked for redeclarations earlier).
8326 //
8327 // FIXME: We should be able to detect this more efficiently, without
8328 // pulling in all of the members of CanonDef.
8329 Found = true;
8330 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008331 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008332 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8333 if (ND->getDeclName() == D->getDeclName())
8334 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008335 }
8336
8337 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008338 // The AST doesn't like TagDecls becoming invalid after they've been
8339 // completed. We only really need to mark FieldDecls as invalid here.
8340 if (!isa<TagDecl>(D))
8341 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008342
8343 // Ensure we don't accidentally recursively enter deserialization while
8344 // we're producing our diagnostic.
8345 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008346
8347 std::string CanonDefModule =
8348 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8349 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8350 << D << getOwningModuleNameForDiagnostic(D)
8351 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8352
8353 if (Candidates.empty())
8354 Diag(cast<Decl>(CanonDef)->getLocation(),
8355 diag::note_module_odr_violation_no_possible_decls) << D;
8356 else {
8357 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8358 Diag(Candidates[I]->getLocation(),
8359 diag::note_module_odr_violation_possible_decl)
8360 << Candidates[I];
8361 }
8362
8363 DiagnosedOdrMergeFailures.insert(CanonDef);
8364 }
8365 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008366
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008367 if (OdrMergeFailures.empty())
8368 return;
8369
8370 // Ensure we don't accidentally recursively enter deserialization while
8371 // we're producing our diagnostics.
8372 Deserializing RecursionGuard(this);
8373
Richard Smithcd45dbc2014-04-19 03:48:30 +00008374 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008375 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008376 // If we've already pointed out a specific problem with this class, don't
8377 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008378 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008379 continue;
8380
8381 bool Diagnosed = false;
8382 for (auto *RD : Merge.second) {
8383 // Multiple different declarations got merged together; tell the user
8384 // where they came from.
8385 if (Merge.first != RD) {
8386 // FIXME: Walk the definition, figure out what's different,
8387 // and diagnose that.
8388 if (!Diagnosed) {
8389 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8390 Diag(Merge.first->getLocation(),
8391 diag::err_module_odr_violation_different_definitions)
8392 << Merge.first << Module.empty() << Module;
8393 Diagnosed = true;
8394 }
8395
8396 Diag(RD->getLocation(),
8397 diag::note_module_odr_violation_different_definitions)
8398 << getOwningModuleNameForDiagnostic(RD);
8399 }
8400 }
8401
8402 if (!Diagnosed) {
8403 // All definitions are updates to the same declaration. This happens if a
8404 // module instantiates the declaration of a class template specialization
8405 // and two or more other modules instantiate its definition.
8406 //
8407 // FIXME: Indicate which modules had instantiations of this definition.
8408 // FIXME: How can this even happen?
8409 Diag(Merge.first->getLocation(),
8410 diag::err_module_odr_violation_different_instantiations)
8411 << Merge.first;
8412 }
8413 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008414}
8415
Richard Smithce18a182015-07-14 00:26:00 +00008416void ASTReader::StartedDeserializing() {
8417 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8418 ReadTimer->startTimer();
8419}
8420
Guy Benyei11169dd2012-12-18 14:30:41 +00008421void ASTReader::FinishedDeserializing() {
8422 assert(NumCurrentElementsDeserializing &&
8423 "FinishedDeserializing not paired with StartedDeserializing");
8424 if (NumCurrentElementsDeserializing == 1) {
8425 // We decrease NumCurrentElementsDeserializing only after pending actions
8426 // are finished, to avoid recursively re-calling finishPendingActions().
8427 finishPendingActions();
8428 }
8429 --NumCurrentElementsDeserializing;
8430
Richard Smitha0ce9c42014-07-29 23:23:27 +00008431 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008432 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008433 while (!PendingExceptionSpecUpdates.empty()) {
8434 auto Updates = std::move(PendingExceptionSpecUpdates);
8435 PendingExceptionSpecUpdates.clear();
8436 for (auto Update : Updates) {
8437 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00008438 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
8439 for (auto *Redecl : Update.second->redecls())
8440 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00008441 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008442 }
8443
Richard Smithce18a182015-07-14 00:26:00 +00008444 if (ReadTimer)
8445 ReadTimer->stopTimer();
8446
Richard Smith0f4e2c42015-08-06 04:23:48 +00008447 diagnoseOdrViolations();
8448
Richard Smith04d05b52014-03-23 00:27:18 +00008449 // We are not in recursive loading, so it's safe to pass the "interesting"
8450 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008451 if (Consumer)
8452 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008453 }
8454}
8455
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008456void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008457 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8458 // Remove any fake results before adding any real ones.
8459 auto It = PendingFakeLookupResults.find(II);
8460 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008461 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008462 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008463 // FIXME: this works around module+PCH performance issue.
8464 // Rather than erase the result from the map, which is O(n), just clear
8465 // the vector of NamedDecls.
8466 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008467 }
8468 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008469
8470 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8471 SemaObj->TUScope->AddDecl(D);
8472 } else if (SemaObj->TUScope) {
8473 // Adding the decl to IdResolver may have failed because it was already in
8474 // (even though it was not added in scope). If it is already in, make sure
8475 // it gets in the scope as well.
8476 if (std::find(SemaObj->IdResolver.begin(Name),
8477 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8478 SemaObj->TUScope->AddDecl(D);
8479 }
8480}
8481
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008482ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008483 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008484 StringRef isysroot, bool DisableValidation,
8485 bool AllowASTWithCompilerErrors,
Nico Weber824285e2014-05-08 04:26:47 +00008486 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Richard Smithce18a182015-07-14 00:26:00 +00008487 bool UseGlobalIndex,
8488 std::unique_ptr<llvm::Timer> ReadTimer)
Craig Toppera13603a2014-05-22 05:54:18 +00008489 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008490 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008491 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008492 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008493 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
Richard Smithce18a182015-07-14 00:26:00 +00008494 ReadTimer(std::move(ReadTimer)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008495 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008496 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8497 AllowConfigurationMismatch(AllowConfigurationMismatch),
8498 ValidateSystemInputs(ValidateSystemInputs),
8499 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008500 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8501 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8502 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8503 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008504 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8505 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8506 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8507 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8508 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8509 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008510 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008511 SourceMgr.setExternalSLocEntrySource(this);
8512}
8513
8514ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008515 if (OwnsDeserializationListener)
8516 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00008517}