blob: 91dc4bdbc90e390a1bff79089746bd2b617e4079 [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}
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000141void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
142 First->visitModuleFile(Filename);
143 Second->visitModuleFile(Filename);
144}
Ben Langmuircb69b572014-03-07 06:40:32 +0000145bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000146 bool isSystem,
147 bool isOverridden) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000148 bool Continue = false;
149 if (First->needsInputFileVisitation() &&
150 (!isSystem || First->needsSystemInputFileVisitation()))
151 Continue |= First->visitInputFile(Filename, isSystem, isOverridden);
152 if (Second->needsInputFileVisitation() &&
153 (!isSystem || Second->needsSystemInputFileVisitation()))
154 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden);
155 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000156}
157
Guy Benyei11169dd2012-12-18 14:30:41 +0000158//===----------------------------------------------------------------------===//
159// PCH validator implementation
160//===----------------------------------------------------------------------===//
161
162ASTReaderListener::~ASTReaderListener() {}
163
164/// \brief Compare the given set of language options against an existing set of
165/// language options.
166///
167/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000168/// \param AllowCompatibleDifferences If true, differences between compatible
169/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000170///
171/// \returns true if the languagae options mis-match, false otherwise.
172static bool checkLanguageOptions(const LangOptions &LangOpts,
173 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000174 DiagnosticsEngine *Diags,
175 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000176#define LANGOPT(Name, Bits, Default, Description) \
177 if (ExistingLangOpts.Name != LangOpts.Name) { \
178 if (Diags) \
179 Diags->Report(diag::err_pch_langopt_mismatch) \
180 << Description << LangOpts.Name << ExistingLangOpts.Name; \
181 return true; \
182 }
183
184#define VALUE_LANGOPT(Name, Bits, Default, Description) \
185 if (ExistingLangOpts.Name != LangOpts.Name) { \
186 if (Diags) \
187 Diags->Report(diag::err_pch_langopt_value_mismatch) \
188 << Description; \
189 return true; \
190 }
191
192#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
193 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
194 if (Diags) \
195 Diags->Report(diag::err_pch_langopt_value_mismatch) \
196 << Description; \
197 return true; \
198 }
199
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000200#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
201 if (!AllowCompatibleDifferences) \
202 LANGOPT(Name, Bits, Default, Description)
203
204#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
205 if (!AllowCompatibleDifferences) \
206 ENUM_LANGOPT(Name, Bits, Default, Description)
207
Guy Benyei11169dd2012-12-18 14:30:41 +0000208#define BENIGN_LANGOPT(Name, Bits, Default, Description)
209#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
210#include "clang/Basic/LangOptions.def"
211
Ben Langmuircd98cb72015-06-23 18:20:18 +0000212 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
213 if (Diags)
214 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
215 return true;
216 }
217
Guy Benyei11169dd2012-12-18 14:30:41 +0000218 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
219 if (Diags)
220 Diags->Report(diag::err_pch_langopt_value_mismatch)
221 << "target Objective-C runtime";
222 return true;
223 }
224
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000225 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
226 LangOpts.CommentOpts.BlockCommandNames) {
227 if (Diags)
228 Diags->Report(diag::err_pch_langopt_value_mismatch)
229 << "block command names";
230 return true;
231 }
232
Guy Benyei11169dd2012-12-18 14:30:41 +0000233 return false;
234}
235
236/// \brief Compare the given set of target options against an existing set of
237/// target options.
238///
239/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
240///
241/// \returns true if the target options mis-match, false otherwise.
242static bool checkTargetOptions(const TargetOptions &TargetOpts,
243 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000244 DiagnosticsEngine *Diags,
245 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000246#define CHECK_TARGET_OPT(Field, Name) \
247 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
248 if (Diags) \
249 Diags->Report(diag::err_pch_targetopt_mismatch) \
250 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
251 return true; \
252 }
253
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000254 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000255 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000256 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000257
258 // We can tolerate different CPUs in many cases, notably when one CPU
259 // supports a strict superset of another. When allowing compatible
260 // differences skip this check.
261 if (!AllowCompatibleDifferences)
262 CHECK_TARGET_OPT(CPU, "target CPU");
263
Guy Benyei11169dd2012-12-18 14:30:41 +0000264#undef CHECK_TARGET_OPT
265
266 // Compare feature sets.
267 SmallVector<StringRef, 4> ExistingFeatures(
268 ExistingTargetOpts.FeaturesAsWritten.begin(),
269 ExistingTargetOpts.FeaturesAsWritten.end());
270 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
271 TargetOpts.FeaturesAsWritten.end());
272 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
273 std::sort(ReadFeatures.begin(), ReadFeatures.end());
274
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000275 // We compute the set difference in both directions explicitly so that we can
276 // diagnose the differences differently.
277 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
278 std::set_difference(
279 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
280 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
281 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
282 ExistingFeatures.begin(), ExistingFeatures.end(),
283 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000284
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000285 // If we are allowing compatible differences and the read feature set is
286 // a strict subset of the existing feature set, there is nothing to diagnose.
287 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
288 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000289
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000290 if (Diags) {
291 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000292 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000293 << /* is-existing-feature */ false << Feature;
294 for (StringRef Feature : UnmatchedExistingFeatures)
295 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
296 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000297 }
298
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000299 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000300}
301
302bool
303PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000304 bool Complain,
305 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000306 const LangOptions &ExistingLangOpts = PP.getLangOpts();
307 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000308 Complain ? &Reader.Diags : nullptr,
309 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000310}
311
312bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000313 bool Complain,
314 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000315 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
316 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000317 Complain ? &Reader.Diags : nullptr,
318 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000319}
320
321namespace {
322 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
323 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000324 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
325 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000326}
327
Ben Langmuirb92de022014-04-29 16:25:26 +0000328static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
329 DiagnosticsEngine &Diags,
330 bool Complain) {
331 typedef DiagnosticsEngine::Level Level;
332
333 // Check current mappings for new -Werror mappings, and the stored mappings
334 // for cases that were explicitly mapped to *not* be errors that are now
335 // errors because of options like -Werror.
336 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
337
338 for (DiagnosticsEngine *MappingSource : MappingSources) {
339 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
340 diag::kind DiagID = DiagIDMappingPair.first;
341 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
342 if (CurLevel < DiagnosticsEngine::Error)
343 continue; // not significant
344 Level StoredLevel =
345 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
346 if (StoredLevel < DiagnosticsEngine::Error) {
347 if (Complain)
348 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
349 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
350 return true;
351 }
352 }
353 }
354
355 return false;
356}
357
Alp Tokerac4e8e52014-06-22 21:58:33 +0000358static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
359 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
360 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
361 return true;
362 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000363}
364
365static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
366 DiagnosticsEngine &Diags,
367 bool IsSystem, bool Complain) {
368 // Top-level options
369 if (IsSystem) {
370 if (Diags.getSuppressSystemWarnings())
371 return false;
372 // If -Wsystem-headers was not enabled before, be conservative
373 if (StoredDiags.getSuppressSystemWarnings()) {
374 if (Complain)
375 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
376 return true;
377 }
378 }
379
380 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
381 if (Complain)
382 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
383 return true;
384 }
385
386 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
387 !StoredDiags.getEnableAllWarnings()) {
388 if (Complain)
389 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
390 return true;
391 }
392
393 if (isExtHandlingFromDiagsError(Diags) &&
394 !isExtHandlingFromDiagsError(StoredDiags)) {
395 if (Complain)
396 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
397 return true;
398 }
399
400 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
401}
402
403bool PCHValidator::ReadDiagnosticOptions(
404 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
405 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
406 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
407 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000408 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000409 // This should never fail, because we would have processed these options
410 // before writing them to an ASTFile.
411 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
412
413 ModuleManager &ModuleMgr = Reader.getModuleManager();
414 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
415
416 // If the original import came from a file explicitly generated by the user,
417 // don't check the diagnostic mappings.
418 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000419 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000420 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
421 // the transitive closure of its imports, since unrelated modules cannot be
422 // imported until after this module finishes validation.
423 ModuleFile *TopImport = *ModuleMgr.rbegin();
424 while (!TopImport->ImportedBy.empty())
425 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000426 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000427 return false;
428
429 StringRef ModuleName = TopImport->ModuleName;
430 assert(!ModuleName.empty() && "diagnostic options read before module name");
431
432 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
433 assert(M && "missing module");
434
435 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
436 // contains the union of their flags.
437 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
438}
439
Guy Benyei11169dd2012-12-18 14:30:41 +0000440/// \brief Collect the macro definitions provided by the given preprocessor
441/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000442static void
443collectMacroDefinitions(const PreprocessorOptions &PPOpts,
444 MacroDefinitionsMap &Macros,
445 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000446 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
447 StringRef Macro = PPOpts.Macros[I].first;
448 bool IsUndef = PPOpts.Macros[I].second;
449
450 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
451 StringRef MacroName = MacroPair.first;
452 StringRef MacroBody = MacroPair.second;
453
454 // For an #undef'd macro, we only care about the name.
455 if (IsUndef) {
456 if (MacroNames && !Macros.count(MacroName))
457 MacroNames->push_back(MacroName);
458
459 Macros[MacroName] = std::make_pair("", true);
460 continue;
461 }
462
463 // For a #define'd macro, figure out the actual definition.
464 if (MacroName.size() == Macro.size())
465 MacroBody = "1";
466 else {
467 // Note: GCC drops anything following an end-of-line character.
468 StringRef::size_type End = MacroBody.find_first_of("\n\r");
469 MacroBody = MacroBody.substr(0, End);
470 }
471
472 if (MacroNames && !Macros.count(MacroName))
473 MacroNames->push_back(MacroName);
474 Macros[MacroName] = std::make_pair(MacroBody, false);
475 }
476}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000477
Guy Benyei11169dd2012-12-18 14:30:41 +0000478/// \brief Check the preprocessor options deserialized from the control block
479/// against the preprocessor options in an existing preprocessor.
480///
481/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
482static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
483 const PreprocessorOptions &ExistingPPOpts,
484 DiagnosticsEngine *Diags,
485 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000486 std::string &SuggestedPredefines,
487 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000488 // Check macro definitions.
489 MacroDefinitionsMap ASTFileMacros;
490 collectMacroDefinitions(PPOpts, ASTFileMacros);
491 MacroDefinitionsMap ExistingMacros;
492 SmallVector<StringRef, 4> ExistingMacroNames;
493 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
494
495 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
496 // Dig out the macro definition in the existing preprocessor options.
497 StringRef MacroName = ExistingMacroNames[I];
498 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
499
500 // Check whether we know anything about this macro name or not.
501 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
502 = ASTFileMacros.find(MacroName);
503 if (Known == ASTFileMacros.end()) {
504 // FIXME: Check whether this identifier was referenced anywhere in the
505 // AST file. If so, we should reject the AST file. Unfortunately, this
506 // information isn't in the control block. What shall we do about it?
507
508 if (Existing.second) {
509 SuggestedPredefines += "#undef ";
510 SuggestedPredefines += MacroName.str();
511 SuggestedPredefines += '\n';
512 } else {
513 SuggestedPredefines += "#define ";
514 SuggestedPredefines += MacroName.str();
515 SuggestedPredefines += ' ';
516 SuggestedPredefines += Existing.first.str();
517 SuggestedPredefines += '\n';
518 }
519 continue;
520 }
521
522 // If the macro was defined in one but undef'd in the other, we have a
523 // conflict.
524 if (Existing.second != Known->second.second) {
525 if (Diags) {
526 Diags->Report(diag::err_pch_macro_def_undef)
527 << MacroName << Known->second.second;
528 }
529 return true;
530 }
531
532 // If the macro was #undef'd in both, or if the macro bodies are identical,
533 // it's fine.
534 if (Existing.second || Existing.first == Known->second.first)
535 continue;
536
537 // The macro bodies differ; complain.
538 if (Diags) {
539 Diags->Report(diag::err_pch_macro_def_conflict)
540 << MacroName << Known->second.first << Existing.first;
541 }
542 return true;
543 }
544
545 // Check whether we're using predefines.
546 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
547 if (Diags) {
548 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
549 }
550 return true;
551 }
552
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000553 // Detailed record is important since it is used for the module cache hash.
554 if (LangOpts.Modules &&
555 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
556 if (Diags) {
557 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
558 }
559 return true;
560 }
561
Guy Benyei11169dd2012-12-18 14:30:41 +0000562 // Compute the #include and #include_macros lines we need.
563 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
564 StringRef File = ExistingPPOpts.Includes[I];
565 if (File == ExistingPPOpts.ImplicitPCHInclude)
566 continue;
567
568 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
569 != PPOpts.Includes.end())
570 continue;
571
572 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000573 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000574 SuggestedPredefines += "\"\n";
575 }
576
577 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
578 StringRef File = ExistingPPOpts.MacroIncludes[I];
579 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
580 File)
581 != PPOpts.MacroIncludes.end())
582 continue;
583
584 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000585 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000586 SuggestedPredefines += "\"\n##\n";
587 }
588
589 return false;
590}
591
592bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
593 bool Complain,
594 std::string &SuggestedPredefines) {
595 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
596
597 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000598 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000599 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000600 SuggestedPredefines,
601 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000602}
603
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000604/// Check the header search options deserialized from the control block
605/// against the header search options in an existing preprocessor.
606///
607/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
608static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
609 StringRef SpecificModuleCachePath,
610 StringRef ExistingModuleCachePath,
611 DiagnosticsEngine *Diags,
612 const LangOptions &LangOpts) {
613 if (LangOpts.Modules) {
614 if (SpecificModuleCachePath != ExistingModuleCachePath) {
615 if (Diags)
616 Diags->Report(diag::err_pch_modulecache_mismatch)
617 << SpecificModuleCachePath << ExistingModuleCachePath;
618 return true;
619 }
620 }
621
622 return false;
623}
624
625bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
626 StringRef SpecificModuleCachePath,
627 bool Complain) {
628 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
629 PP.getHeaderSearchInfo().getModuleCachePath(),
630 Complain ? &Reader.Diags : nullptr,
631 PP.getLangOpts());
632}
633
Guy Benyei11169dd2012-12-18 14:30:41 +0000634void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
635 PP.setCounterValue(Value);
636}
637
638//===----------------------------------------------------------------------===//
639// AST reader implementation
640//===----------------------------------------------------------------------===//
641
Nico Weber824285e2014-05-08 04:26:47 +0000642void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
643 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000644 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000645 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000646}
647
648
649
650unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
651 return serialization::ComputeHash(Sel);
652}
653
654
655std::pair<unsigned, unsigned>
656ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000657 using namespace llvm::support;
658 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
659 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000660 return std::make_pair(KeyLen, DataLen);
661}
662
663ASTSelectorLookupTrait::internal_key_type
664ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000665 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000666 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000667 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
668 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
669 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000670 if (N == 0)
671 return SelTable.getNullarySelector(FirstII);
672 else if (N == 1)
673 return SelTable.getUnarySelector(FirstII);
674
675 SmallVector<IdentifierInfo *, 16> Args;
676 Args.push_back(FirstII);
677 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000678 Args.push_back(Reader.getLocalIdentifier(
679 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000680
681 return SelTable.getSelector(N, Args.data());
682}
683
684ASTSelectorLookupTrait::data_type
685ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
686 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000687 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000688
689 data_type Result;
690
Justin Bogner57ba0b22014-03-28 22:03:24 +0000691 Result.ID = Reader.getGlobalSelectorID(
692 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000693 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
694 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
695 Result.InstanceBits = FullInstanceBits & 0x3;
696 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
697 Result.FactoryBits = FullFactoryBits & 0x3;
698 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
699 unsigned NumInstanceMethods = FullInstanceBits >> 3;
700 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000701
702 // Load instance methods
703 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000704 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
705 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000706 Result.Instance.push_back(Method);
707 }
708
709 // Load factory methods
710 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000711 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
712 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000713 Result.Factory.push_back(Method);
714 }
715
716 return Result;
717}
718
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000719unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
720 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000721}
722
723std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000724ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000725 using namespace llvm::support;
726 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
727 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000728 return std::make_pair(KeyLen, DataLen);
729}
730
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000731ASTIdentifierLookupTraitBase::internal_key_type
732ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000733 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000734 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000735}
736
Douglas Gregordcf25082013-02-11 18:16:18 +0000737/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000738static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
739 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000740 return II.hadMacroDefinition() ||
741 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000742 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000743 II.hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +0000744 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
745 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000746}
747
Richard Smith76c2f2c2015-07-17 20:09:43 +0000748static bool readBit(unsigned &Bits) {
749 bool Value = Bits & 0x1;
750 Bits >>= 1;
751 return Value;
752}
753
Guy Benyei11169dd2012-12-18 14:30:41 +0000754IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
755 const unsigned char* d,
756 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000757 using namespace llvm::support;
758 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000759 bool IsInteresting = RawID & 0x01;
760
761 // Wipe out the "is interesting" bit.
762 RawID = RawID >> 1;
763
Richard Smith76c2f2c2015-07-17 20:09:43 +0000764 // Build the IdentifierInfo and link the identifier ID with it.
765 IdentifierInfo *II = KnownII;
766 if (!II) {
767 II = &Reader.getIdentifierTable().getOwn(k);
768 KnownII = II;
769 }
770 if (!II->isFromAST()) {
771 II->setIsFromAST();
Richard Smitha534a312015-07-21 23:54:07 +0000772 if (isInterestingIdentifier(Reader, *II, F.isModule()))
Richard Smith76c2f2c2015-07-17 20:09:43 +0000773 II->setChangedSinceDeserialization();
774 }
775 Reader.markIdentifierUpToDate(II);
776
Guy Benyei11169dd2012-12-18 14:30:41 +0000777 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
778 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000779 // For uninteresting identifiers, there's nothing else to do. Just notify
780 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000781 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000782 return II;
783 }
784
Justin Bogner57ba0b22014-03-28 22:03:24 +0000785 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
786 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000787 bool CPlusPlusOperatorKeyword = readBit(Bits);
788 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000789 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000790 bool Poisoned = readBit(Bits);
791 bool ExtensionToken = readBit(Bits);
792 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000793
794 assert(Bits == 0 && "Extra bits in the identifier?");
795 DataLen -= 8;
796
Guy Benyei11169dd2012-12-18 14:30:41 +0000797 // Set or check the various bits in the IdentifierInfo structure.
798 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000799 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000800 II->revertTokenIDToIdentifier();
801 if (!F.isModule())
802 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
803 else if (HasRevertedBuiltin && II->getBuiltinID()) {
804 II->revertBuiltin();
805 assert((II->hasRevertedBuiltin() ||
806 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
807 "Incorrect ObjC keyword or builtin ID");
808 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000809 assert(II->isExtensionToken() == ExtensionToken &&
810 "Incorrect extension token flag");
811 (void)ExtensionToken;
812 if (Poisoned)
813 II->setIsPoisoned(true);
814 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
815 "Incorrect C++ operator keyword flag");
816 (void)CPlusPlusOperatorKeyword;
817
818 // If this identifier is a macro, deserialize the macro
819 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000820 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000821 uint32_t MacroDirectivesOffset =
822 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000823 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000824
Richard Smithd7329392015-04-21 21:46:32 +0000825 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000826 }
827
828 Reader.SetIdentifierInfo(ID, II);
829
830 // Read all of the declarations visible at global scope with this
831 // name.
832 if (DataLen > 0) {
833 SmallVector<uint32_t, 4> DeclIDs;
834 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000835 DeclIDs.push_back(Reader.getGlobalDeclID(
836 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000837 Reader.SetGloballyVisibleDecls(II, DeclIDs);
838 }
839
840 return II;
841}
842
843unsigned
Richard Smith3b637412015-07-14 18:42:41 +0000844ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000845 llvm::FoldingSetNodeID ID;
846 ID.AddInteger(Key.Kind);
847
848 switch (Key.Kind) {
849 case DeclarationName::Identifier:
850 case DeclarationName::CXXLiteralOperatorName:
851 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
852 break;
853 case DeclarationName::ObjCZeroArgSelector:
854 case DeclarationName::ObjCOneArgSelector:
855 case DeclarationName::ObjCMultiArgSelector:
856 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
857 break;
858 case DeclarationName::CXXOperatorName:
859 ID.AddInteger((OverloadedOperatorKind)Key.Data);
860 break;
861 case DeclarationName::CXXConstructorName:
862 case DeclarationName::CXXDestructorName:
863 case DeclarationName::CXXConversionFunctionName:
864 case DeclarationName::CXXUsingDirective:
865 break;
866 }
867
868 return ID.ComputeHash();
869}
870
871ASTDeclContextNameLookupTrait::internal_key_type
872ASTDeclContextNameLookupTrait::GetInternalKey(
Richard Smith3b637412015-07-14 18:42:41 +0000873 const external_key_type& Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000874 DeclNameKey Key;
875 Key.Kind = Name.getNameKind();
876 switch (Name.getNameKind()) {
877 case DeclarationName::Identifier:
878 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
879 break;
880 case DeclarationName::ObjCZeroArgSelector:
881 case DeclarationName::ObjCOneArgSelector:
882 case DeclarationName::ObjCMultiArgSelector:
883 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
884 break;
885 case DeclarationName::CXXOperatorName:
886 Key.Data = Name.getCXXOverloadedOperator();
887 break;
888 case DeclarationName::CXXLiteralOperatorName:
889 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
890 break;
891 case DeclarationName::CXXConstructorName:
892 case DeclarationName::CXXDestructorName:
893 case DeclarationName::CXXConversionFunctionName:
894 case DeclarationName::CXXUsingDirective:
895 Key.Data = 0;
896 break;
897 }
898
899 return Key;
900}
901
902std::pair<unsigned, unsigned>
903ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000904 using namespace llvm::support;
905 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
906 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000907 return std::make_pair(KeyLen, DataLen);
908}
909
910ASTDeclContextNameLookupTrait::internal_key_type
911ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000912 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000913
914 DeclNameKey Key;
915 Key.Kind = (DeclarationName::NameKind)*d++;
916 switch (Key.Kind) {
917 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000918 Key.Data = (uint64_t)Reader.getLocalIdentifier(
919 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000920 break;
921 case DeclarationName::ObjCZeroArgSelector:
922 case DeclarationName::ObjCOneArgSelector:
923 case DeclarationName::ObjCMultiArgSelector:
924 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000925 (uint64_t)Reader.getLocalSelector(
926 F, endian::readNext<uint32_t, little, unaligned>(
927 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000928 break;
929 case DeclarationName::CXXOperatorName:
930 Key.Data = *d++; // OverloadedOperatorKind
931 break;
932 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000933 Key.Data = (uint64_t)Reader.getLocalIdentifier(
934 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000935 break;
936 case DeclarationName::CXXConstructorName:
937 case DeclarationName::CXXDestructorName:
938 case DeclarationName::CXXConversionFunctionName:
939 case DeclarationName::CXXUsingDirective:
940 Key.Data = 0;
941 break;
942 }
943
944 return Key;
945}
946
Richard Smithf02662d2015-07-30 03:17:16 +0000947ASTDeclContextNameLookupTrait::data_type
948ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
949 const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000950 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000951 using namespace llvm::support;
Richard Smithf02662d2015-07-30 03:17:16 +0000952 unsigned NumDecls = DataLen / 4;
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000953 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
954 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000955 return std::make_pair(Start, Start + NumDecls);
956}
957
Richard Smith0f4e2c42015-08-06 04:23:48 +0000958bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
959 BitstreamCursor &Cursor,
960 uint64_t Offset,
961 DeclContext *DC) {
962 assert(Offset != 0);
963
Guy Benyei11169dd2012-12-18 14:30:41 +0000964 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +0000965 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000966
Richard Smith0f4e2c42015-08-06 04:23:48 +0000967 RecordData Record;
968 StringRef Blob;
969 unsigned Code = Cursor.ReadCode();
970 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
971 if (RecCode != DECL_CONTEXT_LEXICAL) {
972 Error("Expected lexical block");
973 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000974 }
975
Richard Smith82f8fcd2015-08-06 22:07:25 +0000976 assert(!isa<TranslationUnitDecl>(DC) &&
977 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +0000978 // If we are handling a C++ class template instantiation, we can see multiple
979 // lexical updates for the same record. It's important that we select only one
980 // of them, so that field numbering works properly. Just pick the first one we
981 // see.
982 auto &Lex = LexicalDecls[DC];
983 if (!Lex.first) {
984 Lex = std::make_pair(
985 &M, llvm::makeArrayRef(
986 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
987 Blob.data()),
988 Blob.size() / 4));
989 }
Richard Smith0f4e2c42015-08-06 04:23:48 +0000990 DC->setHasExternalLexicalStorage(true);
991 return false;
992}
Guy Benyei11169dd2012-12-18 14:30:41 +0000993
Richard Smith0f4e2c42015-08-06 04:23:48 +0000994bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
995 BitstreamCursor &Cursor,
996 uint64_t Offset,
997 DeclID ID) {
998 assert(Offset != 0);
999
1000 SavedStreamPosition SavedPosition(Cursor);
1001 Cursor.JumpToBit(Offset);
1002
1003 RecordData Record;
1004 StringRef Blob;
1005 unsigned Code = Cursor.ReadCode();
1006 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1007 if (RecCode != DECL_CONTEXT_VISIBLE) {
1008 Error("Expected visible lookup table block");
1009 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001010 }
1011
Richard Smith0f4e2c42015-08-06 04:23:48 +00001012 // We can't safely determine the primary context yet, so delay attaching the
1013 // lookup table until we're done with recursive deserialization.
1014 unsigned BucketOffset = Record[0];
1015 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{
1016 &M, (const unsigned char *)Blob.data(), BucketOffset});
Guy Benyei11169dd2012-12-18 14:30:41 +00001017 return false;
1018}
1019
1020void ASTReader::Error(StringRef Msg) {
1021 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +00001022 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
1023 Diag(diag::note_module_cache_path)
1024 << PP.getHeaderSearchInfo().getModuleCachePath();
1025 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001026}
1027
1028void ASTReader::Error(unsigned DiagID,
1029 StringRef Arg1, StringRef Arg2) {
1030 if (Diags.isDiagnosticInFlight())
1031 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1032 else
1033 Diag(DiagID) << Arg1 << Arg2;
1034}
1035
1036//===----------------------------------------------------------------------===//
1037// Source Manager Deserialization
1038//===----------------------------------------------------------------------===//
1039
1040/// \brief Read the line table in the source manager block.
1041/// \returns true if there was an error.
1042bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001043 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001044 unsigned Idx = 0;
1045 LineTableInfo &LineTable = SourceMgr.getLineTable();
1046
1047 // Parse the file names
1048 std::map<int, int> FileIDs;
1049 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1050 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001051 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001052 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1053 }
1054
1055 // Parse the line entries
1056 std::vector<LineEntry> Entries;
1057 while (Idx < Record.size()) {
1058 int FID = Record[Idx++];
1059 assert(FID >= 0 && "Serialized line entries for non-local file.");
1060 // Remap FileID from 1-based old view.
1061 FID += F.SLocEntryBaseID - 1;
1062
1063 // Extract the line entries
1064 unsigned NumEntries = Record[Idx++];
1065 assert(NumEntries && "Numentries is 00000");
1066 Entries.clear();
1067 Entries.reserve(NumEntries);
1068 for (unsigned I = 0; I != NumEntries; ++I) {
1069 unsigned FileOffset = Record[Idx++];
1070 unsigned LineNo = Record[Idx++];
1071 int FilenameID = FileIDs[Record[Idx++]];
1072 SrcMgr::CharacteristicKind FileKind
1073 = (SrcMgr::CharacteristicKind)Record[Idx++];
1074 unsigned IncludeOffset = Record[Idx++];
1075 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1076 FileKind, IncludeOffset));
1077 }
1078 LineTable.AddEntry(FileID::get(FID), Entries);
1079 }
1080
1081 return false;
1082}
1083
1084/// \brief Read a source manager block
1085bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1086 using namespace SrcMgr;
1087
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001088 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001089
1090 // Set the source-location entry cursor to the current position in
1091 // the stream. This cursor will be used to read the contents of the
1092 // source manager block initially, and then lazily read
1093 // source-location entries as needed.
1094 SLocEntryCursor = F.Stream;
1095
1096 // The stream itself is going to skip over the source manager block.
1097 if (F.Stream.SkipBlock()) {
1098 Error("malformed block record in AST file");
1099 return true;
1100 }
1101
1102 // Enter the source manager block.
1103 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1104 Error("malformed source manager block record in AST file");
1105 return true;
1106 }
1107
1108 RecordData Record;
1109 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001110 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1111
1112 switch (E.Kind) {
1113 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1114 case llvm::BitstreamEntry::Error:
1115 Error("malformed block record in AST file");
1116 return true;
1117 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001118 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001119 case llvm::BitstreamEntry::Record:
1120 // The interesting case.
1121 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001122 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001123
Guy Benyei11169dd2012-12-18 14:30:41 +00001124 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001125 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001126 StringRef Blob;
1127 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001128 default: // Default behavior: ignore.
1129 break;
1130
1131 case SM_SLOC_FILE_ENTRY:
1132 case SM_SLOC_BUFFER_ENTRY:
1133 case SM_SLOC_EXPANSION_ENTRY:
1134 // Once we hit one of the source location entries, we're done.
1135 return false;
1136 }
1137 }
1138}
1139
1140/// \brief If a header file is not found at the path that we expect it to be
1141/// and the PCH file was moved from its original location, try to resolve the
1142/// file by assuming that header+PCH were moved together and the header is in
1143/// the same place relative to the PCH.
1144static std::string
1145resolveFileRelativeToOriginalDir(const std::string &Filename,
1146 const std::string &OriginalDir,
1147 const std::string &CurrDir) {
1148 assert(OriginalDir != CurrDir &&
1149 "No point trying to resolve the file if the PCH dir didn't change");
1150 using namespace llvm::sys;
1151 SmallString<128> filePath(Filename);
1152 fs::make_absolute(filePath);
1153 assert(path::is_absolute(OriginalDir));
1154 SmallString<128> currPCHPath(CurrDir);
1155
1156 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1157 fileDirE = path::end(path::parent_path(filePath));
1158 path::const_iterator origDirI = path::begin(OriginalDir),
1159 origDirE = path::end(OriginalDir);
1160 // Skip the common path components from filePath and OriginalDir.
1161 while (fileDirI != fileDirE && origDirI != origDirE &&
1162 *fileDirI == *origDirI) {
1163 ++fileDirI;
1164 ++origDirI;
1165 }
1166 for (; origDirI != origDirE; ++origDirI)
1167 path::append(currPCHPath, "..");
1168 path::append(currPCHPath, fileDirI, fileDirE);
1169 path::append(currPCHPath, path::filename(Filename));
1170 return currPCHPath.str();
1171}
1172
1173bool ASTReader::ReadSLocEntry(int ID) {
1174 if (ID == 0)
1175 return false;
1176
1177 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1178 Error("source location entry ID out-of-range for AST file");
1179 return true;
1180 }
1181
1182 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1183 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001184 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001185 unsigned BaseOffset = F->SLocEntryBaseOffset;
1186
1187 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001188 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1189 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001190 Error("incorrectly-formatted source location entry in AST file");
1191 return true;
1192 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001193
Guy Benyei11169dd2012-12-18 14:30:41 +00001194 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001195 StringRef Blob;
1196 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001197 default:
1198 Error("incorrectly-formatted source location entry in AST file");
1199 return true;
1200
1201 case SM_SLOC_FILE_ENTRY: {
1202 // We will detect whether a file changed and return 'Failure' for it, but
1203 // we will also try to fail gracefully by setting up the SLocEntry.
1204 unsigned InputID = Record[4];
1205 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001206 const FileEntry *File = IF.getFile();
1207 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001208
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001209 // Note that we only check if a File was returned. If it was out-of-date
1210 // we have complained but we will continue creating a FileID to recover
1211 // gracefully.
1212 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001213 return true;
1214
1215 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1216 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1217 // This is the module's main file.
1218 IncludeLoc = getImportLocation(F);
1219 }
1220 SrcMgr::CharacteristicKind
1221 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1222 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1223 ID, BaseOffset + Record[0]);
1224 SrcMgr::FileInfo &FileInfo =
1225 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1226 FileInfo.NumCreatedFIDs = Record[5];
1227 if (Record[3])
1228 FileInfo.setHasLineDirectives();
1229
1230 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1231 unsigned NumFileDecls = Record[7];
1232 if (NumFileDecls) {
1233 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1234 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1235 NumFileDecls));
1236 }
1237
1238 const SrcMgr::ContentCache *ContentCache
1239 = SourceMgr.getOrCreateContentCache(File,
1240 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1241 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1242 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1243 unsigned Code = SLocEntryCursor.ReadCode();
1244 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001245 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001246
1247 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1248 Error("AST record has invalid code");
1249 return true;
1250 }
1251
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001252 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001253 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001254 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001255 }
1256
1257 break;
1258 }
1259
1260 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001261 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001262 unsigned Offset = Record[0];
1263 SrcMgr::CharacteristicKind
1264 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1265 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001266 if (IncludeLoc.isInvalid() &&
1267 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001268 IncludeLoc = getImportLocation(F);
1269 }
1270 unsigned Code = SLocEntryCursor.ReadCode();
1271 Record.clear();
1272 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001273 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001274
1275 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1276 Error("AST record has invalid code");
1277 return true;
1278 }
1279
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001280 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1281 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001282 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001283 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001284 break;
1285 }
1286
1287 case SM_SLOC_EXPANSION_ENTRY: {
1288 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1289 SourceMgr.createExpansionLoc(SpellingLoc,
1290 ReadSourceLocation(*F, Record[2]),
1291 ReadSourceLocation(*F, Record[3]),
1292 Record[4],
1293 ID,
1294 BaseOffset + Record[0]);
1295 break;
1296 }
1297 }
1298
1299 return false;
1300}
1301
1302std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1303 if (ID == 0)
1304 return std::make_pair(SourceLocation(), "");
1305
1306 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1307 Error("source location entry ID out-of-range for AST file");
1308 return std::make_pair(SourceLocation(), "");
1309 }
1310
1311 // Find which module file this entry lands in.
1312 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001313 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001314 return std::make_pair(SourceLocation(), "");
1315
1316 // FIXME: Can we map this down to a particular submodule? That would be
1317 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001318 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001319}
1320
1321/// \brief Find the location where the module F is imported.
1322SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1323 if (F->ImportLoc.isValid())
1324 return F->ImportLoc;
1325
1326 // Otherwise we have a PCH. It's considered to be "imported" at the first
1327 // location of its includer.
1328 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001329 // Main file is the importer.
1330 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1331 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001332 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001333 return F->ImportedBy[0]->FirstLoc;
1334}
1335
1336/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1337/// specified cursor. Read the abbreviations that are at the top of the block
1338/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001339bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001340 if (Cursor.EnterSubBlock(BlockID)) {
1341 Error("malformed block record in AST file");
1342 return Failure;
1343 }
1344
1345 while (true) {
1346 uint64_t Offset = Cursor.GetCurrentBitNo();
1347 unsigned Code = Cursor.ReadCode();
1348
1349 // We expect all abbrevs to be at the start of the block.
1350 if (Code != llvm::bitc::DEFINE_ABBREV) {
1351 Cursor.JumpToBit(Offset);
1352 return false;
1353 }
1354 Cursor.ReadAbbrevRecord();
1355 }
1356}
1357
Richard Smithe40f2ba2013-08-07 21:41:30 +00001358Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001359 unsigned &Idx) {
1360 Token Tok;
1361 Tok.startToken();
1362 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1363 Tok.setLength(Record[Idx++]);
1364 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1365 Tok.setIdentifierInfo(II);
1366 Tok.setKind((tok::TokenKind)Record[Idx++]);
1367 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1368 return Tok;
1369}
1370
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001371MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001372 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001373
1374 // Keep track of where we are in the stream, then jump back there
1375 // after reading this macro.
1376 SavedStreamPosition SavedPosition(Stream);
1377
1378 Stream.JumpToBit(Offset);
1379 RecordData Record;
1380 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001381 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001382
Guy Benyei11169dd2012-12-18 14:30:41 +00001383 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001384 // Advance to the next record, but if we get to the end of the block, don't
1385 // pop it (removing all the abbreviations from the cursor) since we want to
1386 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001387 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001388 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1389
1390 switch (Entry.Kind) {
1391 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1392 case llvm::BitstreamEntry::Error:
1393 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001394 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001395 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001396 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001397 case llvm::BitstreamEntry::Record:
1398 // The interesting case.
1399 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001400 }
1401
1402 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001403 Record.clear();
1404 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001405 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001406 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001407 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001408 case PP_MACRO_DIRECTIVE_HISTORY:
1409 return Macro;
1410
Guy Benyei11169dd2012-12-18 14:30:41 +00001411 case PP_MACRO_OBJECT_LIKE:
1412 case PP_MACRO_FUNCTION_LIKE: {
1413 // If we already have a macro, that means that we've hit the end
1414 // of the definition of the macro we were looking for. We're
1415 // done.
1416 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001417 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001418
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001419 unsigned NextIndex = 1; // Skip identifier ID.
1420 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001421 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001422 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001423 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001424 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001425 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001426
Guy Benyei11169dd2012-12-18 14:30:41 +00001427 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1428 // Decode function-like macro info.
1429 bool isC99VarArgs = Record[NextIndex++];
1430 bool isGNUVarArgs = Record[NextIndex++];
1431 bool hasCommaPasting = Record[NextIndex++];
1432 MacroArgs.clear();
1433 unsigned NumArgs = Record[NextIndex++];
1434 for (unsigned i = 0; i != NumArgs; ++i)
1435 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1436
1437 // Install function-like macro info.
1438 MI->setIsFunctionLike();
1439 if (isC99VarArgs) MI->setIsC99Varargs();
1440 if (isGNUVarArgs) MI->setIsGNUVarargs();
1441 if (hasCommaPasting) MI->setHasCommaPasting();
1442 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1443 PP.getPreprocessorAllocator());
1444 }
1445
Guy Benyei11169dd2012-12-18 14:30:41 +00001446 // Remember that we saw this macro last so that we add the tokens that
1447 // form its body to it.
1448 Macro = MI;
1449
1450 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1451 Record[NextIndex]) {
1452 // We have a macro definition. Register the association
1453 PreprocessedEntityID
1454 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1455 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001456 PreprocessingRecord::PPEntityID PPID =
1457 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1458 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1459 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001460 if (PPDef)
1461 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001462 }
1463
1464 ++NumMacrosRead;
1465 break;
1466 }
1467
1468 case PP_TOKEN: {
1469 // If we see a TOKEN before a PP_MACRO_*, then the file is
1470 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001471 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001472
John McCallf413f5e2013-05-03 00:10:13 +00001473 unsigned Idx = 0;
1474 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001475 Macro->AddTokenToBody(Tok);
1476 break;
1477 }
1478 }
1479 }
1480}
1481
1482PreprocessedEntityID
1483ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1484 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1485 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1486 assert(I != M.PreprocessedEntityRemap.end()
1487 && "Invalid index into preprocessed entity index remap");
1488
1489 return LocalID + I->second;
1490}
1491
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001492unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1493 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001494}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001495
Guy Benyei11169dd2012-12-18 14:30:41 +00001496HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001497HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1498 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
Richard Smith7ed1bc92014-12-05 22:42:13 +00001499 FE->getName(), /*Imported*/false };
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001500 return ikey;
1501}
Guy Benyei11169dd2012-12-18 14:30:41 +00001502
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001503bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1504 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001505 return false;
1506
Richard Smith7ed1bc92014-12-05 22:42:13 +00001507 if (llvm::sys::path::is_absolute(a.Filename) &&
1508 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001509 return true;
1510
Guy Benyei11169dd2012-12-18 14:30:41 +00001511 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001512 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001513 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1514 if (!Key.Imported)
1515 return FileMgr.getFile(Key.Filename);
1516
1517 std::string Resolved = Key.Filename;
1518 Reader.ResolveImportedPath(M, Resolved);
1519 return FileMgr.getFile(Resolved);
1520 };
1521
1522 const FileEntry *FEA = GetFile(a);
1523 const FileEntry *FEB = GetFile(b);
1524 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001525}
1526
1527std::pair<unsigned, unsigned>
1528HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001529 using namespace llvm::support;
1530 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001531 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001532 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001533}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001534
1535HeaderFileInfoTrait::internal_key_type
1536HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001537 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001538 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001539 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1540 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001541 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001542 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001543 return ikey;
1544}
1545
Guy Benyei11169dd2012-12-18 14:30:41 +00001546HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001547HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001548 unsigned DataLen) {
1549 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001550 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001551 HeaderFileInfo HFI;
1552 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001553 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1554 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001555 HFI.isImport = (Flags >> 5) & 0x01;
1556 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1557 HFI.DirInfo = (Flags >> 2) & 0x03;
1558 HFI.Resolved = (Flags >> 1) & 0x01;
1559 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001560 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1561 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1562 M, endian::readNext<uint32_t, little, unaligned>(d));
1563 if (unsigned FrameworkOffset =
1564 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001565 // The framework offset is 1 greater than the actual offset,
1566 // since 0 is used as an indicator for "no framework name".
1567 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1568 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1569 }
1570
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001571 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001572 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001573 if (LocalSMID) {
1574 // This header is part of a module. Associate it with the module to enable
1575 // implicit module import.
1576 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1577 Module *Mod = Reader.getSubmodule(GlobalSMID);
1578 HFI.isModuleHeader = true;
1579 FileManager &FileMgr = Reader.getFileManager();
1580 ModuleMap &ModMap =
1581 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001582 // FIXME: This information should be propagated through the
1583 // SUBMODULE_HEADER etc records rather than from here.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001584 // FIXME: We don't ever mark excluded headers.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001585 std::string Filename = key.Filename;
1586 if (key.Imported)
1587 Reader.ResolveImportedPath(M, Filename);
1588 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Hans Wennborg0101b542014-12-02 02:13:09 +00001589 ModMap.addHeader(Mod, H, HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001590 }
1591 }
1592
Guy Benyei11169dd2012-12-18 14:30:41 +00001593 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1594 (void)End;
1595
1596 // This HeaderFileInfo was externally loaded.
1597 HFI.External = true;
1598 return HFI;
1599}
1600
Richard Smithd7329392015-04-21 21:46:32 +00001601void ASTReader::addPendingMacro(IdentifierInfo *II,
1602 ModuleFile *M,
1603 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001604 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1605 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001606}
1607
1608void ASTReader::ReadDefinedMacros() {
1609 // Note that we are loading defined macros.
1610 Deserializing Macros(this);
1611
Pete Cooper57d3f142015-07-30 17:22:52 +00001612 for (auto &I : llvm::reverse(ModuleMgr)) {
1613 BitstreamCursor &MacroCursor = I->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001614
1615 // If there was no preprocessor block, skip this file.
1616 if (!MacroCursor.getBitStreamReader())
1617 continue;
1618
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001619 BitstreamCursor Cursor = MacroCursor;
Pete Cooper57d3f142015-07-30 17:22:52 +00001620 Cursor.JumpToBit(I->MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001621
1622 RecordData Record;
1623 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001624 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1625
1626 switch (E.Kind) {
1627 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1628 case llvm::BitstreamEntry::Error:
1629 Error("malformed block record in AST file");
1630 return;
1631 case llvm::BitstreamEntry::EndBlock:
1632 goto NextCursor;
1633
1634 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001635 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001636 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001637 default: // Default behavior: ignore.
1638 break;
1639
1640 case PP_MACRO_OBJECT_LIKE:
1641 case PP_MACRO_FUNCTION_LIKE:
Pete Cooper57d3f142015-07-30 17:22:52 +00001642 getLocalIdentifier(*I, Record[0]);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001643 break;
1644
1645 case PP_TOKEN:
1646 // Ignore tokens.
1647 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001648 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001649 break;
1650 }
1651 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001652 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001653 }
1654}
1655
1656namespace {
1657 /// \brief Visitor class used to look up identifirs in an AST file.
1658 class IdentifierLookupVisitor {
1659 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001660 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001661 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001662 unsigned &NumIdentifierLookups;
1663 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001664 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001665
Guy Benyei11169dd2012-12-18 14:30:41 +00001666 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001667 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1668 unsigned &NumIdentifierLookups,
1669 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001670 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1671 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001672 NumIdentifierLookups(NumIdentifierLookups),
1673 NumIdentifierLookupHits(NumIdentifierLookupHits),
1674 Found()
1675 {
1676 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001677
1678 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001679 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001680 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001681 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001682
Guy Benyei11169dd2012-12-18 14:30:41 +00001683 ASTIdentifierLookupTable *IdTable
1684 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1685 if (!IdTable)
1686 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001687
1688 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001689 Found);
1690 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001691 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001692 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001693 if (Pos == IdTable->end())
1694 return false;
1695
1696 // Dereferencing the iterator has the effect of building the
1697 // IdentifierInfo node and populating it with the various
1698 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001699 ++NumIdentifierLookupHits;
1700 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001701 return true;
1702 }
1703
1704 // \brief Retrieve the identifier info found within the module
1705 // files.
1706 IdentifierInfo *getIdentifierInfo() const { return Found; }
1707 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001708}
Guy Benyei11169dd2012-12-18 14:30:41 +00001709
1710void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1711 // Note that we are loading an identifier.
1712 Deserializing AnIdentifier(this);
1713
1714 unsigned PriorGeneration = 0;
1715 if (getContext().getLangOpts().Modules)
1716 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001717
1718 // If there is a global index, look there first to determine which modules
1719 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001720 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001721 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001722 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001723 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1724 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001725 }
1726 }
1727
Douglas Gregor7211ac12013-01-25 23:32:03 +00001728 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001729 NumIdentifierLookups,
1730 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001731 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001732 markIdentifierUpToDate(&II);
1733}
1734
1735void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1736 if (!II)
1737 return;
1738
1739 II->setOutOfDate(false);
1740
1741 // Update the generation for this identifier.
1742 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001743 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001744}
1745
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001746void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1747 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001748 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001749
1750 BitstreamCursor &Cursor = M.MacroCursor;
1751 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001752 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001753
Richard Smith713369b2015-04-23 20:40:50 +00001754 struct ModuleMacroRecord {
1755 SubmoduleID SubModID;
1756 MacroInfo *MI;
1757 SmallVector<SubmoduleID, 8> Overrides;
1758 };
1759 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001760
Richard Smithd7329392015-04-21 21:46:32 +00001761 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1762 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1763 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001764 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001765 while (true) {
1766 llvm::BitstreamEntry Entry =
1767 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1768 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1769 Error("malformed block record in AST file");
1770 return;
1771 }
1772
1773 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001774 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001775 case PP_MACRO_DIRECTIVE_HISTORY:
1776 break;
1777
1778 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001779 ModuleMacros.push_back(ModuleMacroRecord());
1780 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001781 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1782 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001783 for (int I = 2, N = Record.size(); I != N; ++I)
1784 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001785 continue;
1786 }
1787
1788 default:
1789 Error("malformed block record in AST file");
1790 return;
1791 }
1792
1793 // We found the macro directive history; that's the last record
1794 // for this macro.
1795 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001796 }
1797
Richard Smithd7329392015-04-21 21:46:32 +00001798 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001799 {
1800 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001801 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001802 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001803 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001804 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001805 Module *Mod = getSubmodule(ModID);
1806 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001807 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001808 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001809 }
1810
1811 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001812 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001813 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001814 }
1815 }
1816
1817 // Don't read the directive history for a module; we don't have anywhere
1818 // to put it.
1819 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1820 return;
1821
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001822 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001823 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001824 unsigned Idx = 0, N = Record.size();
1825 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001826 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001827 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001828 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1829 switch (K) {
1830 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001831 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001832 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001833 break;
1834 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001835 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001836 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001837 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001838 }
1839 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001840 bool isPublic = Record[Idx++];
1841 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1842 break;
1843 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001844
1845 if (!Latest)
1846 Latest = MD;
1847 if (Earliest)
1848 Earliest->setPrevious(MD);
1849 Earliest = MD;
1850 }
1851
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001852 if (Latest)
1853 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001854}
1855
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001856ASTReader::InputFileInfo
1857ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001858 // Go find this input file.
1859 BitstreamCursor &Cursor = F.InputFilesCursor;
1860 SavedStreamPosition SavedPosition(Cursor);
1861 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1862
1863 unsigned Code = Cursor.ReadCode();
1864 RecordData Record;
1865 StringRef Blob;
1866
1867 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1868 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1869 "invalid record type for input file");
1870 (void)Result;
1871
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001872 std::string Filename;
1873 off_t StoredSize;
1874 time_t StoredTime;
1875 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001876
Ben Langmuir198c1682014-03-07 07:27:49 +00001877 assert(Record[0] == ID && "Bogus stored ID or offset");
1878 StoredSize = static_cast<off_t>(Record[1]);
1879 StoredTime = static_cast<time_t>(Record[2]);
1880 Overridden = static_cast<bool>(Record[3]);
1881 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001882 ResolveImportedPath(F, Filename);
1883
Hans Wennborg73945142014-03-14 17:45:06 +00001884 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1885 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001886}
1887
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001888InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001889 // If this ID is bogus, just return an empty input file.
1890 if (ID == 0 || ID > F.InputFilesLoaded.size())
1891 return InputFile();
1892
1893 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001894 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001895 return F.InputFilesLoaded[ID-1];
1896
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001897 if (F.InputFilesLoaded[ID-1].isNotFound())
1898 return InputFile();
1899
Guy Benyei11169dd2012-12-18 14:30:41 +00001900 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001901 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001902 SavedStreamPosition SavedPosition(Cursor);
1903 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1904
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001905 InputFileInfo FI = readInputFileInfo(F, ID);
1906 off_t StoredSize = FI.StoredSize;
1907 time_t StoredTime = FI.StoredTime;
1908 bool Overridden = FI.Overridden;
1909 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001910
Ben Langmuir198c1682014-03-07 07:27:49 +00001911 const FileEntry *File
1912 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1913 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1914
1915 // If we didn't find the file, resolve it relative to the
1916 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00001917 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00001918 F.OriginalDir != CurrentDir) {
1919 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1920 F.OriginalDir,
1921 CurrentDir);
1922 if (!Resolved.empty())
1923 File = FileMgr.getFile(Resolved);
1924 }
1925
1926 // For an overridden file, create a virtual file with the stored
1927 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00001928 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001929 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1930 }
1931
Craig Toppera13603a2014-05-22 05:54:18 +00001932 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001933 if (Complain) {
1934 std::string ErrorStr = "could not find file '";
1935 ErrorStr += Filename;
1936 ErrorStr += "' referenced by AST file";
1937 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001938 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001939 // Record that we didn't find the file.
1940 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1941 return InputFile();
1942 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001943
Ben Langmuir198c1682014-03-07 07:27:49 +00001944 // Check if there was a request to override the contents of the file
1945 // that was part of the precompiled header. Overridding such a file
1946 // can lead to problems when lexing using the source locations from the
1947 // PCH.
1948 SourceManager &SM = getSourceManager();
1949 if (!Overridden && SM.isFileOverridden(File)) {
1950 if (Complain)
1951 Error(diag::err_fe_pch_file_overridden, Filename);
1952 // After emitting the diagnostic, recover by disabling the override so
1953 // that the original file will be used.
1954 SM.disableFileContentsOverride(File);
1955 // The FileEntry is a virtual file entry with the size of the contents
1956 // that would override the original contents. Set it to the original's
1957 // size/time.
1958 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1959 StoredSize, StoredTime);
1960 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001961
Ben Langmuir198c1682014-03-07 07:27:49 +00001962 bool IsOutOfDate = false;
1963
1964 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00001965 if (!Overridden && //
1966 (StoredSize != File->getSize() ||
1967#if defined(LLVM_ON_WIN32)
1968 false
1969#else
Ben Langmuir198c1682014-03-07 07:27:49 +00001970 // In our regression testing, the Windows file system seems to
1971 // have inconsistent modification times that sometimes
1972 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00001973 //
1974 // This also happens in networked file systems, so disable this
1975 // check if validation is disabled or if we have an explicitly
1976 // built PCM file.
1977 //
1978 // FIXME: Should we also do this for PCH files? They could also
1979 // reasonably get shared across a network during a distributed build.
1980 (StoredTime != File->getModificationTime() && !DisableValidation &&
1981 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001982#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00001983 )) {
1984 if (Complain) {
1985 // Build a list of the PCH imports that got us here (in reverse).
1986 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1987 while (ImportStack.back()->ImportedBy.size() > 0)
1988 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00001989
Ben Langmuir198c1682014-03-07 07:27:49 +00001990 // The top-level PCH is stale.
1991 StringRef TopLevelPCHName(ImportStack.back()->FileName);
1992 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00001993
Ben Langmuir198c1682014-03-07 07:27:49 +00001994 // Print the import stack.
1995 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
1996 Diag(diag::note_pch_required_by)
1997 << Filename << ImportStack[0]->FileName;
1998 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00001999 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002000 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002001 }
2002
Ben Langmuir198c1682014-03-07 07:27:49 +00002003 if (!Diags.isDiagnosticInFlight())
2004 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002005 }
2006
Ben Langmuir198c1682014-03-07 07:27:49 +00002007 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002008 }
2009
Ben Langmuir198c1682014-03-07 07:27:49 +00002010 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2011
2012 // Note that we've loaded this input file.
2013 F.InputFilesLoaded[ID-1] = IF;
2014 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002015}
2016
Richard Smith7ed1bc92014-12-05 22:42:13 +00002017/// \brief If we are loading a relocatable PCH or module file, and the filename
2018/// is not an absolute path, add the system or module root to the beginning of
2019/// the file name.
2020void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2021 // Resolve relative to the base directory, if we have one.
2022 if (!M.BaseDirectory.empty())
2023 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002024}
2025
Richard Smith7ed1bc92014-12-05 22:42:13 +00002026void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002027 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2028 return;
2029
Richard Smith7ed1bc92014-12-05 22:42:13 +00002030 SmallString<128> Buffer;
2031 llvm::sys::path::append(Buffer, Prefix, Filename);
2032 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002033}
2034
Richard Smith0f99d6a2015-08-09 08:48:41 +00002035static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2036 switch (ARR) {
2037 case ASTReader::Failure: return true;
2038 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2039 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2040 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2041 case ASTReader::ConfigurationMismatch:
2042 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2043 case ASTReader::HadErrors: return true;
2044 case ASTReader::Success: return false;
2045 }
2046
2047 llvm_unreachable("unknown ASTReadResult");
2048}
2049
Guy Benyei11169dd2012-12-18 14:30:41 +00002050ASTReader::ASTReadResult
2051ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002052 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002053 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002054 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002055 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002056
2057 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2058 Error("malformed block record in AST file");
2059 return Failure;
2060 }
2061
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002062 // Should we allow the configuration of the module file to differ from the
2063 // configuration of the current translation unit in a compatible way?
2064 //
2065 // FIXME: Allow this for files explicitly specified with -include-pch too.
2066 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2067
Guy Benyei11169dd2012-12-18 14:30:41 +00002068 // Read all of the records and blocks in the control block.
2069 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002070 unsigned NumInputs = 0;
2071 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002072 while (1) {
2073 llvm::BitstreamEntry Entry = Stream.advance();
2074
2075 switch (Entry.Kind) {
2076 case llvm::BitstreamEntry::Error:
2077 Error("malformed block record in AST file");
2078 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002079 case llvm::BitstreamEntry::EndBlock: {
2080 // Validate input files.
2081 const HeaderSearchOptions &HSOpts =
2082 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002083
Richard Smitha1825302014-10-23 22:18:29 +00002084 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002085 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2086 // loaded module files, ignore missing inputs.
2087 if (!DisableValidation && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002088 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002089
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002090 // If we are reading a module, we will create a verification timestamp,
2091 // so we verify all input files. Otherwise, verify only user input
2092 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002093
2094 unsigned N = NumUserInputs;
2095 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002096 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002097 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002098 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002099 N = NumInputs;
2100
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002101 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002102 InputFile IF = getInputFile(F, I+1, Complain);
2103 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002104 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002105 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002106 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002107
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002108 if (Listener)
2109 Listener->visitModuleFile(F.FileName);
2110
Ben Langmuircb69b572014-03-07 06:40:32 +00002111 if (Listener && Listener->needsInputFileVisitation()) {
2112 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2113 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002114 for (unsigned I = 0; I < N; ++I) {
2115 bool IsSystem = I >= NumUserInputs;
2116 InputFileInfo FI = readInputFileInfo(F, I+1);
2117 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2118 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002119 }
2120
Guy Benyei11169dd2012-12-18 14:30:41 +00002121 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002122 }
2123
Chris Lattnere7b154b2013-01-19 21:39:22 +00002124 case llvm::BitstreamEntry::SubBlock:
2125 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002126 case INPUT_FILES_BLOCK_ID:
2127 F.InputFilesCursor = Stream;
2128 if (Stream.SkipBlock() || // Skip with the main cursor
2129 // Read the abbreviations
2130 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2131 Error("malformed block record in AST file");
2132 return Failure;
2133 }
2134 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002135
Guy Benyei11169dd2012-12-18 14:30:41 +00002136 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002137 if (Stream.SkipBlock()) {
2138 Error("malformed block record in AST file");
2139 return Failure;
2140 }
2141 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002142 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002143
2144 case llvm::BitstreamEntry::Record:
2145 // The interesting case.
2146 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002147 }
2148
2149 // Read and process a record.
2150 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002151 StringRef Blob;
2152 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002153 case METADATA: {
2154 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2155 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002156 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2157 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002158 return VersionMismatch;
2159 }
2160
2161 bool hasErrors = Record[5];
2162 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2163 Diag(diag::err_pch_with_compiler_errors);
2164 return HadErrors;
2165 }
2166
2167 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002168 // Relative paths in a relocatable PCH are relative to our sysroot.
2169 if (F.RelocatablePCH)
2170 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002171
2172 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002173 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002174 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2175 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002176 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002177 return VersionMismatch;
2178 }
2179 break;
2180 }
2181
Ben Langmuir487ea142014-10-23 18:05:36 +00002182 case SIGNATURE:
2183 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2184 F.Signature = Record[0];
2185 break;
2186
Guy Benyei11169dd2012-12-18 14:30:41 +00002187 case IMPORTS: {
2188 // Load each of the imported PCH files.
2189 unsigned Idx = 0, N = Record.size();
2190 while (Idx < N) {
2191 // Read information about the AST file.
2192 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2193 // The import location will be the local one for now; we will adjust
2194 // all import locations of module imports after the global source
2195 // location info are setup.
2196 SourceLocation ImportLoc =
2197 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002198 off_t StoredSize = (off_t)Record[Idx++];
2199 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002200 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002201 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002202
Richard Smith0f99d6a2015-08-09 08:48:41 +00002203 // If our client can't cope with us being out of date, we can't cope with
2204 // our dependency being missing.
2205 unsigned Capabilities = ClientLoadCapabilities;
2206 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2207 Capabilities &= ~ARR_Missing;
2208
Guy Benyei11169dd2012-12-18 14:30:41 +00002209 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002210 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2211 Loaded, StoredSize, StoredModTime,
2212 StoredSignature, Capabilities);
2213
2214 // If we diagnosed a problem, produce a backtrace.
2215 if (isDiagnosedResult(Result, Capabilities))
2216 Diag(diag::note_module_file_imported_by)
2217 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2218
2219 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002220 case Failure: return Failure;
2221 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002222 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002223 case OutOfDate: return OutOfDate;
2224 case VersionMismatch: return VersionMismatch;
2225 case ConfigurationMismatch: return ConfigurationMismatch;
2226 case HadErrors: return HadErrors;
2227 case Success: break;
2228 }
2229 }
2230 break;
2231 }
2232
2233 case LANGUAGE_OPTIONS: {
2234 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002235 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002236 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002237 ParseLanguageOptions(Record, Complain, *Listener,
2238 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002239 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002240 return ConfigurationMismatch;
2241 break;
2242 }
2243
2244 case TARGET_OPTIONS: {
2245 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2246 if (Listener && &F == *ModuleMgr.begin() &&
Chandler Carruth0d745bc2015-03-14 04:47:43 +00002247 ParseTargetOptions(Record, Complain, *Listener,
2248 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002249 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002250 return ConfigurationMismatch;
2251 break;
2252 }
2253
2254 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002255 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002256 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002257 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002258 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002259 !DisableValidation)
2260 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002261 break;
2262 }
2263
2264 case FILE_SYSTEM_OPTIONS: {
2265 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2266 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002267 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002268 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002269 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002270 return ConfigurationMismatch;
2271 break;
2272 }
2273
2274 case HEADER_SEARCH_OPTIONS: {
2275 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2276 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002277 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002278 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002279 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002280 return ConfigurationMismatch;
2281 break;
2282 }
2283
2284 case PREPROCESSOR_OPTIONS: {
2285 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2286 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002287 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002288 ParsePreprocessorOptions(Record, Complain, *Listener,
2289 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002290 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002291 return ConfigurationMismatch;
2292 break;
2293 }
2294
2295 case ORIGINAL_FILE:
2296 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002297 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002298 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002299 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002300 break;
2301
2302 case ORIGINAL_FILE_ID:
2303 F.OriginalSourceFileID = FileID::get(Record[0]);
2304 break;
2305
2306 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002307 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002308 break;
2309
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002310 case MODULE_NAME:
2311 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002312 if (Listener)
2313 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002314 break;
2315
Richard Smith223d3f22014-12-06 03:21:08 +00002316 case MODULE_DIRECTORY: {
2317 assert(!F.ModuleName.empty() &&
2318 "MODULE_DIRECTORY found before MODULE_NAME");
2319 // If we've already loaded a module map file covering this module, we may
2320 // have a better path for it (relative to the current build).
2321 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2322 if (M && M->Directory) {
2323 // If we're implicitly loading a module, the base directory can't
2324 // change between the build and use.
2325 if (F.Kind != MK_ExplicitModule) {
2326 const DirectoryEntry *BuildDir =
2327 PP.getFileManager().getDirectory(Blob);
2328 if (!BuildDir || BuildDir != M->Directory) {
2329 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2330 Diag(diag::err_imported_module_relocated)
2331 << F.ModuleName << Blob << M->Directory->getName();
2332 return OutOfDate;
2333 }
2334 }
2335 F.BaseDirectory = M->Directory->getName();
2336 } else {
2337 F.BaseDirectory = Blob;
2338 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002339 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002340 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002341
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002342 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002343 if (ASTReadResult Result =
2344 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2345 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002346 break;
2347
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002348 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002349 NumInputs = Record[0];
2350 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002351 F.InputFileOffsets =
2352 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002353 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002354 break;
2355 }
2356 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002357}
2358
Ben Langmuir2c9af442014-04-10 17:57:43 +00002359ASTReader::ASTReadResult
2360ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002361 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002362
2363 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2364 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002365 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002366 }
2367
2368 // Read all of the records and blocks for the AST file.
2369 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002370 while (1) {
2371 llvm::BitstreamEntry Entry = Stream.advance();
2372
2373 switch (Entry.Kind) {
2374 case llvm::BitstreamEntry::Error:
2375 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002376 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002377 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002378 // Outside of C++, we do not store a lookup map for the translation unit.
2379 // Instead, mark it as needing a lookup map to be built if this module
2380 // contains any declarations lexically within it (which it always does!).
2381 // This usually has no cost, since we very rarely need the lookup map for
2382 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002383 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002384 if (DC->hasExternalLexicalStorage() &&
2385 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002386 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002387
Ben Langmuir2c9af442014-04-10 17:57:43 +00002388 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002389 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002390 case llvm::BitstreamEntry::SubBlock:
2391 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002392 case DECLTYPES_BLOCK_ID:
2393 // We lazily load the decls block, but we want to set up the
2394 // DeclsCursor cursor to point into it. Clone our current bitcode
2395 // cursor to it, enter the block and read the abbrevs in that block.
2396 // With the main cursor, we just skip over it.
2397 F.DeclsCursor = Stream;
2398 if (Stream.SkipBlock() || // Skip with the main cursor.
2399 // Read the abbrevs.
2400 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2401 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002402 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002403 }
2404 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002405
Guy Benyei11169dd2012-12-18 14:30:41 +00002406 case PREPROCESSOR_BLOCK_ID:
2407 F.MacroCursor = Stream;
2408 if (!PP.getExternalSource())
2409 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002410
Guy Benyei11169dd2012-12-18 14:30:41 +00002411 if (Stream.SkipBlock() ||
2412 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2413 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002414 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002415 }
2416 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2417 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002418
Guy Benyei11169dd2012-12-18 14:30:41 +00002419 case PREPROCESSOR_DETAIL_BLOCK_ID:
2420 F.PreprocessorDetailCursor = Stream;
2421 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002422 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002423 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002424 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002425 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002426 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002427 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002428 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2429
Guy Benyei11169dd2012-12-18 14:30:41 +00002430 if (!PP.getPreprocessingRecord())
2431 PP.createPreprocessingRecord();
2432 if (!PP.getPreprocessingRecord()->getExternalSource())
2433 PP.getPreprocessingRecord()->SetExternalSource(*this);
2434 break;
2435
2436 case SOURCE_MANAGER_BLOCK_ID:
2437 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002438 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002439 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002440
Guy Benyei11169dd2012-12-18 14:30:41 +00002441 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002442 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2443 return Result;
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 COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002447 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002448 if (Stream.SkipBlock() ||
2449 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2450 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002451 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002452 }
2453 CommentsCursors.push_back(std::make_pair(C, &F));
2454 break;
2455 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002456
Guy Benyei11169dd2012-12-18 14:30:41 +00002457 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002458 if (Stream.SkipBlock()) {
2459 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002460 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002461 }
2462 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002463 }
2464 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002465
2466 case llvm::BitstreamEntry::Record:
2467 // The interesting case.
2468 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002469 }
2470
2471 // Read and process a record.
2472 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002473 StringRef Blob;
2474 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002475 default: // Default behavior: ignore.
2476 break;
2477
2478 case TYPE_OFFSET: {
2479 if (F.LocalNumTypes != 0) {
2480 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002481 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002482 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002483 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002484 F.LocalNumTypes = Record[0];
2485 unsigned LocalBaseTypeIndex = Record[1];
2486 F.BaseTypeIndex = getTotalNumTypes();
2487
2488 if (F.LocalNumTypes > 0) {
2489 // Introduce the global -> local mapping for types within this module.
2490 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2491
2492 // Introduce the local -> global mapping for types within this module.
2493 F.TypeRemap.insertOrReplace(
2494 std::make_pair(LocalBaseTypeIndex,
2495 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002496
2497 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002498 }
2499 break;
2500 }
2501
2502 case DECL_OFFSET: {
2503 if (F.LocalNumDecls != 0) {
2504 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002505 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002506 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002507 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002508 F.LocalNumDecls = Record[0];
2509 unsigned LocalBaseDeclID = Record[1];
2510 F.BaseDeclID = getTotalNumDecls();
2511
2512 if (F.LocalNumDecls > 0) {
2513 // Introduce the global -> local mapping for declarations within this
2514 // module.
2515 GlobalDeclMap.insert(
2516 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2517
2518 // Introduce the local -> global mapping for declarations within this
2519 // module.
2520 F.DeclRemap.insertOrReplace(
2521 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2522
2523 // Introduce the global -> local mapping for declarations within this
2524 // module.
2525 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002526
Ben Langmuir52ca6782014-10-20 16:27:32 +00002527 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2528 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002529 break;
2530 }
2531
2532 case TU_UPDATE_LEXICAL: {
2533 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002534 LexicalContents Contents(
2535 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2536 Blob.data()),
2537 static_cast<unsigned int>(Blob.size() / 4));
2538 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002539 TU->setHasExternalLexicalStorage(true);
2540 break;
2541 }
2542
2543 case UPDATE_VISIBLE: {
2544 unsigned Idx = 0;
2545 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002546 auto *Data = (const unsigned char*)Blob.data();
2547 unsigned BucketOffset = Record[Idx++];
2548 PendingVisibleUpdates[ID].push_back(
2549 PendingVisibleUpdate{&F, Data, BucketOffset});
2550 // If we've already loaded the decl, perform the updates when we finish
2551 // loading this block.
2552 if (Decl *D = GetExistingDecl(ID))
2553 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002554 break;
2555 }
2556
2557 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002558 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002559 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002560 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2561 (const unsigned char *)F.IdentifierTableData + Record[0],
2562 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2563 (const unsigned char *)F.IdentifierTableData,
2564 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002565
2566 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2567 }
2568 break;
2569
2570 case IDENTIFIER_OFFSET: {
2571 if (F.LocalNumIdentifiers != 0) {
2572 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002573 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002574 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002575 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002576 F.LocalNumIdentifiers = Record[0];
2577 unsigned LocalBaseIdentifierID = Record[1];
2578 F.BaseIdentifierID = getTotalNumIdentifiers();
2579
2580 if (F.LocalNumIdentifiers > 0) {
2581 // Introduce the global -> local mapping for identifiers within this
2582 // module.
2583 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2584 &F));
2585
2586 // Introduce the local -> global mapping for identifiers within this
2587 // module.
2588 F.IdentifierRemap.insertOrReplace(
2589 std::make_pair(LocalBaseIdentifierID,
2590 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002591
Ben Langmuir52ca6782014-10-20 16:27:32 +00002592 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2593 + F.LocalNumIdentifiers);
2594 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 break;
2596 }
2597
Richard Smith33e0f7e2015-07-22 02:08:40 +00002598 case INTERESTING_IDENTIFIERS:
2599 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2600 break;
2601
Ben Langmuir332aafe2014-01-31 01:06:56 +00002602 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002603 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2604 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002605 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002606 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002607 break;
2608
2609 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002610 if (SpecialTypes.empty()) {
2611 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2612 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2613 break;
2614 }
2615
2616 if (SpecialTypes.size() != Record.size()) {
2617 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002618 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002619 }
2620
2621 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2622 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2623 if (!SpecialTypes[I])
2624 SpecialTypes[I] = ID;
2625 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2626 // merge step?
2627 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002628 break;
2629
2630 case STATISTICS:
2631 TotalNumStatements += Record[0];
2632 TotalNumMacros += Record[1];
2633 TotalLexicalDeclContexts += Record[2];
2634 TotalVisibleDeclContexts += Record[3];
2635 break;
2636
2637 case UNUSED_FILESCOPED_DECLS:
2638 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2639 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2640 break;
2641
2642 case DELEGATING_CTORS:
2643 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2644 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2645 break;
2646
2647 case WEAK_UNDECLARED_IDENTIFIERS:
2648 if (Record.size() % 4 != 0) {
2649 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002650 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002651 }
2652
2653 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2654 // files. This isn't the way to do it :)
2655 WeakUndeclaredIdentifiers.clear();
2656
2657 // Translate the weak, undeclared identifiers into global IDs.
2658 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2659 WeakUndeclaredIdentifiers.push_back(
2660 getGlobalIdentifierID(F, Record[I++]));
2661 WeakUndeclaredIdentifiers.push_back(
2662 getGlobalIdentifierID(F, Record[I++]));
2663 WeakUndeclaredIdentifiers.push_back(
2664 ReadSourceLocation(F, Record, I).getRawEncoding());
2665 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2666 }
2667 break;
2668
Guy Benyei11169dd2012-12-18 14:30:41 +00002669 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002670 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002671 F.LocalNumSelectors = Record[0];
2672 unsigned LocalBaseSelectorID = Record[1];
2673 F.BaseSelectorID = getTotalNumSelectors();
2674
2675 if (F.LocalNumSelectors > 0) {
2676 // Introduce the global -> local mapping for selectors within this
2677 // module.
2678 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2679
2680 // Introduce the local -> global mapping for selectors within this
2681 // module.
2682 F.SelectorRemap.insertOrReplace(
2683 std::make_pair(LocalBaseSelectorID,
2684 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002685
2686 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002687 }
2688 break;
2689 }
2690
2691 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002692 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002693 if (Record[0])
2694 F.SelectorLookupTable
2695 = ASTSelectorLookupTable::Create(
2696 F.SelectorLookupTableData + Record[0],
2697 F.SelectorLookupTableData,
2698 ASTSelectorLookupTrait(*this, F));
2699 TotalNumMethodPoolEntries += Record[1];
2700 break;
2701
2702 case REFERENCED_SELECTOR_POOL:
2703 if (!Record.empty()) {
2704 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2705 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2706 Record[Idx++]));
2707 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2708 getRawEncoding());
2709 }
2710 }
2711 break;
2712
2713 case PP_COUNTER_VALUE:
2714 if (!Record.empty() && Listener)
2715 Listener->ReadCounter(F, Record[0]);
2716 break;
2717
2718 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002719 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002720 F.NumFileSortedDecls = Record[0];
2721 break;
2722
2723 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002724 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002725 F.LocalNumSLocEntries = Record[0];
2726 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002727 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002728 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002729 SLocSpaceSize);
2730 // Make our entry in the range map. BaseID is negative and growing, so
2731 // we invert it. Because we invert it, though, we need the other end of
2732 // the range.
2733 unsigned RangeStart =
2734 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2735 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2736 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2737
2738 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2739 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2740 GlobalSLocOffsetMap.insert(
2741 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2742 - SLocSpaceSize,&F));
2743
2744 // Initialize the remapping table.
2745 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002746 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002747 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002748 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002749 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2750
2751 TotalNumSLocEntries += F.LocalNumSLocEntries;
2752 break;
2753 }
2754
2755 case MODULE_OFFSET_MAP: {
2756 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002757 const unsigned char *Data = (const unsigned char*)Blob.data();
2758 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002759
2760 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2761 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2762 F.SLocRemap.insert(std::make_pair(0U, 0));
2763 F.SLocRemap.insert(std::make_pair(2U, 1));
2764 }
2765
Guy Benyei11169dd2012-12-18 14:30:41 +00002766 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002767 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2768 RemapBuilder;
2769 RemapBuilder SLocRemap(F.SLocRemap);
2770 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2771 RemapBuilder MacroRemap(F.MacroRemap);
2772 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2773 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2774 RemapBuilder SelectorRemap(F.SelectorRemap);
2775 RemapBuilder DeclRemap(F.DeclRemap);
2776 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002777
2778 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002779 using namespace llvm::support;
2780 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002781 StringRef Name = StringRef((const char*)Data, Len);
2782 Data += Len;
2783 ModuleFile *OM = ModuleMgr.lookup(Name);
2784 if (!OM) {
2785 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002786 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002787 }
2788
Justin Bogner57ba0b22014-03-28 22:03:24 +00002789 uint32_t SLocOffset =
2790 endian::readNext<uint32_t, little, unaligned>(Data);
2791 uint32_t IdentifierIDOffset =
2792 endian::readNext<uint32_t, little, unaligned>(Data);
2793 uint32_t MacroIDOffset =
2794 endian::readNext<uint32_t, little, unaligned>(Data);
2795 uint32_t PreprocessedEntityIDOffset =
2796 endian::readNext<uint32_t, little, unaligned>(Data);
2797 uint32_t SubmoduleIDOffset =
2798 endian::readNext<uint32_t, little, unaligned>(Data);
2799 uint32_t SelectorIDOffset =
2800 endian::readNext<uint32_t, little, unaligned>(Data);
2801 uint32_t DeclIDOffset =
2802 endian::readNext<uint32_t, little, unaligned>(Data);
2803 uint32_t TypeIndexOffset =
2804 endian::readNext<uint32_t, little, unaligned>(Data);
2805
Ben Langmuir785180e2014-10-20 16:27:30 +00002806 uint32_t None = std::numeric_limits<uint32_t>::max();
2807
2808 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2809 RemapBuilder &Remap) {
2810 if (Offset != None)
2811 Remap.insert(std::make_pair(Offset,
2812 static_cast<int>(BaseOffset - Offset)));
2813 };
2814 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2815 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2816 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2817 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2818 PreprocessedEntityRemap);
2819 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2820 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2821 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2822 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002823
2824 // Global -> local mappings.
2825 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2826 }
2827 break;
2828 }
2829
2830 case SOURCE_MANAGER_LINE_TABLE:
2831 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002832 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002833 break;
2834
2835 case SOURCE_LOCATION_PRELOADS: {
2836 // Need to transform from the local view (1-based IDs) to the global view,
2837 // which is based off F.SLocEntryBaseID.
2838 if (!F.PreloadSLocEntries.empty()) {
2839 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002840 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002841 }
2842
2843 F.PreloadSLocEntries.swap(Record);
2844 break;
2845 }
2846
2847 case EXT_VECTOR_DECLS:
2848 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2849 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2850 break;
2851
2852 case VTABLE_USES:
2853 if (Record.size() % 3 != 0) {
2854 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002855 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002856 }
2857
2858 // Later tables overwrite earlier ones.
2859 // FIXME: Modules will have some trouble with this. This is clearly not
2860 // the right way to do this.
2861 VTableUses.clear();
2862
2863 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2864 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2865 VTableUses.push_back(
2866 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2867 VTableUses.push_back(Record[Idx++]);
2868 }
2869 break;
2870
Guy Benyei11169dd2012-12-18 14:30:41 +00002871 case PENDING_IMPLICIT_INSTANTIATIONS:
2872 if (PendingInstantiations.size() % 2 != 0) {
2873 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002874 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002875 }
2876
2877 if (Record.size() % 2 != 0) {
2878 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002879 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002880 }
2881
2882 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2883 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2884 PendingInstantiations.push_back(
2885 ReadSourceLocation(F, Record, I).getRawEncoding());
2886 }
2887 break;
2888
2889 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002890 if (Record.size() != 2) {
2891 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002892 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002893 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002894 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2895 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2896 break;
2897
2898 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002899 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2900 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2901 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002902
2903 unsigned LocalBasePreprocessedEntityID = Record[0];
2904
2905 unsigned StartingID;
2906 if (!PP.getPreprocessingRecord())
2907 PP.createPreprocessingRecord();
2908 if (!PP.getPreprocessingRecord()->getExternalSource())
2909 PP.getPreprocessingRecord()->SetExternalSource(*this);
2910 StartingID
2911 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00002912 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00002913 F.BasePreprocessedEntityID = StartingID;
2914
2915 if (F.NumPreprocessedEntities > 0) {
2916 // Introduce the global -> local mapping for preprocessed entities in
2917 // this module.
2918 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2919
2920 // Introduce the local -> global mapping for preprocessed entities in
2921 // this module.
2922 F.PreprocessedEntityRemap.insertOrReplace(
2923 std::make_pair(LocalBasePreprocessedEntityID,
2924 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2925 }
2926
2927 break;
2928 }
2929
2930 case DECL_UPDATE_OFFSETS: {
2931 if (Record.size() % 2 != 0) {
2932 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002933 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002934 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00002935 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
2936 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
2937 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
2938
2939 // If we've already loaded the decl, perform the updates when we finish
2940 // loading this block.
2941 if (Decl *D = GetExistingDecl(ID))
2942 PendingUpdateRecords.push_back(std::make_pair(ID, D));
2943 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002944 break;
2945 }
2946
2947 case DECL_REPLACEMENTS: {
2948 if (Record.size() % 3 != 0) {
2949 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002950 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002951 }
2952 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2953 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2954 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2955 break;
2956 }
2957
2958 case OBJC_CATEGORIES_MAP: {
2959 if (F.LocalNumObjCCategoriesInMap != 0) {
2960 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002961 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002962 }
2963
2964 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002965 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002966 break;
2967 }
2968
2969 case OBJC_CATEGORIES:
2970 F.ObjCCategories.swap(Record);
2971 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00002972
Guy Benyei11169dd2012-12-18 14:30:41 +00002973 case CXX_BASE_SPECIFIER_OFFSETS: {
2974 if (F.LocalNumCXXBaseSpecifiers != 0) {
2975 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002976 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002977 }
Richard Smithc2bb8182015-03-24 06:36:48 +00002978
Guy Benyei11169dd2012-12-18 14:30:41 +00002979 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002980 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00002981 break;
2982 }
2983
2984 case CXX_CTOR_INITIALIZERS_OFFSETS: {
2985 if (F.LocalNumCXXCtorInitializers != 0) {
2986 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
2987 return Failure;
2988 }
2989
2990 F.LocalNumCXXCtorInitializers = Record[0];
2991 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002992 break;
2993 }
2994
2995 case DIAG_PRAGMA_MAPPINGS:
2996 if (F.PragmaDiagMappings.empty())
2997 F.PragmaDiagMappings.swap(Record);
2998 else
2999 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3000 Record.begin(), Record.end());
3001 break;
3002
3003 case CUDA_SPECIAL_DECL_REFS:
3004 // Later tables overwrite earlier ones.
3005 // FIXME: Modules will have trouble with this.
3006 CUDASpecialDeclRefs.clear();
3007 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3008 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3009 break;
3010
3011 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003012 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003013 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003014 if (Record[0]) {
3015 F.HeaderFileInfoTable
3016 = HeaderFileInfoLookupTable::Create(
3017 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3018 (const unsigned char *)F.HeaderFileInfoTableData,
3019 HeaderFileInfoTrait(*this, F,
3020 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003021 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003022
3023 PP.getHeaderSearchInfo().SetExternalSource(this);
3024 if (!PP.getHeaderSearchInfo().getExternalLookup())
3025 PP.getHeaderSearchInfo().SetExternalLookup(this);
3026 }
3027 break;
3028 }
3029
3030 case FP_PRAGMA_OPTIONS:
3031 // Later tables overwrite earlier ones.
3032 FPPragmaOptions.swap(Record);
3033 break;
3034
3035 case OPENCL_EXTENSIONS:
3036 // Later tables overwrite earlier ones.
3037 OpenCLExtensions.swap(Record);
3038 break;
3039
3040 case TENTATIVE_DEFINITIONS:
3041 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3042 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3043 break;
3044
3045 case KNOWN_NAMESPACES:
3046 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3047 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3048 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003049
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003050 case UNDEFINED_BUT_USED:
3051 if (UndefinedButUsed.size() % 2 != 0) {
3052 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003053 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003054 }
3055
3056 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003057 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003058 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003059 }
3060 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003061 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3062 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003063 ReadSourceLocation(F, Record, I).getRawEncoding());
3064 }
3065 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003066 case DELETE_EXPRS_TO_ANALYZE:
3067 for (unsigned I = 0, N = Record.size(); I != N;) {
3068 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3069 const uint64_t Count = Record[I++];
3070 DelayedDeleteExprs.push_back(Count);
3071 for (uint64_t C = 0; C < Count; ++C) {
3072 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3073 bool IsArrayForm = Record[I++] == 1;
3074 DelayedDeleteExprs.push_back(IsArrayForm);
3075 }
3076 }
3077 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003078
Guy Benyei11169dd2012-12-18 14:30:41 +00003079 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003080 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003081 // If we aren't loading a module (which has its own exports), make
3082 // all of the imported modules visible.
3083 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003084 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3085 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3086 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3087 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003088 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003089 }
3090 }
3091 break;
3092 }
3093
3094 case LOCAL_REDECLARATIONS: {
3095 F.RedeclarationChains.swap(Record);
3096 break;
3097 }
3098
3099 case LOCAL_REDECLARATIONS_MAP: {
3100 if (F.LocalNumRedeclarationsInMap != 0) {
3101 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003102 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003103 }
3104
3105 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003106 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003107 break;
3108 }
3109
Guy Benyei11169dd2012-12-18 14:30:41 +00003110 case MACRO_OFFSET: {
3111 if (F.LocalNumMacros != 0) {
3112 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003113 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003114 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003115 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003116 F.LocalNumMacros = Record[0];
3117 unsigned LocalBaseMacroID = Record[1];
3118 F.BaseMacroID = getTotalNumMacros();
3119
3120 if (F.LocalNumMacros > 0) {
3121 // Introduce the global -> local mapping for macros within this module.
3122 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3123
3124 // Introduce the local -> global mapping for macros within this module.
3125 F.MacroRemap.insertOrReplace(
3126 std::make_pair(LocalBaseMacroID,
3127 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003128
3129 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003130 }
3131 break;
3132 }
3133
Richard Smithe40f2ba2013-08-07 21:41:30 +00003134 case LATE_PARSED_TEMPLATE: {
3135 LateParsedTemplates.append(Record.begin(), Record.end());
3136 break;
3137 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003138
3139 case OPTIMIZE_PRAGMA_OPTIONS:
3140 if (Record.size() != 1) {
3141 Error("invalid pragma optimize record");
3142 return Failure;
3143 }
3144 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3145 break;
Nico Weber72889432014-09-06 01:25:55 +00003146
3147 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3148 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3149 UnusedLocalTypedefNameCandidates.push_back(
3150 getGlobalDeclID(F, Record[I]));
3151 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003152 }
3153 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003154}
3155
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003156ASTReader::ASTReadResult
3157ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3158 const ModuleFile *ImportedBy,
3159 unsigned ClientLoadCapabilities) {
3160 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003161 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003162
Richard Smithe842a472014-10-22 02:05:46 +00003163 if (F.Kind == MK_ExplicitModule) {
3164 // For an explicitly-loaded module, we don't care whether the original
3165 // module map file exists or matches.
3166 return Success;
3167 }
3168
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003169 // Try to resolve ModuleName in the current header search context and
3170 // verify that it is found in the same module map file as we saved. If the
3171 // top-level AST file is a main file, skip this check because there is no
3172 // usable header search context.
3173 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003174 "MODULE_NAME should come before MODULE_MAP_FILE");
3175 if (F.Kind == MK_ImplicitModule &&
3176 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3177 // An implicitly-loaded module file should have its module listed in some
3178 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003179 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003180 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3181 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3182 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003183 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003184 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3185 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3186 // This module was defined by an imported (explicit) module.
3187 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3188 << ASTFE->getName();
3189 else
3190 // This module was built with a different module map.
3191 Diag(diag::err_imported_module_not_found)
3192 << F.ModuleName << F.FileName << ImportedBy->FileName
3193 << F.ModuleMapPath;
3194 }
3195 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003196 }
3197
Richard Smithe842a472014-10-22 02:05:46 +00003198 assert(M->Name == F.ModuleName && "found module with different name");
3199
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003200 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003201 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003202 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3203 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003204 assert(ImportedBy && "top-level import should be verified");
3205 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3206 Diag(diag::err_imported_module_modmap_changed)
3207 << F.ModuleName << ImportedBy->FileName
3208 << ModMap->getName() << F.ModuleMapPath;
3209 return OutOfDate;
3210 }
3211
3212 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3213 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3214 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003215 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003216 const FileEntry *F =
3217 FileMgr.getFile(Filename, false, false);
3218 if (F == nullptr) {
3219 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3220 Error("could not find file '" + Filename +"' referenced by AST file");
3221 return OutOfDate;
3222 }
3223 AdditionalStoredMaps.insert(F);
3224 }
3225
3226 // Check any additional module map files (e.g. module.private.modulemap)
3227 // that are not in the pcm.
3228 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3229 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3230 // Remove files that match
3231 // Note: SmallPtrSet::erase is really remove
3232 if (!AdditionalStoredMaps.erase(ModMap)) {
3233 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3234 Diag(diag::err_module_different_modmap)
3235 << F.ModuleName << /*new*/0 << ModMap->getName();
3236 return OutOfDate;
3237 }
3238 }
3239 }
3240
3241 // Check any additional module map files that are in the pcm, but not
3242 // found in header search. Cases that match are already removed.
3243 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3244 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3245 Diag(diag::err_module_different_modmap)
3246 << F.ModuleName << /*not new*/1 << ModMap->getName();
3247 return OutOfDate;
3248 }
3249 }
3250
3251 if (Listener)
3252 Listener->ReadModuleMapFile(F.ModuleMapPath);
3253 return Success;
3254}
3255
3256
Douglas Gregorc1489562013-02-12 23:36:21 +00003257/// \brief Move the given method to the back of the global list of methods.
3258static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3259 // Find the entry for this selector in the method pool.
3260 Sema::GlobalMethodPool::iterator Known
3261 = S.MethodPool.find(Method->getSelector());
3262 if (Known == S.MethodPool.end())
3263 return;
3264
3265 // Retrieve the appropriate method list.
3266 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3267 : Known->second.second;
3268 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003269 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003270 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003271 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003272 Found = true;
3273 } else {
3274 // Keep searching.
3275 continue;
3276 }
3277 }
3278
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003279 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003280 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003281 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003282 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003283 }
3284}
3285
Richard Smithde711422015-04-23 21:20:19 +00003286void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003287 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003288 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003289 bool wasHidden = D->Hidden;
3290 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003291
Richard Smith49f906a2014-03-01 00:08:04 +00003292 if (wasHidden && SemaObj) {
3293 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3294 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003295 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003296 }
3297 }
3298}
3299
Richard Smith49f906a2014-03-01 00:08:04 +00003300void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003301 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003302 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003303 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003304 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003305 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003306 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003307 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003308
3309 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003310 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003311 // there is nothing more to do.
3312 continue;
3313 }
Richard Smith49f906a2014-03-01 00:08:04 +00003314
Guy Benyei11169dd2012-12-18 14:30:41 +00003315 if (!Mod->isAvailable()) {
3316 // Modules that aren't available cannot be made visible.
3317 continue;
3318 }
3319
3320 // Update the module's name visibility.
3321 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003322
Guy Benyei11169dd2012-12-18 14:30:41 +00003323 // If we've already deserialized any names from this module,
3324 // mark them as visible.
3325 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3326 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003327 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003328 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003329 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003330 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3331 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003332 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003333
Guy Benyei11169dd2012-12-18 14:30:41 +00003334 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003335 SmallVector<Module *, 16> Exports;
3336 Mod->getExportedModules(Exports);
3337 for (SmallVectorImpl<Module *>::iterator
3338 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3339 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003340 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003341 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003342 }
3343 }
3344}
3345
Douglas Gregore060e572013-01-25 01:03:03 +00003346bool ASTReader::loadGlobalIndex() {
3347 if (GlobalIndex)
3348 return false;
3349
3350 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3351 !Context.getLangOpts().Modules)
3352 return true;
3353
3354 // Try to load the global index.
3355 TriedLoadingGlobalIndex = true;
3356 StringRef ModuleCachePath
3357 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3358 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003359 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003360 if (!Result.first)
3361 return true;
3362
3363 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003364 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003365 return false;
3366}
3367
3368bool ASTReader::isGlobalIndexUnavailable() const {
3369 return Context.getLangOpts().Modules && UseGlobalIndex &&
3370 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3371}
3372
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003373static void updateModuleTimestamp(ModuleFile &MF) {
3374 // Overwrite the timestamp file contents so that file's mtime changes.
3375 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003376 std::error_code EC;
3377 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3378 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003379 return;
3380 OS << "Timestamp file\n";
3381}
3382
Guy Benyei11169dd2012-12-18 14:30:41 +00003383ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3384 ModuleKind Type,
3385 SourceLocation ImportLoc,
3386 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003387 llvm::SaveAndRestore<SourceLocation>
3388 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3389
Richard Smithd1c46742014-04-30 02:24:17 +00003390 // Defer any pending actions until we get to the end of reading the AST file.
3391 Deserializing AnASTFile(this);
3392
Guy Benyei11169dd2012-12-18 14:30:41 +00003393 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003394 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003395
3396 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003397 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003398 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003399 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003400 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003401 ClientLoadCapabilities)) {
3402 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003403 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003404 case OutOfDate:
3405 case VersionMismatch:
3406 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003407 case HadErrors: {
3408 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3409 for (const ImportedModule &IM : Loaded)
3410 LoadedSet.insert(IM.Mod);
3411
Douglas Gregor7029ce12013-03-19 00:28:20 +00003412 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003413 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003414 Context.getLangOpts().Modules
3415 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003416 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003417
3418 // If we find that any modules are unusable, the global index is going
3419 // to be out-of-date. Just remove it.
3420 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003421 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003422 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003423 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003424 case Success:
3425 break;
3426 }
3427
3428 // Here comes stuff that we only do once the entire chain is loaded.
3429
3430 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003431 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3432 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003433 M != MEnd; ++M) {
3434 ModuleFile &F = *M->Mod;
3435
3436 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003437 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3438 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003439
3440 // Once read, set the ModuleFile bit base offset and update the size in
3441 // bits of all files we've seen.
3442 F.GlobalBitOffset = TotalModulesSizeInBits;
3443 TotalModulesSizeInBits += F.SizeInBits;
3444 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3445
3446 // Preload SLocEntries.
3447 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3448 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3449 // Load it through the SourceManager and don't call ReadSLocEntry()
3450 // directly because the entry may have already been loaded in which case
3451 // calling ReadSLocEntry() directly would trigger an assertion in
3452 // SourceManager.
3453 SourceMgr.getLoadedSLocEntryByID(Index);
3454 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003455
3456 // Preload all the pending interesting identifiers by marking them out of
3457 // date.
3458 for (auto Offset : F.PreloadIdentifierOffsets) {
3459 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3460 F.IdentifierTableData + Offset);
3461
3462 ASTIdentifierLookupTrait Trait(*this, F);
3463 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3464 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
3465 PP.getIdentifierTable().getOwn(Key).setOutOfDate(true);
3466 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003467 }
3468
Douglas Gregor603cd862013-03-22 18:50:14 +00003469 // Setup the import locations and notify the module manager that we've
3470 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003471 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3472 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003473 M != MEnd; ++M) {
3474 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003475
3476 ModuleMgr.moduleFileAccepted(&F);
3477
3478 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003479 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003480 if (!M->ImportedBy)
3481 F.ImportLoc = M->ImportLoc;
3482 else
3483 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3484 M->ImportLoc.getRawEncoding());
3485 }
3486
Richard Smith33e0f7e2015-07-22 02:08:40 +00003487 if (!Context.getLangOpts().CPlusPlus ||
3488 (Type != MK_ImplicitModule && Type != MK_ExplicitModule)) {
3489 // Mark all of the identifiers in the identifier table as being out of date,
3490 // so that various accessors know to check the loaded modules when the
3491 // identifier is used.
3492 //
3493 // For C++ modules, we don't need information on many identifiers (just
3494 // those that provide macros or are poisoned), so we mark all of
3495 // the interesting ones via PreloadIdentifierOffsets.
3496 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3497 IdEnd = PP.getIdentifierTable().end();
3498 Id != IdEnd; ++Id)
3499 Id->second->setOutOfDate(true);
3500 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003501
3502 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003503 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3504 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003505 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3506 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003507
3508 switch (Unresolved.Kind) {
3509 case UnresolvedModuleRef::Conflict:
3510 if (ResolvedMod) {
3511 Module::Conflict Conflict;
3512 Conflict.Other = ResolvedMod;
3513 Conflict.Message = Unresolved.String.str();
3514 Unresolved.Mod->Conflicts.push_back(Conflict);
3515 }
3516 continue;
3517
3518 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003519 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003520 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003521 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003522
Douglas Gregorfb912652013-03-20 21:10:35 +00003523 case UnresolvedModuleRef::Export:
3524 if (ResolvedMod || Unresolved.IsWildcard)
3525 Unresolved.Mod->Exports.push_back(
3526 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3527 continue;
3528 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003529 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003530 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003531
3532 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3533 // Might be unnecessary as use declarations are only used to build the
3534 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003535
3536 InitializeContext();
3537
Richard Smith3d8e97e2013-10-18 06:54:39 +00003538 if (SemaObj)
3539 UpdateSema();
3540
Guy Benyei11169dd2012-12-18 14:30:41 +00003541 if (DeserializationListener)
3542 DeserializationListener->ReaderInitialized(this);
3543
3544 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3545 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3546 PrimaryModule.OriginalSourceFileID
3547 = FileID::get(PrimaryModule.SLocEntryBaseID
3548 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3549
3550 // If this AST file is a precompiled preamble, then set the
3551 // preamble file ID of the source manager to the file source file
3552 // from which the preamble was built.
3553 if (Type == MK_Preamble) {
3554 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3555 } else if (Type == MK_MainFile) {
3556 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3557 }
3558 }
3559
3560 // For any Objective-C class definitions we have already loaded, make sure
3561 // that we load any additional categories.
3562 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3563 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3564 ObjCClassesLoaded[I],
3565 PreviousGeneration);
3566 }
Douglas Gregore060e572013-01-25 01:03:03 +00003567
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003568 if (PP.getHeaderSearchInfo()
3569 .getHeaderSearchOpts()
3570 .ModulesValidateOncePerBuildSession) {
3571 // Now we are certain that the module and all modules it depends on are
3572 // up to date. Create or update timestamp files for modules that are
3573 // located in the module cache (not for PCH files that could be anywhere
3574 // in the filesystem).
3575 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3576 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003577 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003578 updateModuleTimestamp(*M.Mod);
3579 }
3580 }
3581 }
3582
Guy Benyei11169dd2012-12-18 14:30:41 +00003583 return Success;
3584}
3585
Ben Langmuir487ea142014-10-23 18:05:36 +00003586static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3587
Ben Langmuir70a1b812015-03-24 04:43:52 +00003588/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3589static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3590 return Stream.Read(8) == 'C' &&
3591 Stream.Read(8) == 'P' &&
3592 Stream.Read(8) == 'C' &&
3593 Stream.Read(8) == 'H';
3594}
3595
Richard Smith0f99d6a2015-08-09 08:48:41 +00003596static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3597 switch (Kind) {
3598 case MK_PCH:
3599 return 0; // PCH
3600 case MK_ImplicitModule:
3601 case MK_ExplicitModule:
3602 return 1; // module
3603 case MK_MainFile:
3604 case MK_Preamble:
3605 return 2; // main source file
3606 }
3607 llvm_unreachable("unknown module kind");
3608}
3609
Guy Benyei11169dd2012-12-18 14:30:41 +00003610ASTReader::ASTReadResult
3611ASTReader::ReadASTCore(StringRef FileName,
3612 ModuleKind Type,
3613 SourceLocation ImportLoc,
3614 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003615 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003616 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003617 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003618 unsigned ClientLoadCapabilities) {
3619 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003620 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003621 ModuleManager::AddModuleResult AddResult
3622 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003623 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003624 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003625 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003626
Douglas Gregor7029ce12013-03-19 00:28:20 +00003627 switch (AddResult) {
3628 case ModuleManager::AlreadyLoaded:
3629 return Success;
3630
3631 case ModuleManager::NewlyLoaded:
3632 // Load module file below.
3633 break;
3634
3635 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003636 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003637 // it.
3638 if (ClientLoadCapabilities & ARR_Missing)
3639 return Missing;
3640
3641 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003642 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
3643 << FileName << ErrorStr.empty()
3644 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003645 return Failure;
3646
3647 case ModuleManager::OutOfDate:
3648 // We couldn't load the module file because it is out-of-date. If the
3649 // client can handle out-of-date, return it.
3650 if (ClientLoadCapabilities & ARR_OutOfDate)
3651 return OutOfDate;
3652
3653 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003654 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
3655 << FileName << ErrorStr.empty()
3656 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003657 return Failure;
3658 }
3659
Douglas Gregor7029ce12013-03-19 00:28:20 +00003660 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003661
3662 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3663 // module?
3664 if (FileName != "-") {
3665 CurrentDir = llvm::sys::path::parent_path(FileName);
3666 if (CurrentDir.empty()) CurrentDir = ".";
3667 }
3668
3669 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003670 BitstreamCursor &Stream = F.Stream;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003671 PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003672 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003673 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3674
Guy Benyei11169dd2012-12-18 14:30:41 +00003675 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003676 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003677 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3678 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003679 return Failure;
3680 }
3681
3682 // This is used for compatibility with older PCH formats.
3683 bool HaveReadControlBlock = false;
3684
Chris Lattnerefa77172013-01-20 00:00:22 +00003685 while (1) {
3686 llvm::BitstreamEntry Entry = Stream.advance();
3687
3688 switch (Entry.Kind) {
3689 case llvm::BitstreamEntry::Error:
3690 case llvm::BitstreamEntry::EndBlock:
3691 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003692 Error("invalid record at top-level of AST file");
3693 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003694
3695 case llvm::BitstreamEntry::SubBlock:
3696 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003697 }
3698
Guy Benyei11169dd2012-12-18 14:30:41 +00003699 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003700 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003701 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3702 if (Stream.ReadBlockInfoBlock()) {
3703 Error("malformed BlockInfoBlock in AST file");
3704 return Failure;
3705 }
3706 break;
3707 case CONTROL_BLOCK_ID:
3708 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003709 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003710 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003711 // Check that we didn't try to load a non-module AST file as a module.
3712 //
3713 // FIXME: Should we also perform the converse check? Loading a module as
3714 // a PCH file sort of works, but it's a bit wonky.
3715 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule) &&
3716 F.ModuleName.empty()) {
3717 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3718 if (Result != OutOfDate ||
3719 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3720 Diag(diag::err_module_file_not_module) << FileName;
3721 return Result;
3722 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003723 break;
3724
3725 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003726 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003727 case OutOfDate: return OutOfDate;
3728 case VersionMismatch: return VersionMismatch;
3729 case ConfigurationMismatch: return ConfigurationMismatch;
3730 case HadErrors: return HadErrors;
3731 }
3732 break;
3733 case AST_BLOCK_ID:
3734 if (!HaveReadControlBlock) {
3735 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003736 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003737 return VersionMismatch;
3738 }
3739
3740 // Record that we've loaded this module.
3741 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3742 return Success;
3743
3744 default:
3745 if (Stream.SkipBlock()) {
3746 Error("malformed block record in AST file");
3747 return Failure;
3748 }
3749 break;
3750 }
3751 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003752}
3753
Richard Smitha7e2cc62015-05-01 01:53:09 +00003754void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003755 // If there's a listener, notify them that we "read" the translation unit.
3756 if (DeserializationListener)
3757 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3758 Context.getTranslationUnitDecl());
3759
Guy Benyei11169dd2012-12-18 14:30:41 +00003760 // FIXME: Find a better way to deal with collisions between these
3761 // built-in types. Right now, we just ignore the problem.
3762
3763 // Load the special types.
3764 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3765 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3766 if (!Context.CFConstantStringTypeDecl)
3767 Context.setCFConstantStringType(GetType(String));
3768 }
3769
3770 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3771 QualType FileType = GetType(File);
3772 if (FileType.isNull()) {
3773 Error("FILE type is NULL");
3774 return;
3775 }
3776
3777 if (!Context.FILEDecl) {
3778 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3779 Context.setFILEDecl(Typedef->getDecl());
3780 else {
3781 const TagType *Tag = FileType->getAs<TagType>();
3782 if (!Tag) {
3783 Error("Invalid FILE type in AST file");
3784 return;
3785 }
3786 Context.setFILEDecl(Tag->getDecl());
3787 }
3788 }
3789 }
3790
3791 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3792 QualType Jmp_bufType = GetType(Jmp_buf);
3793 if (Jmp_bufType.isNull()) {
3794 Error("jmp_buf type is NULL");
3795 return;
3796 }
3797
3798 if (!Context.jmp_bufDecl) {
3799 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3800 Context.setjmp_bufDecl(Typedef->getDecl());
3801 else {
3802 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3803 if (!Tag) {
3804 Error("Invalid jmp_buf type in AST file");
3805 return;
3806 }
3807 Context.setjmp_bufDecl(Tag->getDecl());
3808 }
3809 }
3810 }
3811
3812 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3813 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3814 if (Sigjmp_bufType.isNull()) {
3815 Error("sigjmp_buf type is NULL");
3816 return;
3817 }
3818
3819 if (!Context.sigjmp_bufDecl) {
3820 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3821 Context.setsigjmp_bufDecl(Typedef->getDecl());
3822 else {
3823 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3824 assert(Tag && "Invalid sigjmp_buf type in AST file");
3825 Context.setsigjmp_bufDecl(Tag->getDecl());
3826 }
3827 }
3828 }
3829
3830 if (unsigned ObjCIdRedef
3831 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3832 if (Context.ObjCIdRedefinitionType.isNull())
3833 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3834 }
3835
3836 if (unsigned ObjCClassRedef
3837 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3838 if (Context.ObjCClassRedefinitionType.isNull())
3839 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3840 }
3841
3842 if (unsigned ObjCSelRedef
3843 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3844 if (Context.ObjCSelRedefinitionType.isNull())
3845 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3846 }
3847
3848 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3849 QualType Ucontext_tType = GetType(Ucontext_t);
3850 if (Ucontext_tType.isNull()) {
3851 Error("ucontext_t type is NULL");
3852 return;
3853 }
3854
3855 if (!Context.ucontext_tDecl) {
3856 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3857 Context.setucontext_tDecl(Typedef->getDecl());
3858 else {
3859 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3860 assert(Tag && "Invalid ucontext_t type in AST file");
3861 Context.setucontext_tDecl(Tag->getDecl());
3862 }
3863 }
3864 }
3865 }
3866
3867 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3868
3869 // If there were any CUDA special declarations, deserialize them.
3870 if (!CUDASpecialDeclRefs.empty()) {
3871 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3872 Context.setcudaConfigureCallDecl(
3873 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3874 }
Richard Smith56be7542014-03-21 00:33:59 +00003875
Guy Benyei11169dd2012-12-18 14:30:41 +00003876 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00003877 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00003878 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00003879 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003880 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003881 /*ImportLoc=*/Import.ImportLoc);
3882 PP.makeModuleVisible(Imported, Import.ImportLoc);
3883 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003884 }
3885 ImportedModules.clear();
3886}
3887
3888void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00003889 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00003890}
3891
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003892/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3893/// cursor into the start of the given block ID, returning false on success and
3894/// true on failure.
3895static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003896 while (1) {
3897 llvm::BitstreamEntry Entry = Cursor.advance();
3898 switch (Entry.Kind) {
3899 case llvm::BitstreamEntry::Error:
3900 case llvm::BitstreamEntry::EndBlock:
3901 return true;
3902
3903 case llvm::BitstreamEntry::Record:
3904 // Ignore top-level records.
3905 Cursor.skipRecord(Entry.ID);
3906 break;
3907
3908 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003909 if (Entry.ID == BlockID) {
3910 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003911 return true;
3912 // Found it!
3913 return false;
3914 }
3915
3916 if (Cursor.SkipBlock())
3917 return true;
3918 }
3919 }
3920}
3921
Ben Langmuir70a1b812015-03-24 04:43:52 +00003922/// \brief Reads and return the signature record from \p StreamFile's control
3923/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00003924static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
3925 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00003926 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00003927 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00003928
3929 // Scan for the CONTROL_BLOCK_ID block.
3930 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
3931 return 0;
3932
3933 // Scan for SIGNATURE inside the control block.
3934 ASTReader::RecordData Record;
3935 while (1) {
3936 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3937 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
3938 Entry.Kind != llvm::BitstreamEntry::Record)
3939 return 0;
3940
3941 Record.clear();
3942 StringRef Blob;
3943 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
3944 return Record[0];
3945 }
3946}
3947
Guy Benyei11169dd2012-12-18 14:30:41 +00003948/// \brief Retrieve the name of the original source file name
3949/// directly from the AST file, without actually loading the AST
3950/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003951std::string ASTReader::getOriginalSourceFile(
3952 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003953 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003954 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00003955 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00003956 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00003957 Diags.Report(diag::err_fe_unable_to_read_pch_file)
3958 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00003959 return std::string();
3960 }
3961
3962 // Initialize the stream
3963 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003964 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00003965 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003966
3967 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003968 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003969 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3970 return std::string();
3971 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003972
Chris Lattnere7b154b2013-01-19 21:39:22 +00003973 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003974 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003975 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3976 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003977 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003978
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003979 // Scan for ORIGINAL_FILE inside the control block.
3980 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003981 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003982 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003983 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3984 return std::string();
3985
3986 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3987 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3988 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003989 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003990
Guy Benyei11169dd2012-12-18 14:30:41 +00003991 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003992 StringRef Blob;
3993 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3994 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003995 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003996}
3997
3998namespace {
3999 class SimplePCHValidator : public ASTReaderListener {
4000 const LangOptions &ExistingLangOpts;
4001 const TargetOptions &ExistingTargetOpts;
4002 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004003 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004004 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004005
Guy Benyei11169dd2012-12-18 14:30:41 +00004006 public:
4007 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4008 const TargetOptions &ExistingTargetOpts,
4009 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004010 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004011 FileManager &FileMgr)
4012 : ExistingLangOpts(ExistingLangOpts),
4013 ExistingTargetOpts(ExistingTargetOpts),
4014 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004015 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004016 FileMgr(FileMgr)
4017 {
4018 }
4019
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004020 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4021 bool AllowCompatibleDifferences) override {
4022 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4023 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004024 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004025 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4026 bool AllowCompatibleDifferences) override {
4027 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4028 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004029 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004030 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4031 StringRef SpecificModuleCachePath,
4032 bool Complain) override {
4033 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4034 ExistingModuleCachePath,
4035 nullptr, ExistingLangOpts);
4036 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004037 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4038 bool Complain,
4039 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004040 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004041 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004042 }
4043 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004044}
Guy Benyei11169dd2012-12-18 14:30:41 +00004045
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004046bool ASTReader::readASTFileControlBlock(
4047 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004048 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004049 ASTReaderListener &Listener) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004050 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004051 // FIXME: This allows use of the VFS; we do not allow use of the
4052 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004053 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004054 if (!Buffer) {
4055 return true;
4056 }
4057
4058 // Initialize the stream
4059 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004060 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004061 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004062
4063 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004064 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004065 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004066
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004067 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004068 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004069 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004070
4071 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004072 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004073 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004074 BitstreamCursor InputFilesCursor;
4075 if (NeedsInputFiles) {
4076 InputFilesCursor = Stream;
4077 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4078 return true;
4079
4080 // Read the abbreviations
4081 while (true) {
4082 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4083 unsigned Code = InputFilesCursor.ReadCode();
4084
4085 // We expect all abbrevs to be at the start of the block.
4086 if (Code != llvm::bitc::DEFINE_ABBREV) {
4087 InputFilesCursor.JumpToBit(Offset);
4088 break;
4089 }
4090 InputFilesCursor.ReadAbbrevRecord();
4091 }
4092 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004093
4094 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004095 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004096 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004097 while (1) {
4098 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4099 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4100 return false;
4101
4102 if (Entry.Kind != llvm::BitstreamEntry::Record)
4103 return true;
4104
Guy Benyei11169dd2012-12-18 14:30:41 +00004105 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004106 StringRef Blob;
4107 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004108 switch ((ControlRecordTypes)RecCode) {
4109 case METADATA: {
4110 if (Record[0] != VERSION_MAJOR)
4111 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004112
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004113 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004114 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004115
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004116 break;
4117 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004118 case MODULE_NAME:
4119 Listener.ReadModuleName(Blob);
4120 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004121 case MODULE_DIRECTORY:
4122 ModuleDir = Blob;
4123 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004124 case MODULE_MAP_FILE: {
4125 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004126 auto Path = ReadString(Record, Idx);
4127 ResolveImportedPath(Path, ModuleDir);
4128 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004129 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004130 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004131 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004132 if (ParseLanguageOptions(Record, false, Listener,
4133 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004134 return true;
4135 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004136
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004137 case TARGET_OPTIONS:
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004138 if (ParseTargetOptions(Record, false, Listener,
4139 /*AllowCompatibleConfigurationMismatch*/ false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004140 return true;
4141 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004142
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004143 case DIAGNOSTIC_OPTIONS:
4144 if (ParseDiagnosticOptions(Record, false, Listener))
4145 return true;
4146 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004147
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004148 case FILE_SYSTEM_OPTIONS:
4149 if (ParseFileSystemOptions(Record, false, Listener))
4150 return true;
4151 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004152
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004153 case HEADER_SEARCH_OPTIONS:
4154 if (ParseHeaderSearchOptions(Record, false, Listener))
4155 return true;
4156 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004157
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004158 case PREPROCESSOR_OPTIONS: {
4159 std::string IgnoredSuggestedPredefines;
4160 if (ParsePreprocessorOptions(Record, false, Listener,
4161 IgnoredSuggestedPredefines))
4162 return true;
4163 break;
4164 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004165
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004166 case INPUT_FILE_OFFSETS: {
4167 if (!NeedsInputFiles)
4168 break;
4169
4170 unsigned NumInputFiles = Record[0];
4171 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004172 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004173 for (unsigned I = 0; I != NumInputFiles; ++I) {
4174 // Go find this input file.
4175 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004176
4177 if (isSystemFile && !NeedsSystemInputFiles)
4178 break; // the rest are system input files
4179
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004180 BitstreamCursor &Cursor = InputFilesCursor;
4181 SavedStreamPosition SavedPosition(Cursor);
4182 Cursor.JumpToBit(InputFileOffs[I]);
4183
4184 unsigned Code = Cursor.ReadCode();
4185 RecordData Record;
4186 StringRef Blob;
4187 bool shouldContinue = false;
4188 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4189 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004190 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004191 std::string Filename = Blob;
4192 ResolveImportedPath(Filename, ModuleDir);
4193 shouldContinue =
4194 Listener.visitInputFile(Filename, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004195 break;
4196 }
4197 if (!shouldContinue)
4198 break;
4199 }
4200 break;
4201 }
4202
Richard Smithd4b230b2014-10-27 23:01:16 +00004203 case IMPORTS: {
4204 if (!NeedsImports)
4205 break;
4206
4207 unsigned Idx = 0, N = Record.size();
4208 while (Idx < N) {
4209 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004210 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004211 std::string Filename = ReadString(Record, Idx);
4212 ResolveImportedPath(Filename, ModuleDir);
4213 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004214 }
4215 break;
4216 }
4217
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004218 default:
4219 // No other validation to perform.
4220 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004221 }
4222 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004223}
4224
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004225bool ASTReader::isAcceptableASTFile(
4226 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004227 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004228 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4229 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004230 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4231 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004232 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004233 validator);
Guy Benyei11169dd2012-12-18 14:30:41 +00004234}
4235
Ben Langmuir2c9af442014-04-10 17:57:43 +00004236ASTReader::ASTReadResult
4237ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004238 // Enter the submodule block.
4239 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4240 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004241 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004242 }
4243
4244 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4245 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004246 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004247 RecordData Record;
4248 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004249 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4250
4251 switch (Entry.Kind) {
4252 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4253 case llvm::BitstreamEntry::Error:
4254 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004255 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004256 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004257 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004258 case llvm::BitstreamEntry::Record:
4259 // The interesting case.
4260 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004261 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004262
Guy Benyei11169dd2012-12-18 14:30:41 +00004263 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004264 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004265 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004266 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4267
4268 if ((Kind == SUBMODULE_METADATA) != First) {
4269 Error("submodule metadata record should be at beginning of block");
4270 return Failure;
4271 }
4272 First = false;
4273
4274 // Submodule information is only valid if we have a current module.
4275 // FIXME: Should we error on these cases?
4276 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4277 Kind != SUBMODULE_DEFINITION)
4278 continue;
4279
4280 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004281 default: // Default behavior: ignore.
4282 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004283
Richard Smith03478d92014-10-23 22:12:14 +00004284 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004285 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004286 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004287 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004288 }
Richard Smith03478d92014-10-23 22:12:14 +00004289
Chris Lattner0e6c9402013-01-20 02:38:54 +00004290 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004291 unsigned Idx = 0;
4292 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4293 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4294 bool IsFramework = Record[Idx++];
4295 bool IsExplicit = Record[Idx++];
4296 bool IsSystem = Record[Idx++];
4297 bool IsExternC = Record[Idx++];
4298 bool InferSubmodules = Record[Idx++];
4299 bool InferExplicitSubmodules = Record[Idx++];
4300 bool InferExportWildcard = Record[Idx++];
4301 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004302
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004303 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004304 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004305 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004306
Guy Benyei11169dd2012-12-18 14:30:41 +00004307 // Retrieve this (sub)module from the module map, creating it if
4308 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004309 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004310 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004311
4312 // FIXME: set the definition loc for CurrentModule, or call
4313 // ModMap.setInferredModuleAllowedBy()
4314
Guy Benyei11169dd2012-12-18 14:30:41 +00004315 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4316 if (GlobalIndex >= SubmodulesLoaded.size() ||
4317 SubmodulesLoaded[GlobalIndex]) {
4318 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004319 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004320 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004321
Douglas Gregor7029ce12013-03-19 00:28:20 +00004322 if (!ParentModule) {
4323 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4324 if (CurFile != F.File) {
4325 if (!Diags.isDiagnosticInFlight()) {
4326 Diag(diag::err_module_file_conflict)
4327 << CurrentModule->getTopLevelModuleName()
4328 << CurFile->getName()
4329 << F.File->getName();
4330 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004331 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004332 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004333 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004334
4335 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004336 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004337
Adrian Prantl15bcf702015-06-30 17:39:43 +00004338 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004339 CurrentModule->IsFromModuleFile = true;
4340 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004341 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004342 CurrentModule->InferSubmodules = InferSubmodules;
4343 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4344 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004345 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004346 if (DeserializationListener)
4347 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4348
4349 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004350
Douglas Gregorfb912652013-03-20 21:10:35 +00004351 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004352 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004353 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004354 CurrentModule->UnresolvedConflicts.clear();
4355 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004356 break;
4357 }
4358
4359 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004360 std::string Filename = Blob;
4361 ResolveImportedPath(F, Filename);
4362 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004363 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004364 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4365 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004366 // This can be a spurious difference caused by changing the VFS to
4367 // point to a different copy of the file, and it is too late to
4368 // to rebuild safely.
4369 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4370 // after input file validation only real problems would remain and we
4371 // could just error. For now, assume it's okay.
4372 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004373 }
4374 }
4375 break;
4376 }
4377
Richard Smith202210b2014-10-24 20:23:01 +00004378 case SUBMODULE_HEADER:
4379 case SUBMODULE_EXCLUDED_HEADER:
4380 case SUBMODULE_PRIVATE_HEADER:
4381 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004382 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4383 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004384 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004385
Richard Smith202210b2014-10-24 20:23:01 +00004386 case SUBMODULE_TEXTUAL_HEADER:
4387 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4388 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4389 // them here.
4390 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004391
Guy Benyei11169dd2012-12-18 14:30:41 +00004392 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004393 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004394 break;
4395 }
4396
4397 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004398 std::string Dirname = Blob;
4399 ResolveImportedPath(F, Dirname);
4400 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004401 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004402 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4403 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004404 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4405 Error("mismatched umbrella directories in submodule");
4406 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004407 }
4408 }
4409 break;
4410 }
4411
4412 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004413 F.BaseSubmoduleID = getTotalNumSubmodules();
4414 F.LocalNumSubmodules = Record[0];
4415 unsigned LocalBaseSubmoduleID = Record[1];
4416 if (F.LocalNumSubmodules > 0) {
4417 // Introduce the global -> local mapping for submodules within this
4418 // module.
4419 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4420
4421 // Introduce the local -> global mapping for submodules within this
4422 // module.
4423 F.SubmoduleRemap.insertOrReplace(
4424 std::make_pair(LocalBaseSubmoduleID,
4425 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004426
Ben Langmuir52ca6782014-10-20 16:27:32 +00004427 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4428 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004429 break;
4430 }
4431
4432 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004433 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004434 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004435 Unresolved.File = &F;
4436 Unresolved.Mod = CurrentModule;
4437 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004438 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004439 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004440 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004441 }
4442 break;
4443 }
4444
4445 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004446 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004447 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004448 Unresolved.File = &F;
4449 Unresolved.Mod = CurrentModule;
4450 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004451 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004452 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004453 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004454 }
4455
4456 // Once we've loaded the set of exports, there's no reason to keep
4457 // the parsed, unresolved exports around.
4458 CurrentModule->UnresolvedExports.clear();
4459 break;
4460 }
4461 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004462 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004463 Context.getTargetInfo());
4464 break;
4465 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004466
4467 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004468 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004469 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004470 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004471
4472 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004473 CurrentModule->ConfigMacros.push_back(Blob.str());
4474 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004475
4476 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004477 UnresolvedModuleRef Unresolved;
4478 Unresolved.File = &F;
4479 Unresolved.Mod = CurrentModule;
4480 Unresolved.ID = Record[0];
4481 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4482 Unresolved.IsWildcard = false;
4483 Unresolved.String = Blob;
4484 UnresolvedModuleRefs.push_back(Unresolved);
4485 break;
4486 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004487 }
4488 }
4489}
4490
4491/// \brief Parse the record that corresponds to a LangOptions data
4492/// structure.
4493///
4494/// This routine parses the language options from the AST file and then gives
4495/// them to the AST listener if one is set.
4496///
4497/// \returns true if the listener deems the file unacceptable, false otherwise.
4498bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4499 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004500 ASTReaderListener &Listener,
4501 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004502 LangOptions LangOpts;
4503 unsigned Idx = 0;
4504#define LANGOPT(Name, Bits, Default, Description) \
4505 LangOpts.Name = Record[Idx++];
4506#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4507 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4508#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004509#define SANITIZER(NAME, ID) \
4510 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004511#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004512
Ben Langmuircd98cb72015-06-23 18:20:18 +00004513 for (unsigned N = Record[Idx++]; N; --N)
4514 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4515
Guy Benyei11169dd2012-12-18 14:30:41 +00004516 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4517 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4518 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004519
Ben Langmuird4a667a2015-06-23 18:20:23 +00004520 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004521
4522 // Comment options.
4523 for (unsigned N = Record[Idx++]; N; --N) {
4524 LangOpts.CommentOpts.BlockCommandNames.push_back(
4525 ReadString(Record, Idx));
4526 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004527 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004528
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004529 return Listener.ReadLanguageOptions(LangOpts, Complain,
4530 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004531}
4532
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004533bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4534 ASTReaderListener &Listener,
4535 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004536 unsigned Idx = 0;
4537 TargetOptions TargetOpts;
4538 TargetOpts.Triple = ReadString(Record, Idx);
4539 TargetOpts.CPU = ReadString(Record, Idx);
4540 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004541 for (unsigned N = Record[Idx++]; N; --N) {
4542 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4543 }
4544 for (unsigned N = Record[Idx++]; N; --N) {
4545 TargetOpts.Features.push_back(ReadString(Record, Idx));
4546 }
4547
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004548 return Listener.ReadTargetOptions(TargetOpts, Complain,
4549 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004550}
4551
4552bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4553 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004554 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004555 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004556#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004557#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004558 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004559#include "clang/Basic/DiagnosticOptions.def"
4560
Richard Smith3be1cb22014-08-07 00:24:21 +00004561 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004562 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004563 for (unsigned N = Record[Idx++]; N; --N)
4564 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004565
4566 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4567}
4568
4569bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4570 ASTReaderListener &Listener) {
4571 FileSystemOptions FSOpts;
4572 unsigned Idx = 0;
4573 FSOpts.WorkingDir = ReadString(Record, Idx);
4574 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4575}
4576
4577bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4578 bool Complain,
4579 ASTReaderListener &Listener) {
4580 HeaderSearchOptions HSOpts;
4581 unsigned Idx = 0;
4582 HSOpts.Sysroot = ReadString(Record, Idx);
4583
4584 // Include entries.
4585 for (unsigned N = Record[Idx++]; N; --N) {
4586 std::string Path = ReadString(Record, Idx);
4587 frontend::IncludeDirGroup Group
4588 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004589 bool IsFramework = Record[Idx++];
4590 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004591 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4592 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004593 }
4594
4595 // System header prefixes.
4596 for (unsigned N = Record[Idx++]; N; --N) {
4597 std::string Prefix = ReadString(Record, Idx);
4598 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004599 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004600 }
4601
4602 HSOpts.ResourceDir = ReadString(Record, Idx);
4603 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004604 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004605 HSOpts.DisableModuleHash = Record[Idx++];
4606 HSOpts.UseBuiltinIncludes = Record[Idx++];
4607 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4608 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4609 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004610 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004611
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004612 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4613 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004614}
4615
4616bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4617 bool Complain,
4618 ASTReaderListener &Listener,
4619 std::string &SuggestedPredefines) {
4620 PreprocessorOptions PPOpts;
4621 unsigned Idx = 0;
4622
4623 // Macro definitions/undefs
4624 for (unsigned N = Record[Idx++]; N; --N) {
4625 std::string Macro = ReadString(Record, Idx);
4626 bool IsUndef = Record[Idx++];
4627 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4628 }
4629
4630 // Includes
4631 for (unsigned N = Record[Idx++]; N; --N) {
4632 PPOpts.Includes.push_back(ReadString(Record, Idx));
4633 }
4634
4635 // Macro Includes
4636 for (unsigned N = Record[Idx++]; N; --N) {
4637 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4638 }
4639
4640 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004641 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004642 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4643 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4644 PPOpts.ObjCXXARCStandardLibrary =
4645 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4646 SuggestedPredefines.clear();
4647 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4648 SuggestedPredefines);
4649}
4650
4651std::pair<ModuleFile *, unsigned>
4652ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4653 GlobalPreprocessedEntityMapType::iterator
4654 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4655 assert(I != GlobalPreprocessedEntityMap.end() &&
4656 "Corrupted global preprocessed entity map");
4657 ModuleFile *M = I->second;
4658 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4659 return std::make_pair(M, LocalIndex);
4660}
4661
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004662llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004663ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4664 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4665 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4666 Mod.NumPreprocessedEntities);
4667
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004668 return llvm::make_range(PreprocessingRecord::iterator(),
4669 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004670}
4671
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004672llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004673ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004674 return llvm::make_range(
4675 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4676 ModuleDeclIterator(this, &Mod,
4677 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004678}
4679
4680PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4681 PreprocessedEntityID PPID = Index+1;
4682 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4683 ModuleFile &M = *PPInfo.first;
4684 unsigned LocalIndex = PPInfo.second;
4685 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4686
Guy Benyei11169dd2012-12-18 14:30:41 +00004687 if (!PP.getPreprocessingRecord()) {
4688 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004689 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004690 }
4691
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004692 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4693 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4694
4695 llvm::BitstreamEntry Entry =
4696 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4697 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004698 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004699
Guy Benyei11169dd2012-12-18 14:30:41 +00004700 // Read the record.
4701 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4702 ReadSourceLocation(M, PPOffs.End));
4703 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004704 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004705 RecordData Record;
4706 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004707 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4708 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004709 switch (RecType) {
4710 case PPD_MACRO_EXPANSION: {
4711 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004712 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004713 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004714 if (isBuiltin)
4715 Name = getLocalIdentifier(M, Record[1]);
4716 else {
Richard Smith66a81862015-05-04 02:25:31 +00004717 PreprocessedEntityID GlobalID =
4718 getGlobalPreprocessedEntityID(M, Record[1]);
4719 Def = cast<MacroDefinitionRecord>(
4720 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004721 }
4722
4723 MacroExpansion *ME;
4724 if (isBuiltin)
4725 ME = new (PPRec) MacroExpansion(Name, Range);
4726 else
4727 ME = new (PPRec) MacroExpansion(Def, Range);
4728
4729 return ME;
4730 }
4731
4732 case PPD_MACRO_DEFINITION: {
4733 // Decode the identifier info and then check again; if the macro is
4734 // still defined and associated with the identifier,
4735 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004736 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004737
4738 if (DeserializationListener)
4739 DeserializationListener->MacroDefinitionRead(PPID, MD);
4740
4741 return MD;
4742 }
4743
4744 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004745 const char *FullFileNameStart = Blob.data() + Record[0];
4746 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004747 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004748 if (!FullFileName.empty())
4749 File = PP.getFileManager().getFile(FullFileName);
4750
4751 // FIXME: Stable encoding
4752 InclusionDirective::InclusionKind Kind
4753 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4754 InclusionDirective *ID
4755 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004756 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004757 Record[1], Record[3],
4758 File,
4759 Range);
4760 return ID;
4761 }
4762 }
4763
4764 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4765}
4766
4767/// \brief \arg SLocMapI points at a chunk of a module that contains no
4768/// preprocessed entities or the entities it contains are not the ones we are
4769/// looking for. Find the next module that contains entities and return the ID
4770/// of the first entry.
4771PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4772 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4773 ++SLocMapI;
4774 for (GlobalSLocOffsetMapType::const_iterator
4775 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4776 ModuleFile &M = *SLocMapI->second;
4777 if (M.NumPreprocessedEntities)
4778 return M.BasePreprocessedEntityID;
4779 }
4780
4781 return getTotalNumPreprocessedEntities();
4782}
4783
4784namespace {
4785
4786template <unsigned PPEntityOffset::*PPLoc>
4787struct PPEntityComp {
4788 const ASTReader &Reader;
4789 ModuleFile &M;
4790
4791 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4792
4793 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4794 SourceLocation LHS = getLoc(L);
4795 SourceLocation RHS = getLoc(R);
4796 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4797 }
4798
4799 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4800 SourceLocation LHS = getLoc(L);
4801 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4802 }
4803
4804 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4805 SourceLocation RHS = getLoc(R);
4806 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4807 }
4808
4809 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4810 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4811 }
4812};
4813
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004814}
Guy Benyei11169dd2012-12-18 14:30:41 +00004815
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004816PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4817 bool EndsAfter) const {
4818 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004819 return getTotalNumPreprocessedEntities();
4820
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004821 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4822 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004823 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4824 "Corrupted global sloc offset map");
4825
4826 if (SLocMapI->second->NumPreprocessedEntities == 0)
4827 return findNextPreprocessedEntity(SLocMapI);
4828
4829 ModuleFile &M = *SLocMapI->second;
4830 typedef const PPEntityOffset *pp_iterator;
4831 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4832 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4833
4834 size_t Count = M.NumPreprocessedEntities;
4835 size_t Half;
4836 pp_iterator First = pp_begin;
4837 pp_iterator PPI;
4838
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004839 if (EndsAfter) {
4840 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4841 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4842 } else {
4843 // Do a binary search manually instead of using std::lower_bound because
4844 // The end locations of entities may be unordered (when a macro expansion
4845 // is inside another macro argument), but for this case it is not important
4846 // whether we get the first macro expansion or its containing macro.
4847 while (Count > 0) {
4848 Half = Count / 2;
4849 PPI = First;
4850 std::advance(PPI, Half);
4851 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4852 Loc)) {
4853 First = PPI;
4854 ++First;
4855 Count = Count - Half - 1;
4856 } else
4857 Count = Half;
4858 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004859 }
4860
4861 if (PPI == pp_end)
4862 return findNextPreprocessedEntity(SLocMapI);
4863
4864 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4865}
4866
Guy Benyei11169dd2012-12-18 14:30:41 +00004867/// \brief Returns a pair of [Begin, End) indices of preallocated
4868/// preprocessed entities that \arg Range encompasses.
4869std::pair<unsigned, unsigned>
4870 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4871 if (Range.isInvalid())
4872 return std::make_pair(0,0);
4873 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4874
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004875 PreprocessedEntityID BeginID =
4876 findPreprocessedEntity(Range.getBegin(), false);
4877 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004878 return std::make_pair(BeginID, EndID);
4879}
4880
4881/// \brief Optionally returns true or false if the preallocated preprocessed
4882/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004883Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004884 FileID FID) {
4885 if (FID.isInvalid())
4886 return false;
4887
4888 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4889 ModuleFile &M = *PPInfo.first;
4890 unsigned LocalIndex = PPInfo.second;
4891 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4892
4893 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4894 if (Loc.isInvalid())
4895 return false;
4896
4897 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4898 return true;
4899 else
4900 return false;
4901}
4902
4903namespace {
4904 /// \brief Visitor used to search for information about a header file.
4905 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004906 const FileEntry *FE;
4907
David Blaikie05785d12013-02-20 22:23:23 +00004908 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004909
4910 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004911 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4912 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004913
4914 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004915 HeaderFileInfoLookupTable *Table
4916 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4917 if (!Table)
4918 return false;
4919
4920 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00004921 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004922 if (Pos == Table->end())
4923 return false;
4924
Richard Smithbdf2d932015-07-30 03:37:16 +00004925 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00004926 return true;
4927 }
4928
David Blaikie05785d12013-02-20 22:23:23 +00004929 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004930 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004931}
Guy Benyei11169dd2012-12-18 14:30:41 +00004932
4933HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004934 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004935 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004936 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004937 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004938
4939 return HeaderFileInfo();
4940}
4941
4942void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4943 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004944 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004945 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4946 ModuleFile &F = *(*I);
4947 unsigned Idx = 0;
4948 DiagStates.clear();
4949 assert(!Diag.DiagStates.empty());
4950 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4951 while (Idx < F.PragmaDiagMappings.size()) {
4952 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4953 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4954 if (DiagStateID != 0) {
4955 Diag.DiagStatePoints.push_back(
4956 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4957 FullSourceLoc(Loc, SourceMgr)));
4958 continue;
4959 }
4960
4961 assert(DiagStateID == 0);
4962 // A new DiagState was created here.
4963 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4964 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4965 DiagStates.push_back(NewState);
4966 Diag.DiagStatePoints.push_back(
4967 DiagnosticsEngine::DiagStatePoint(NewState,
4968 FullSourceLoc(Loc, SourceMgr)));
4969 while (1) {
4970 assert(Idx < F.PragmaDiagMappings.size() &&
4971 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4972 if (Idx >= F.PragmaDiagMappings.size()) {
4973 break; // Something is messed up but at least avoid infinite loop in
4974 // release build.
4975 }
4976 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4977 if (DiagID == (unsigned)-1) {
4978 break; // no more diag/map pairs for this location.
4979 }
Alp Tokerc726c362014-06-10 09:31:37 +00004980 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
4981 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
4982 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00004983 }
4984 }
4985 }
4986}
4987
4988/// \brief Get the correct cursor and offset for loading a type.
4989ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4990 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4991 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4992 ModuleFile *M = I->second;
4993 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4994}
4995
4996/// \brief Read and return the type with the given index..
4997///
4998/// The index is the type ID, shifted and minus the number of predefs. This
4999/// routine actually reads the record corresponding to the type at the given
5000/// location. It is a helper routine for GetType, which deals with reading type
5001/// IDs.
5002QualType ASTReader::readTypeRecord(unsigned Index) {
5003 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005004 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005005
5006 // Keep track of where we are in the stream, then jump back there
5007 // after reading this type.
5008 SavedStreamPosition SavedPosition(DeclsCursor);
5009
5010 ReadingKindTracker ReadingKind(Read_Type, *this);
5011
5012 // Note that we are loading a type record.
5013 Deserializing AType(this);
5014
5015 unsigned Idx = 0;
5016 DeclsCursor.JumpToBit(Loc.Offset);
5017 RecordData Record;
5018 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005019 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005020 case TYPE_EXT_QUAL: {
5021 if (Record.size() != 2) {
5022 Error("Incorrect encoding of extended qualifier type");
5023 return QualType();
5024 }
5025 QualType Base = readType(*Loc.F, Record, Idx);
5026 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5027 return Context.getQualifiedType(Base, Quals);
5028 }
5029
5030 case TYPE_COMPLEX: {
5031 if (Record.size() != 1) {
5032 Error("Incorrect encoding of complex type");
5033 return QualType();
5034 }
5035 QualType ElemType = readType(*Loc.F, Record, Idx);
5036 return Context.getComplexType(ElemType);
5037 }
5038
5039 case TYPE_POINTER: {
5040 if (Record.size() != 1) {
5041 Error("Incorrect encoding of pointer type");
5042 return QualType();
5043 }
5044 QualType PointeeType = readType(*Loc.F, Record, Idx);
5045 return Context.getPointerType(PointeeType);
5046 }
5047
Reid Kleckner8a365022013-06-24 17:51:48 +00005048 case TYPE_DECAYED: {
5049 if (Record.size() != 1) {
5050 Error("Incorrect encoding of decayed type");
5051 return QualType();
5052 }
5053 QualType OriginalType = readType(*Loc.F, Record, Idx);
5054 QualType DT = Context.getAdjustedParameterType(OriginalType);
5055 if (!isa<DecayedType>(DT))
5056 Error("Decayed type does not decay");
5057 return DT;
5058 }
5059
Reid Kleckner0503a872013-12-05 01:23:43 +00005060 case TYPE_ADJUSTED: {
5061 if (Record.size() != 2) {
5062 Error("Incorrect encoding of adjusted type");
5063 return QualType();
5064 }
5065 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5066 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5067 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5068 }
5069
Guy Benyei11169dd2012-12-18 14:30:41 +00005070 case TYPE_BLOCK_POINTER: {
5071 if (Record.size() != 1) {
5072 Error("Incorrect encoding of block pointer type");
5073 return QualType();
5074 }
5075 QualType PointeeType = readType(*Loc.F, Record, Idx);
5076 return Context.getBlockPointerType(PointeeType);
5077 }
5078
5079 case TYPE_LVALUE_REFERENCE: {
5080 if (Record.size() != 2) {
5081 Error("Incorrect encoding of lvalue reference type");
5082 return QualType();
5083 }
5084 QualType PointeeType = readType(*Loc.F, Record, Idx);
5085 return Context.getLValueReferenceType(PointeeType, Record[1]);
5086 }
5087
5088 case TYPE_RVALUE_REFERENCE: {
5089 if (Record.size() != 1) {
5090 Error("Incorrect encoding of rvalue reference type");
5091 return QualType();
5092 }
5093 QualType PointeeType = readType(*Loc.F, Record, Idx);
5094 return Context.getRValueReferenceType(PointeeType);
5095 }
5096
5097 case TYPE_MEMBER_POINTER: {
5098 if (Record.size() != 2) {
5099 Error("Incorrect encoding of member pointer type");
5100 return QualType();
5101 }
5102 QualType PointeeType = readType(*Loc.F, Record, Idx);
5103 QualType ClassType = readType(*Loc.F, Record, Idx);
5104 if (PointeeType.isNull() || ClassType.isNull())
5105 return QualType();
5106
5107 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5108 }
5109
5110 case TYPE_CONSTANT_ARRAY: {
5111 QualType ElementType = readType(*Loc.F, Record, Idx);
5112 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5113 unsigned IndexTypeQuals = Record[2];
5114 unsigned Idx = 3;
5115 llvm::APInt Size = ReadAPInt(Record, Idx);
5116 return Context.getConstantArrayType(ElementType, Size,
5117 ASM, IndexTypeQuals);
5118 }
5119
5120 case TYPE_INCOMPLETE_ARRAY: {
5121 QualType ElementType = readType(*Loc.F, Record, Idx);
5122 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5123 unsigned IndexTypeQuals = Record[2];
5124 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5125 }
5126
5127 case TYPE_VARIABLE_ARRAY: {
5128 QualType ElementType = readType(*Loc.F, Record, Idx);
5129 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5130 unsigned IndexTypeQuals = Record[2];
5131 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5132 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5133 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5134 ASM, IndexTypeQuals,
5135 SourceRange(LBLoc, RBLoc));
5136 }
5137
5138 case TYPE_VECTOR: {
5139 if (Record.size() != 3) {
5140 Error("incorrect encoding of vector type in AST file");
5141 return QualType();
5142 }
5143
5144 QualType ElementType = readType(*Loc.F, Record, Idx);
5145 unsigned NumElements = Record[1];
5146 unsigned VecKind = Record[2];
5147 return Context.getVectorType(ElementType, NumElements,
5148 (VectorType::VectorKind)VecKind);
5149 }
5150
5151 case TYPE_EXT_VECTOR: {
5152 if (Record.size() != 3) {
5153 Error("incorrect encoding of extended vector type in AST file");
5154 return QualType();
5155 }
5156
5157 QualType ElementType = readType(*Loc.F, Record, Idx);
5158 unsigned NumElements = Record[1];
5159 return Context.getExtVectorType(ElementType, NumElements);
5160 }
5161
5162 case TYPE_FUNCTION_NO_PROTO: {
5163 if (Record.size() != 6) {
5164 Error("incorrect encoding of no-proto function type");
5165 return QualType();
5166 }
5167 QualType ResultType = readType(*Loc.F, Record, Idx);
5168 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5169 (CallingConv)Record[4], Record[5]);
5170 return Context.getFunctionNoProtoType(ResultType, Info);
5171 }
5172
5173 case TYPE_FUNCTION_PROTO: {
5174 QualType ResultType = readType(*Loc.F, Record, Idx);
5175
5176 FunctionProtoType::ExtProtoInfo EPI;
5177 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5178 /*hasregparm*/ Record[2],
5179 /*regparm*/ Record[3],
5180 static_cast<CallingConv>(Record[4]),
5181 /*produces*/ Record[5]);
5182
5183 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005184
5185 EPI.Variadic = Record[Idx++];
5186 EPI.HasTrailingReturn = Record[Idx++];
5187 EPI.TypeQuals = Record[Idx++];
5188 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005189 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005190 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005191
5192 unsigned NumParams = Record[Idx++];
5193 SmallVector<QualType, 16> ParamTypes;
5194 for (unsigned I = 0; I != NumParams; ++I)
5195 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5196
Jordan Rose5c382722013-03-08 21:51:21 +00005197 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005198 }
5199
5200 case TYPE_UNRESOLVED_USING: {
5201 unsigned Idx = 0;
5202 return Context.getTypeDeclType(
5203 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5204 }
5205
5206 case TYPE_TYPEDEF: {
5207 if (Record.size() != 2) {
5208 Error("incorrect encoding of typedef type");
5209 return QualType();
5210 }
5211 unsigned Idx = 0;
5212 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5213 QualType Canonical = readType(*Loc.F, Record, Idx);
5214 if (!Canonical.isNull())
5215 Canonical = Context.getCanonicalType(Canonical);
5216 return Context.getTypedefType(Decl, Canonical);
5217 }
5218
5219 case TYPE_TYPEOF_EXPR:
5220 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5221
5222 case TYPE_TYPEOF: {
5223 if (Record.size() != 1) {
5224 Error("incorrect encoding of typeof(type) in AST file");
5225 return QualType();
5226 }
5227 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5228 return Context.getTypeOfType(UnderlyingType);
5229 }
5230
5231 case TYPE_DECLTYPE: {
5232 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5233 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5234 }
5235
5236 case TYPE_UNARY_TRANSFORM: {
5237 QualType BaseType = readType(*Loc.F, Record, Idx);
5238 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5239 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5240 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5241 }
5242
Richard Smith74aeef52013-04-26 16:15:35 +00005243 case TYPE_AUTO: {
5244 QualType Deduced = readType(*Loc.F, Record, Idx);
5245 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005246 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005247 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005248 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005249
5250 case TYPE_RECORD: {
5251 if (Record.size() != 2) {
5252 Error("incorrect encoding of record type");
5253 return QualType();
5254 }
5255 unsigned Idx = 0;
5256 bool IsDependent = Record[Idx++];
5257 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5258 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5259 QualType T = Context.getRecordType(RD);
5260 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5261 return T;
5262 }
5263
5264 case TYPE_ENUM: {
5265 if (Record.size() != 2) {
5266 Error("incorrect encoding of enum type");
5267 return QualType();
5268 }
5269 unsigned Idx = 0;
5270 bool IsDependent = Record[Idx++];
5271 QualType T
5272 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5273 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5274 return T;
5275 }
5276
5277 case TYPE_ATTRIBUTED: {
5278 if (Record.size() != 3) {
5279 Error("incorrect encoding of attributed type");
5280 return QualType();
5281 }
5282 QualType modifiedType = readType(*Loc.F, Record, Idx);
5283 QualType equivalentType = readType(*Loc.F, Record, Idx);
5284 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5285 return Context.getAttributedType(kind, modifiedType, equivalentType);
5286 }
5287
5288 case TYPE_PAREN: {
5289 if (Record.size() != 1) {
5290 Error("incorrect encoding of paren type");
5291 return QualType();
5292 }
5293 QualType InnerType = readType(*Loc.F, Record, Idx);
5294 return Context.getParenType(InnerType);
5295 }
5296
5297 case TYPE_PACK_EXPANSION: {
5298 if (Record.size() != 2) {
5299 Error("incorrect encoding of pack expansion type");
5300 return QualType();
5301 }
5302 QualType Pattern = readType(*Loc.F, Record, Idx);
5303 if (Pattern.isNull())
5304 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005305 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005306 if (Record[1])
5307 NumExpansions = Record[1] - 1;
5308 return Context.getPackExpansionType(Pattern, NumExpansions);
5309 }
5310
5311 case TYPE_ELABORATED: {
5312 unsigned Idx = 0;
5313 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5314 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5315 QualType NamedType = readType(*Loc.F, Record, Idx);
5316 return Context.getElaboratedType(Keyword, NNS, NamedType);
5317 }
5318
5319 case TYPE_OBJC_INTERFACE: {
5320 unsigned Idx = 0;
5321 ObjCInterfaceDecl *ItfD
5322 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5323 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5324 }
5325
5326 case TYPE_OBJC_OBJECT: {
5327 unsigned Idx = 0;
5328 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005329 unsigned NumTypeArgs = Record[Idx++];
5330 SmallVector<QualType, 4> TypeArgs;
5331 for (unsigned I = 0; I != NumTypeArgs; ++I)
5332 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005333 unsigned NumProtos = Record[Idx++];
5334 SmallVector<ObjCProtocolDecl*, 4> Protos;
5335 for (unsigned I = 0; I != NumProtos; ++I)
5336 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005337 bool IsKindOf = Record[Idx++];
5338 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005339 }
5340
5341 case TYPE_OBJC_OBJECT_POINTER: {
5342 unsigned Idx = 0;
5343 QualType Pointee = readType(*Loc.F, Record, Idx);
5344 return Context.getObjCObjectPointerType(Pointee);
5345 }
5346
5347 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5348 unsigned Idx = 0;
5349 QualType Parm = readType(*Loc.F, Record, Idx);
5350 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005351 return Context.getSubstTemplateTypeParmType(
5352 cast<TemplateTypeParmType>(Parm),
5353 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005354 }
5355
5356 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5357 unsigned Idx = 0;
5358 QualType Parm = readType(*Loc.F, Record, Idx);
5359 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5360 return Context.getSubstTemplateTypeParmPackType(
5361 cast<TemplateTypeParmType>(Parm),
5362 ArgPack);
5363 }
5364
5365 case TYPE_INJECTED_CLASS_NAME: {
5366 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5367 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5368 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5369 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005370 const Type *T = nullptr;
5371 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5372 if (const Type *Existing = DI->getTypeForDecl()) {
5373 T = Existing;
5374 break;
5375 }
5376 }
5377 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005378 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005379 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5380 DI->setTypeForDecl(T);
5381 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005382 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005383 }
5384
5385 case TYPE_TEMPLATE_TYPE_PARM: {
5386 unsigned Idx = 0;
5387 unsigned Depth = Record[Idx++];
5388 unsigned Index = Record[Idx++];
5389 bool Pack = Record[Idx++];
5390 TemplateTypeParmDecl *D
5391 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5392 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5393 }
5394
5395 case TYPE_DEPENDENT_NAME: {
5396 unsigned Idx = 0;
5397 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5398 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005399 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005400 QualType Canon = readType(*Loc.F, Record, Idx);
5401 if (!Canon.isNull())
5402 Canon = Context.getCanonicalType(Canon);
5403 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5404 }
5405
5406 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5407 unsigned Idx = 0;
5408 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5409 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005410 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005411 unsigned NumArgs = Record[Idx++];
5412 SmallVector<TemplateArgument, 8> Args;
5413 Args.reserve(NumArgs);
5414 while (NumArgs--)
5415 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5416 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5417 Args.size(), Args.data());
5418 }
5419
5420 case TYPE_DEPENDENT_SIZED_ARRAY: {
5421 unsigned Idx = 0;
5422
5423 // ArrayType
5424 QualType ElementType = readType(*Loc.F, Record, Idx);
5425 ArrayType::ArraySizeModifier ASM
5426 = (ArrayType::ArraySizeModifier)Record[Idx++];
5427 unsigned IndexTypeQuals = Record[Idx++];
5428
5429 // DependentSizedArrayType
5430 Expr *NumElts = ReadExpr(*Loc.F);
5431 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5432
5433 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5434 IndexTypeQuals, Brackets);
5435 }
5436
5437 case TYPE_TEMPLATE_SPECIALIZATION: {
5438 unsigned Idx = 0;
5439 bool IsDependent = Record[Idx++];
5440 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5441 SmallVector<TemplateArgument, 8> Args;
5442 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5443 QualType Underlying = readType(*Loc.F, Record, Idx);
5444 QualType T;
5445 if (Underlying.isNull())
5446 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5447 Args.size());
5448 else
5449 T = Context.getTemplateSpecializationType(Name, Args.data(),
5450 Args.size(), Underlying);
5451 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5452 return T;
5453 }
5454
5455 case TYPE_ATOMIC: {
5456 if (Record.size() != 1) {
5457 Error("Incorrect encoding of atomic type");
5458 return QualType();
5459 }
5460 QualType ValueType = readType(*Loc.F, Record, Idx);
5461 return Context.getAtomicType(ValueType);
5462 }
5463 }
5464 llvm_unreachable("Invalid TypeCode!");
5465}
5466
Richard Smith564417a2014-03-20 21:47:22 +00005467void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5468 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005469 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005470 const RecordData &Record, unsigned &Idx) {
5471 ExceptionSpecificationType EST =
5472 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005473 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005474 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005475 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005476 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005477 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005478 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005479 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005480 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005481 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5482 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005483 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005484 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005485 }
5486}
5487
Guy Benyei11169dd2012-12-18 14:30:41 +00005488class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5489 ASTReader &Reader;
5490 ModuleFile &F;
5491 const ASTReader::RecordData &Record;
5492 unsigned &Idx;
5493
5494 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5495 unsigned &I) {
5496 return Reader.ReadSourceLocation(F, R, I);
5497 }
5498
5499 template<typename T>
5500 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5501 return Reader.ReadDeclAs<T>(F, Record, Idx);
5502 }
5503
5504public:
5505 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5506 const ASTReader::RecordData &Record, unsigned &Idx)
5507 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5508 { }
5509
5510 // We want compile-time assurance that we've enumerated all of
5511 // these, so unfortunately we have to declare them first, then
5512 // define them out-of-line.
5513#define ABSTRACT_TYPELOC(CLASS, PARENT)
5514#define TYPELOC(CLASS, PARENT) \
5515 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5516#include "clang/AST/TypeLocNodes.def"
5517
5518 void VisitFunctionTypeLoc(FunctionTypeLoc);
5519 void VisitArrayTypeLoc(ArrayTypeLoc);
5520};
5521
5522void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5523 // nothing to do
5524}
5525void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5526 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5527 if (TL.needsExtraLocalData()) {
5528 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5529 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5530 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5531 TL.setModeAttr(Record[Idx++]);
5532 }
5533}
5534void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5535 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5536}
5537void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5538 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5539}
Reid Kleckner8a365022013-06-24 17:51:48 +00005540void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5541 // nothing to do
5542}
Reid Kleckner0503a872013-12-05 01:23:43 +00005543void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5544 // nothing to do
5545}
Guy Benyei11169dd2012-12-18 14:30:41 +00005546void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5547 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5548}
5549void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5550 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5551}
5552void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5553 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5554}
5555void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5556 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5557 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5558}
5559void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5560 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5561 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5562 if (Record[Idx++])
5563 TL.setSizeExpr(Reader.ReadExpr(F));
5564 else
Craig Toppera13603a2014-05-22 05:54:18 +00005565 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005566}
5567void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5568 VisitArrayTypeLoc(TL);
5569}
5570void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5571 VisitArrayTypeLoc(TL);
5572}
5573void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5574 VisitArrayTypeLoc(TL);
5575}
5576void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5577 DependentSizedArrayTypeLoc TL) {
5578 VisitArrayTypeLoc(TL);
5579}
5580void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5581 DependentSizedExtVectorTypeLoc TL) {
5582 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5583}
5584void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5585 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5586}
5587void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5588 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5589}
5590void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5591 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5592 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5593 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5594 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005595 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5596 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005597 }
5598}
5599void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5600 VisitFunctionTypeLoc(TL);
5601}
5602void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5603 VisitFunctionTypeLoc(TL);
5604}
5605void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5606 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5607}
5608void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5609 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5610}
5611void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5612 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5613 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5614 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5615}
5616void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5617 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5618 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5619 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5620 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5621}
5622void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5623 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5624}
5625void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5626 TL.setKWLoc(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::VisitAutoTypeLoc(AutoTypeLoc TL) {
5632 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5633}
5634void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5635 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5636}
5637void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5638 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5639}
5640void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5641 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5642 if (TL.hasAttrOperand()) {
5643 SourceRange range;
5644 range.setBegin(ReadSourceLocation(Record, Idx));
5645 range.setEnd(ReadSourceLocation(Record, Idx));
5646 TL.setAttrOperandParensRange(range);
5647 }
5648 if (TL.hasAttrExprOperand()) {
5649 if (Record[Idx++])
5650 TL.setAttrExprOperand(Reader.ReadExpr(F));
5651 else
Craig Toppera13603a2014-05-22 05:54:18 +00005652 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005653 } else if (TL.hasAttrEnumOperand())
5654 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5655}
5656void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5657 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5658}
5659void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5660 SubstTemplateTypeParmTypeLoc TL) {
5661 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5662}
5663void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5664 SubstTemplateTypeParmPackTypeLoc TL) {
5665 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5666}
5667void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5668 TemplateSpecializationTypeLoc TL) {
5669 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5670 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5671 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5672 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5673 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5674 TL.setArgLocInfo(i,
5675 Reader.GetTemplateArgumentLocInfo(F,
5676 TL.getTypePtr()->getArg(i).getKind(),
5677 Record, Idx));
5678}
5679void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5680 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5681 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5682}
5683void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5684 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5685 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5686}
5687void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5688 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5689}
5690void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5691 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5692 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5693 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5694}
5695void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5696 DependentTemplateSpecializationTypeLoc TL) {
5697 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5698 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5699 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5700 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5701 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5702 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5703 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5704 TL.setArgLocInfo(I,
5705 Reader.GetTemplateArgumentLocInfo(F,
5706 TL.getTypePtr()->getArg(I).getKind(),
5707 Record, Idx));
5708}
5709void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5710 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5711}
5712void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5713 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5714}
5715void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5716 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005717 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5718 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5719 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5720 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5721 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5722 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005723 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5724 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5725}
5726void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5727 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5728}
5729void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5730 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5731 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5732 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5733}
5734
5735TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5736 const RecordData &Record,
5737 unsigned &Idx) {
5738 QualType InfoTy = readType(F, Record, Idx);
5739 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005740 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005741
5742 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5743 TypeLocReader TLR(*this, F, Record, Idx);
5744 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5745 TLR.Visit(TL);
5746 return TInfo;
5747}
5748
5749QualType ASTReader::GetType(TypeID ID) {
5750 unsigned FastQuals = ID & Qualifiers::FastMask;
5751 unsigned Index = ID >> Qualifiers::FastWidth;
5752
5753 if (Index < NUM_PREDEF_TYPE_IDS) {
5754 QualType T;
5755 switch ((PredefinedTypeIDs)Index) {
5756 case PREDEF_TYPE_NULL_ID: return QualType();
5757 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5758 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5759
5760 case PREDEF_TYPE_CHAR_U_ID:
5761 case PREDEF_TYPE_CHAR_S_ID:
5762 // FIXME: Check that the signedness of CharTy is correct!
5763 T = Context.CharTy;
5764 break;
5765
5766 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5767 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5768 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5769 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5770 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5771 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5772 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5773 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5774 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5775 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5776 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5777 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5778 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5779 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5780 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5781 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5782 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5783 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5784 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5785 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5786 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5787 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5788 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5789 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5790 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5791 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5792 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5793 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005794 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5795 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5796 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5797 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5798 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5799 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005800 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005801 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005802 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5803
5804 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5805 T = Context.getAutoRRefDeductType();
5806 break;
5807
5808 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5809 T = Context.ARCUnbridgedCastTy;
5810 break;
5811
Guy Benyei11169dd2012-12-18 14:30:41 +00005812 case PREDEF_TYPE_BUILTIN_FN:
5813 T = Context.BuiltinFnTy;
5814 break;
5815 }
5816
5817 assert(!T.isNull() && "Unknown predefined type");
5818 return T.withFastQualifiers(FastQuals);
5819 }
5820
5821 Index -= NUM_PREDEF_TYPE_IDS;
5822 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5823 if (TypesLoaded[Index].isNull()) {
5824 TypesLoaded[Index] = readTypeRecord(Index);
5825 if (TypesLoaded[Index].isNull())
5826 return QualType();
5827
5828 TypesLoaded[Index]->setFromAST();
5829 if (DeserializationListener)
5830 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5831 TypesLoaded[Index]);
5832 }
5833
5834 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5835}
5836
5837QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5838 return GetType(getGlobalTypeID(F, LocalID));
5839}
5840
5841serialization::TypeID
5842ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5843 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5844 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5845
5846 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5847 return LocalID;
5848
5849 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5850 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5851 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5852
5853 unsigned GlobalIndex = LocalIndex + I->second;
5854 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5855}
5856
5857TemplateArgumentLocInfo
5858ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5859 TemplateArgument::ArgKind Kind,
5860 const RecordData &Record,
5861 unsigned &Index) {
5862 switch (Kind) {
5863 case TemplateArgument::Expression:
5864 return ReadExpr(F);
5865 case TemplateArgument::Type:
5866 return GetTypeSourceInfo(F, Record, Index);
5867 case TemplateArgument::Template: {
5868 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5869 Index);
5870 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5871 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5872 SourceLocation());
5873 }
5874 case TemplateArgument::TemplateExpansion: {
5875 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5876 Index);
5877 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5878 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5879 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5880 EllipsisLoc);
5881 }
5882 case TemplateArgument::Null:
5883 case TemplateArgument::Integral:
5884 case TemplateArgument::Declaration:
5885 case TemplateArgument::NullPtr:
5886 case TemplateArgument::Pack:
5887 // FIXME: Is this right?
5888 return TemplateArgumentLocInfo();
5889 }
5890 llvm_unreachable("unexpected template argument loc");
5891}
5892
5893TemplateArgumentLoc
5894ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5895 const RecordData &Record, unsigned &Index) {
5896 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5897
5898 if (Arg.getKind() == TemplateArgument::Expression) {
5899 if (Record[Index++]) // bool InfoHasSameExpr.
5900 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5901 }
5902 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5903 Record, Index));
5904}
5905
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005906const ASTTemplateArgumentListInfo*
5907ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5908 const RecordData &Record,
5909 unsigned &Index) {
5910 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5911 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5912 unsigned NumArgsAsWritten = Record[Index++];
5913 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5914 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5915 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5916 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5917}
5918
Guy Benyei11169dd2012-12-18 14:30:41 +00005919Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5920 return GetDecl(ID);
5921}
5922
Richard Smith50895422015-01-31 03:04:55 +00005923template<typename TemplateSpecializationDecl>
5924static void completeRedeclChainForTemplateSpecialization(Decl *D) {
5925 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
5926 TSD->getSpecializedTemplate()->LoadLazySpecializations();
5927}
5928
Richard Smith053f6c62014-05-16 23:01:30 +00005929void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005930 if (NumCurrentElementsDeserializing) {
5931 // We arrange to not care about the complete redeclaration chain while we're
5932 // deserializing. Just remember that the AST has marked this one as complete
5933 // but that it's not actually complete yet, so we know we still need to
5934 // complete it later.
5935 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5936 return;
5937 }
5938
Richard Smith053f6c62014-05-16 23:01:30 +00005939 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5940
Richard Smith053f6c62014-05-16 23:01:30 +00005941 // If this is a named declaration, complete it by looking it up
5942 // within its context.
5943 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00005944 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00005945 // all mergeable entities within it.
5946 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5947 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5948 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00005949 if (!getContext().getLangOpts().CPlusPlus &&
5950 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00005951 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00005952 // the identifier instead. (For C++ modules, we don't store decls
5953 // in the serialized identifier table, so we do the lookup in the TU.)
5954 auto *II = Name.getAsIdentifierInfo();
5955 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00005956 if (II->isOutOfDate())
5957 updateOutOfDateIdentifier(*II);
5958 } else
5959 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00005960 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00005961 // Find all declarations of this kind from the relevant context.
5962 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
5963 auto *DC = cast<DeclContext>(DCDecl);
5964 SmallVector<Decl*, 8> Decls;
5965 FindExternalLexicalDecls(
5966 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
5967 }
Richard Smith053f6c62014-05-16 23:01:30 +00005968 }
5969 }
Richard Smith50895422015-01-31 03:04:55 +00005970
5971 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
5972 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
5973 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
5974 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
5975 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5976 if (auto *Template = FD->getPrimaryTemplate())
5977 Template->LoadLazySpecializations();
5978 }
Richard Smith053f6c62014-05-16 23:01:30 +00005979}
5980
Richard Smithc2bb8182015-03-24 06:36:48 +00005981uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
5982 const RecordData &Record,
5983 unsigned &Idx) {
5984 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
5985 Error("malformed AST file: missing C++ ctor initializers");
5986 return 0;
5987 }
5988
5989 unsigned LocalID = Record[Idx++];
5990 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
5991}
5992
5993CXXCtorInitializer **
5994ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
5995 RecordLocation Loc = getLocalBitOffset(Offset);
5996 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
5997 SavedStreamPosition SavedPosition(Cursor);
5998 Cursor.JumpToBit(Loc.Offset);
5999 ReadingKindTracker ReadingKind(Read_Decl, *this);
6000
6001 RecordData Record;
6002 unsigned Code = Cursor.ReadCode();
6003 unsigned RecCode = Cursor.readRecord(Code, Record);
6004 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6005 Error("malformed AST file: missing C++ ctor initializers");
6006 return nullptr;
6007 }
6008
6009 unsigned Idx = 0;
6010 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6011}
6012
Richard Smithcd45dbc2014-04-19 03:48:30 +00006013uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6014 const RecordData &Record,
6015 unsigned &Idx) {
6016 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6017 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006018 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006019 }
6020
Guy Benyei11169dd2012-12-18 14:30:41 +00006021 unsigned LocalID = Record[Idx++];
6022 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6023}
6024
6025CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6026 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006027 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006028 SavedStreamPosition SavedPosition(Cursor);
6029 Cursor.JumpToBit(Loc.Offset);
6030 ReadingKindTracker ReadingKind(Read_Decl, *this);
6031 RecordData Record;
6032 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006033 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006034 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006035 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006036 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006037 }
6038
6039 unsigned Idx = 0;
6040 unsigned NumBases = Record[Idx++];
6041 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6042 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6043 for (unsigned I = 0; I != NumBases; ++I)
6044 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6045 return Bases;
6046}
6047
6048serialization::DeclID
6049ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6050 if (LocalID < NUM_PREDEF_DECL_IDS)
6051 return LocalID;
6052
6053 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6054 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6055 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6056
6057 return LocalID + I->second;
6058}
6059
6060bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6061 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006062 // Predefined decls aren't from any module.
6063 if (ID < NUM_PREDEF_DECL_IDS)
6064 return false;
6065
Richard Smithbcda1a92015-07-12 23:51:20 +00006066 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6067 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006068}
6069
Douglas Gregor9f782892013-01-21 15:25:38 +00006070ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006071 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006072 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006073 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6074 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6075 return I->second;
6076}
6077
6078SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6079 if (ID < NUM_PREDEF_DECL_IDS)
6080 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006081
Guy Benyei11169dd2012-12-18 14:30:41 +00006082 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6083
6084 if (Index > DeclsLoaded.size()) {
6085 Error("declaration ID out-of-range for AST file");
6086 return SourceLocation();
6087 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006088
Guy Benyei11169dd2012-12-18 14:30:41 +00006089 if (Decl *D = DeclsLoaded[Index])
6090 return D->getLocation();
6091
6092 unsigned RawLocation = 0;
6093 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6094 return ReadSourceLocation(*Rec.F, RawLocation);
6095}
6096
Richard Smithfe620d22015-03-05 23:24:12 +00006097static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6098 switch (ID) {
6099 case PREDEF_DECL_NULL_ID:
6100 return nullptr;
6101
6102 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6103 return Context.getTranslationUnitDecl();
6104
6105 case PREDEF_DECL_OBJC_ID_ID:
6106 return Context.getObjCIdDecl();
6107
6108 case PREDEF_DECL_OBJC_SEL_ID:
6109 return Context.getObjCSelDecl();
6110
6111 case PREDEF_DECL_OBJC_CLASS_ID:
6112 return Context.getObjCClassDecl();
6113
6114 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6115 return Context.getObjCProtocolDecl();
6116
6117 case PREDEF_DECL_INT_128_ID:
6118 return Context.getInt128Decl();
6119
6120 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6121 return Context.getUInt128Decl();
6122
6123 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6124 return Context.getObjCInstanceTypeDecl();
6125
6126 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6127 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006128
Richard Smith9b88a4c2015-07-27 05:40:23 +00006129 case PREDEF_DECL_VA_LIST_TAG:
6130 return Context.getVaListTagDecl();
6131
Richard Smithf19e1272015-03-07 00:04:49 +00006132 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6133 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006134 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006135 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006136}
6137
Richard Smithcd45dbc2014-04-19 03:48:30 +00006138Decl *ASTReader::GetExistingDecl(DeclID ID) {
6139 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006140 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6141 if (D) {
6142 // Track that we have merged the declaration with ID \p ID into the
6143 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006144 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006145 if (Merged.empty())
6146 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006147 }
Richard Smithfe620d22015-03-05 23:24:12 +00006148 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006149 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006150
Guy Benyei11169dd2012-12-18 14:30:41 +00006151 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6152
6153 if (Index >= DeclsLoaded.size()) {
6154 assert(0 && "declaration ID out-of-range for AST file");
6155 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006156 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006157 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006158
6159 return DeclsLoaded[Index];
6160}
6161
6162Decl *ASTReader::GetDecl(DeclID ID) {
6163 if (ID < NUM_PREDEF_DECL_IDS)
6164 return GetExistingDecl(ID);
6165
6166 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6167
6168 if (Index >= DeclsLoaded.size()) {
6169 assert(0 && "declaration ID out-of-range for AST file");
6170 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006171 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006172 }
6173
Guy Benyei11169dd2012-12-18 14:30:41 +00006174 if (!DeclsLoaded[Index]) {
6175 ReadDeclRecord(ID);
6176 if (DeserializationListener)
6177 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6178 }
6179
6180 return DeclsLoaded[Index];
6181}
6182
6183DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6184 DeclID GlobalID) {
6185 if (GlobalID < NUM_PREDEF_DECL_IDS)
6186 return GlobalID;
6187
6188 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6189 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6190 ModuleFile *Owner = I->second;
6191
6192 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6193 = M.GlobalToLocalDeclIDs.find(Owner);
6194 if (Pos == M.GlobalToLocalDeclIDs.end())
6195 return 0;
6196
6197 return GlobalID - Owner->BaseDeclID + Pos->second;
6198}
6199
6200serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6201 const RecordData &Record,
6202 unsigned &Idx) {
6203 if (Idx >= Record.size()) {
6204 Error("Corrupted AST file");
6205 return 0;
6206 }
6207
6208 return getGlobalDeclID(F, Record[Idx++]);
6209}
6210
6211/// \brief Resolve the offset of a statement into a statement.
6212///
6213/// This operation will read a new statement from the external
6214/// source each time it is called, and is meant to be used via a
6215/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6216Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6217 // Switch case IDs are per Decl.
6218 ClearSwitchCaseIDs();
6219
6220 // Offset here is a global offset across the entire chain.
6221 RecordLocation Loc = getLocalBitOffset(Offset);
6222 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6223 return ReadStmtFromStream(*Loc.F);
6224}
6225
Richard Smith3cb15722015-08-05 22:41:45 +00006226void ASTReader::FindExternalLexicalDecls(
6227 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6228 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006229 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6230
Richard Smith9ccdd932015-08-06 22:14:12 +00006231 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006232 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6233 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6234 auto K = (Decl::Kind)+LexicalDecls[I];
6235 if (!IsKindWeWant(K))
6236 continue;
6237
6238 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6239
6240 // Don't add predefined declarations to the lexical context more
6241 // than once.
6242 if (ID < NUM_PREDEF_DECL_IDS) {
6243 if (PredefsVisited[ID])
6244 continue;
6245
6246 PredefsVisited[ID] = true;
6247 }
6248
6249 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006250 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006251 if (!DC->isDeclInLexicalTraversal(D))
6252 Decls.push_back(D);
6253 }
6254 }
6255 };
6256
6257 if (isa<TranslationUnitDecl>(DC)) {
6258 for (auto Lexical : TULexicalDecls)
6259 Visit(Lexical.first, Lexical.second);
6260 } else {
6261 auto I = LexicalDecls.find(DC);
6262 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006263 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006264 }
6265
Guy Benyei11169dd2012-12-18 14:30:41 +00006266 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006267}
6268
6269namespace {
6270
6271class DeclIDComp {
6272 ASTReader &Reader;
6273 ModuleFile &Mod;
6274
6275public:
6276 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6277
6278 bool operator()(LocalDeclID L, LocalDeclID R) const {
6279 SourceLocation LHS = getLocation(L);
6280 SourceLocation RHS = getLocation(R);
6281 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6282 }
6283
6284 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6285 SourceLocation RHS = getLocation(R);
6286 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6287 }
6288
6289 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6290 SourceLocation LHS = getLocation(L);
6291 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6292 }
6293
6294 SourceLocation getLocation(LocalDeclID ID) const {
6295 return Reader.getSourceManager().getFileLoc(
6296 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6297 }
6298};
6299
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006300}
Guy Benyei11169dd2012-12-18 14:30:41 +00006301
6302void ASTReader::FindFileRegionDecls(FileID File,
6303 unsigned Offset, unsigned Length,
6304 SmallVectorImpl<Decl *> &Decls) {
6305 SourceManager &SM = getSourceManager();
6306
6307 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6308 if (I == FileDeclIDs.end())
6309 return;
6310
6311 FileDeclsInfo &DInfo = I->second;
6312 if (DInfo.Decls.empty())
6313 return;
6314
6315 SourceLocation
6316 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6317 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6318
6319 DeclIDComp DIDComp(*this, *DInfo.Mod);
6320 ArrayRef<serialization::LocalDeclID>::iterator
6321 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6322 BeginLoc, DIDComp);
6323 if (BeginIt != DInfo.Decls.begin())
6324 --BeginIt;
6325
6326 // If we are pointing at a top-level decl inside an objc container, we need
6327 // to backtrack until we find it otherwise we will fail to report that the
6328 // region overlaps with an objc container.
6329 while (BeginIt != DInfo.Decls.begin() &&
6330 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6331 ->isTopLevelDeclInObjCContainer())
6332 --BeginIt;
6333
6334 ArrayRef<serialization::LocalDeclID>::iterator
6335 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6336 EndLoc, DIDComp);
6337 if (EndIt != DInfo.Decls.end())
6338 ++EndIt;
6339
6340 for (ArrayRef<serialization::LocalDeclID>::iterator
6341 DIt = BeginIt; DIt != EndIt; ++DIt)
6342 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6343}
6344
Richard Smith3b637412015-07-14 18:42:41 +00006345/// \brief Retrieve the "definitive" module file for the definition of the
6346/// given declaration context, if there is one.
6347///
6348/// The "definitive" module file is the only place where we need to look to
6349/// find information about the declarations within the given declaration
6350/// context. For example, C++ and Objective-C classes, C structs/unions, and
6351/// Objective-C protocols, categories, and extensions are all defined in a
6352/// single place in the source code, so they have definitive module files
6353/// associated with them. C++ namespaces, on the other hand, can have
6354/// definitions in multiple different module files.
6355///
6356/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6357/// NDEBUG checking.
6358static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6359 ASTReader &Reader) {
6360 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6361 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
6362
6363 return nullptr;
6364}
6365
Guy Benyei11169dd2012-12-18 14:30:41 +00006366namespace {
6367 /// \brief ModuleFile visitor used to perform name lookup into a
6368 /// declaration context.
6369 class DeclContextNameLookupVisitor {
6370 ASTReader &Reader;
Richard Smithf13c68d2015-08-06 21:05:21 +00006371 const DeclContext *Context;
Guy Benyei11169dd2012-12-18 14:30:41 +00006372 DeclarationName Name;
Richard Smith3b637412015-07-14 18:42:41 +00006373 ASTDeclContextNameLookupTrait::DeclNameKey NameKey;
6374 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00006375 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006376 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006377
6378 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006379 DeclContextNameLookupVisitor(ASTReader &Reader,
Richard Smithf13c68d2015-08-06 21:05:21 +00006380 const DeclContext *Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00006381 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006382 SmallVectorImpl<NamedDecl *> &Decls,
6383 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
Richard Smithf13c68d2015-08-06 21:05:21 +00006384 : Reader(Reader), Context(Context), Name(Name),
Richard Smith3b637412015-07-14 18:42:41 +00006385 NameKey(ASTDeclContextNameLookupTrait::GetInternalKey(Name)),
6386 NameHash(ASTDeclContextNameLookupTrait::ComputeHash(NameKey)),
6387 Decls(Decls), DeclSet(DeclSet) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006388
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006389 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006390 // Check whether we have any visible declaration information for
6391 // this context in this module.
Richard Smithf13c68d2015-08-06 21:05:21 +00006392 auto Info = M.DeclContextInfos.find(Context);
6393 if (Info == M.DeclContextInfos.end() || !Info->second.NameLookupTableData)
Guy Benyei11169dd2012-12-18 14:30:41 +00006394 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006395
Guy Benyei11169dd2012-12-18 14:30:41 +00006396 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006397 ASTDeclContextNameLookupTable *LookupTable =
Richard Smithf13c68d2015-08-06 21:05:21 +00006398 Info->second.NameLookupTableData;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006399 ASTDeclContextNameLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00006400 LookupTable->find_hashed(NameKey, NameHash);
Guy Benyei11169dd2012-12-18 14:30:41 +00006401 if (Pos == LookupTable->end())
6402 return false;
6403
6404 bool FoundAnything = false;
6405 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6406 for (; Data.first != Data.second; ++Data.first) {
Richard Smithbdf2d932015-07-30 03:37:16 +00006407 NamedDecl *ND = Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
Guy Benyei11169dd2012-12-18 14:30:41 +00006408 if (!ND)
6409 continue;
6410
Richard Smithbdf2d932015-07-30 03:37:16 +00006411 if (ND->getDeclName() != Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006412 // A name might be null because the decl's redeclarable part is
6413 // currently read before reading its name. The lookup is triggered by
6414 // building that decl (likely indirectly), and so it is later in the
6415 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006416 // FIXME: This should not happen; deserializing declarations should
6417 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006418 continue;
6419 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006420
Guy Benyei11169dd2012-12-18 14:30:41 +00006421 // Record this declaration.
6422 FoundAnything = true;
Richard Smithbdf2d932015-07-30 03:37:16 +00006423 if (DeclSet.insert(ND).second)
6424 Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006425 }
6426
6427 return FoundAnything;
6428 }
6429 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006430}
Guy Benyei11169dd2012-12-18 14:30:41 +00006431
Richard Smith9ce12e32013-02-07 03:30:24 +00006432bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006433ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6434 DeclarationName Name) {
6435 assert(DC->hasExternalVisibleStorage() &&
6436 "DeclContext has no visible decls in storage");
6437 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006438 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006439
Richard Smith8c913ec2014-08-14 02:21:01 +00006440 Deserializing LookupResults(this);
6441
Guy Benyei11169dd2012-12-18 14:30:41 +00006442 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006443 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006444
Richard Smithf13c68d2015-08-06 21:05:21 +00006445 DeclContextNameLookupVisitor Visitor(*this, DC, Name, Decls, DeclSet);
Richard Smith8c913ec2014-08-14 02:21:01 +00006446
Richard Smithf13c68d2015-08-06 21:05:21 +00006447 // If we can definitively determine which module file to look into,
6448 // only look there. Otherwise, look in all module files.
6449 if (ModuleFile *Definitive = getDefinitiveModuleFileFor(DC, *this))
6450 Visitor(*Definitive);
6451 else
6452 ModuleMgr.visit(Visitor);
Richard Smithcd45dbc2014-04-19 03:48:30 +00006453
Guy Benyei11169dd2012-12-18 14:30:41 +00006454 ++NumVisibleDeclContextsRead;
6455 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006456 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006457}
6458
6459namespace {
6460 /// \brief ModuleFile visitor used to retrieve all visible names in a
6461 /// declaration context.
6462 class DeclContextAllNamesVisitor {
6463 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006464 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006465 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006466 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006467 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006468
6469 public:
6470 DeclContextAllNamesVisitor(ASTReader &Reader,
6471 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006472 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006473 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006474
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006475 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006476 // Check whether we have any visible declaration information for
6477 // this context in this module.
6478 ModuleFile::DeclContextInfosMap::iterator Info;
6479 bool FoundInfo = false;
Richard Smithbdf2d932015-07-30 03:37:16 +00006480 for (unsigned I = 0, N = Contexts.size(); I != N; ++I) {
6481 Info = M.DeclContextInfos.find(Contexts[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006482 if (Info != M.DeclContextInfos.end() &&
6483 Info->second.NameLookupTableData) {
6484 FoundInfo = true;
6485 break;
6486 }
6487 }
6488
6489 if (!FoundInfo)
6490 return false;
6491
Richard Smith52e3fba2014-03-11 07:17:35 +00006492 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006493 Info->second.NameLookupTableData;
6494 bool FoundAnything = false;
6495 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006496 I = LookupTable->data_begin(), E = LookupTable->data_end();
6497 I != E;
6498 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006499 ASTDeclContextNameLookupTrait::data_type Data = *I;
6500 for (; Data.first != Data.second; ++Data.first) {
Richard Smithbdf2d932015-07-30 03:37:16 +00006501 NamedDecl *ND = Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
Guy Benyei11169dd2012-12-18 14:30:41 +00006502 if (!ND)
6503 continue;
6504
6505 // Record this declaration.
6506 FoundAnything = true;
Richard Smithbdf2d932015-07-30 03:37:16 +00006507 if (DeclSet.insert(ND).second)
6508 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006509 }
6510 }
6511
Richard Smithbdf2d932015-07-30 03:37:16 +00006512 return FoundAnything && !VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006513 }
6514 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006515}
Guy Benyei11169dd2012-12-18 14:30:41 +00006516
6517void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6518 if (!DC->hasExternalVisibleStorage())
6519 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006520 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006521
6522 // Compute the declaration contexts we need to look into. Multiple such
6523 // declaration contexts occur when two declaration contexts from disjoint
6524 // modules get merged, e.g., when two namespaces with the same name are
6525 // independently defined in separate modules.
6526 SmallVector<const DeclContext *, 2> Contexts;
6527 Contexts.push_back(DC);
6528
6529 if (DC->isNamespace()) {
Richard Smith5fc18a92015-07-12 23:43:21 +00006530 KeyDeclsMap::iterator Key =
6531 KeyDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6532 if (Key != KeyDecls.end()) {
6533 for (unsigned I = 0, N = Key->second.size(); I != N; ++I)
6534 Contexts.push_back(cast<DeclContext>(GetDecl(Key->second[I])));
Guy Benyei11169dd2012-12-18 14:30:41 +00006535 }
6536 }
6537
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006538 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6539 /*VisitAll=*/DC->isFileContext());
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006540 ModuleMgr.visit(Visitor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006541 ++NumVisibleDeclContextsRead;
6542
Craig Topper79be4cd2013-07-05 04:33:53 +00006543 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006544 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6545 }
6546 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6547}
6548
6549/// \brief Under non-PCH compilation the consumer receives the objc methods
6550/// before receiving the implementation, and codegen depends on this.
6551/// We simulate this by deserializing and passing to consumer the methods of the
6552/// implementation before passing the deserialized implementation decl.
6553static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6554 ASTConsumer *Consumer) {
6555 assert(ImplD && Consumer);
6556
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006557 for (auto *I : ImplD->methods())
6558 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006559
6560 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6561}
6562
6563void ASTReader::PassInterestingDeclsToConsumer() {
6564 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006565
6566 if (PassingDeclsToConsumer)
6567 return;
6568
6569 // Guard variable to avoid recursively redoing the process of passing
6570 // decls to consumer.
6571 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6572 true);
6573
Richard Smith9e2341d2015-03-23 03:25:59 +00006574 // Ensure that we've loaded all potentially-interesting declarations
6575 // that need to be eagerly loaded.
6576 for (auto ID : EagerlyDeserializedDecls)
6577 GetDecl(ID);
6578 EagerlyDeserializedDecls.clear();
6579
Guy Benyei11169dd2012-12-18 14:30:41 +00006580 while (!InterestingDecls.empty()) {
6581 Decl *D = InterestingDecls.front();
6582 InterestingDecls.pop_front();
6583
6584 PassInterestingDeclToConsumer(D);
6585 }
6586}
6587
6588void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6589 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6590 PassObjCImplDeclToConsumer(ImplD, Consumer);
6591 else
6592 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6593}
6594
6595void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6596 this->Consumer = Consumer;
6597
Richard Smith9e2341d2015-03-23 03:25:59 +00006598 if (Consumer)
6599 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006600
6601 if (DeserializationListener)
6602 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006603}
6604
6605void ASTReader::PrintStats() {
6606 std::fprintf(stderr, "*** AST File Statistics:\n");
6607
6608 unsigned NumTypesLoaded
6609 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6610 QualType());
6611 unsigned NumDeclsLoaded
6612 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006613 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006614 unsigned NumIdentifiersLoaded
6615 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6616 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006617 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006618 unsigned NumMacrosLoaded
6619 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6620 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006621 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006622 unsigned NumSelectorsLoaded
6623 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6624 SelectorsLoaded.end(),
6625 Selector());
6626
6627 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6628 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6629 NumSLocEntriesRead, TotalNumSLocEntries,
6630 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6631 if (!TypesLoaded.empty())
6632 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6633 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6634 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6635 if (!DeclsLoaded.empty())
6636 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6637 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6638 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6639 if (!IdentifiersLoaded.empty())
6640 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6641 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6642 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6643 if (!MacrosLoaded.empty())
6644 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6645 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6646 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6647 if (!SelectorsLoaded.empty())
6648 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6649 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6650 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6651 if (TotalNumStatements)
6652 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6653 NumStatementsRead, TotalNumStatements,
6654 ((float)NumStatementsRead/TotalNumStatements * 100));
6655 if (TotalNumMacros)
6656 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6657 NumMacrosRead, TotalNumMacros,
6658 ((float)NumMacrosRead/TotalNumMacros * 100));
6659 if (TotalLexicalDeclContexts)
6660 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6661 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6662 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6663 * 100));
6664 if (TotalVisibleDeclContexts)
6665 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6666 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6667 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6668 * 100));
6669 if (TotalNumMethodPoolEntries) {
6670 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6671 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6672 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6673 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006674 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006675 if (NumMethodPoolLookups) {
6676 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6677 NumMethodPoolHits, NumMethodPoolLookups,
6678 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6679 }
6680 if (NumMethodPoolTableLookups) {
6681 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6682 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6683 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6684 * 100.0));
6685 }
6686
Douglas Gregor00a50f72013-01-25 00:38:33 +00006687 if (NumIdentifierLookupHits) {
6688 std::fprintf(stderr,
6689 " %u / %u identifier table lookups succeeded (%f%%)\n",
6690 NumIdentifierLookupHits, NumIdentifierLookups,
6691 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6692 }
6693
Douglas Gregore060e572013-01-25 01:03:03 +00006694 if (GlobalIndex) {
6695 std::fprintf(stderr, "\n");
6696 GlobalIndex->printStats();
6697 }
6698
Guy Benyei11169dd2012-12-18 14:30:41 +00006699 std::fprintf(stderr, "\n");
6700 dump();
6701 std::fprintf(stderr, "\n");
6702}
6703
6704template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6705static void
6706dumpModuleIDMap(StringRef Name,
6707 const ContinuousRangeMap<Key, ModuleFile *,
6708 InitialCapacity> &Map) {
6709 if (Map.begin() == Map.end())
6710 return;
6711
6712 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6713 llvm::errs() << Name << ":\n";
6714 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6715 I != IEnd; ++I) {
6716 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6717 << "\n";
6718 }
6719}
6720
6721void ASTReader::dump() {
6722 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6723 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6724 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6725 dumpModuleIDMap("Global type map", GlobalTypeMap);
6726 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6727 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6728 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6729 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6730 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6731 dumpModuleIDMap("Global preprocessed entity map",
6732 GlobalPreprocessedEntityMap);
6733
6734 llvm::errs() << "\n*** PCH/Modules Loaded:";
6735 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6736 MEnd = ModuleMgr.end();
6737 M != MEnd; ++M)
6738 (*M)->dump();
6739}
6740
6741/// Return the amount of memory used by memory buffers, breaking down
6742/// by heap-backed versus mmap'ed memory.
6743void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6744 for (ModuleConstIterator I = ModuleMgr.begin(),
6745 E = ModuleMgr.end(); I != E; ++I) {
6746 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6747 size_t bytes = buf->getBufferSize();
6748 switch (buf->getBufferKind()) {
6749 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6750 sizes.malloc_bytes += bytes;
6751 break;
6752 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6753 sizes.mmap_bytes += bytes;
6754 break;
6755 }
6756 }
6757 }
6758}
6759
6760void ASTReader::InitializeSema(Sema &S) {
6761 SemaObj = &S;
6762 S.addExternalSource(this);
6763
6764 // Makes sure any declarations that were deserialized "too early"
6765 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006766 for (uint64_t ID : PreloadedDeclIDs) {
6767 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6768 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006769 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006770 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006771
Richard Smith3d8e97e2013-10-18 06:54:39 +00006772 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006773 if (!FPPragmaOptions.empty()) {
6774 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6775 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6776 }
6777
Richard Smith3d8e97e2013-10-18 06:54:39 +00006778 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006779 if (!OpenCLExtensions.empty()) {
6780 unsigned I = 0;
6781#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6782#include "clang/Basic/OpenCLExtensions.def"
6783
6784 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6785 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006786
6787 UpdateSema();
6788}
6789
6790void ASTReader::UpdateSema() {
6791 assert(SemaObj && "no Sema to update");
6792
6793 // Load the offsets of the declarations that Sema references.
6794 // They will be lazily deserialized when needed.
6795 if (!SemaDeclRefs.empty()) {
6796 assert(SemaDeclRefs.size() % 2 == 0);
6797 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6798 if (!SemaObj->StdNamespace)
6799 SemaObj->StdNamespace = SemaDeclRefs[I];
6800 if (!SemaObj->StdBadAlloc)
6801 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6802 }
6803 SemaDeclRefs.clear();
6804 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006805
6806 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6807 // encountered the pragma in the source.
6808 if(OptimizeOffPragmaLocation.isValid())
6809 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006810}
6811
Richard Smitha8d5b6a2015-07-17 19:51:03 +00006812IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006813 // Note that we are loading an identifier.
6814 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006815
Douglas Gregor7211ac12013-01-25 23:32:03 +00006816 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006817 NumIdentifierLookups,
6818 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006819
6820 // We don't need to do identifier table lookups in C++ modules (we preload
6821 // all interesting declarations, and don't need to use the scope for name
6822 // lookups). Perform the lookup in PCH files, though, since we don't build
6823 // a complete initial identifier table if we're carrying on from a PCH.
6824 if (Context.getLangOpts().CPlusPlus) {
6825 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006826 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00006827 break;
6828 } else {
6829 // If there is a global index, look there first to determine which modules
6830 // provably do not have any results for this identifier.
6831 GlobalModuleIndex::HitSet Hits;
6832 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
6833 if (!loadGlobalIndex()) {
6834 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6835 HitsPtr = &Hits;
6836 }
6837 }
6838
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006839 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006840 }
6841
Guy Benyei11169dd2012-12-18 14:30:41 +00006842 IdentifierInfo *II = Visitor.getIdentifierInfo();
6843 markIdentifierUpToDate(II);
6844 return II;
6845}
6846
6847namespace clang {
6848 /// \brief An identifier-lookup iterator that enumerates all of the
6849 /// identifiers stored within a set of AST files.
6850 class ASTIdentifierIterator : public IdentifierIterator {
6851 /// \brief The AST reader whose identifiers are being enumerated.
6852 const ASTReader &Reader;
6853
6854 /// \brief The current index into the chain of AST files stored in
6855 /// the AST reader.
6856 unsigned Index;
6857
6858 /// \brief The current position within the identifier lookup table
6859 /// of the current AST file.
6860 ASTIdentifierLookupTable::key_iterator Current;
6861
6862 /// \brief The end position within the identifier lookup table of
6863 /// the current AST file.
6864 ASTIdentifierLookupTable::key_iterator End;
6865
6866 public:
6867 explicit ASTIdentifierIterator(const ASTReader &Reader);
6868
Craig Topper3e89dfe2014-03-13 02:13:41 +00006869 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006870 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006871}
Guy Benyei11169dd2012-12-18 14:30:41 +00006872
6873ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6874 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6875 ASTIdentifierLookupTable *IdTable
6876 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6877 Current = IdTable->key_begin();
6878 End = IdTable->key_end();
6879}
6880
6881StringRef ASTIdentifierIterator::Next() {
6882 while (Current == End) {
6883 // If we have exhausted all of our AST files, we're done.
6884 if (Index == 0)
6885 return StringRef();
6886
6887 --Index;
6888 ASTIdentifierLookupTable *IdTable
6889 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6890 IdentifierLookupTable;
6891 Current = IdTable->key_begin();
6892 End = IdTable->key_end();
6893 }
6894
6895 // We have any identifiers remaining in the current AST file; return
6896 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006897 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006898 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006899 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006900}
6901
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006902IdentifierIterator *ASTReader::getIdentifiers() {
6903 if (!loadGlobalIndex())
6904 return GlobalIndex->createIdentifierIterator();
6905
Guy Benyei11169dd2012-12-18 14:30:41 +00006906 return new ASTIdentifierIterator(*this);
6907}
6908
6909namespace clang { namespace serialization {
6910 class ReadMethodPoolVisitor {
6911 ASTReader &Reader;
6912 Selector Sel;
6913 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006914 unsigned InstanceBits;
6915 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006916 bool InstanceHasMoreThanOneDecl;
6917 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006918 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6919 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006920
6921 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00006922 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00006923 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00006924 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00006925 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
6926 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00006927
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006928 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006929 if (!M.SelectorLookupTable)
6930 return false;
6931
6932 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00006933 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00006934 return true;
6935
Richard Smithbdf2d932015-07-30 03:37:16 +00006936 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006937 ASTSelectorLookupTable *PoolTable
6938 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00006939 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00006940 if (Pos == PoolTable->end())
6941 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006942
Richard Smithbdf2d932015-07-30 03:37:16 +00006943 ++Reader.NumMethodPoolTableHits;
6944 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006945 // FIXME: Not quite happy with the statistics here. We probably should
6946 // disable this tracking when called via LoadSelector.
6947 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00006948 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006949 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00006950 if (Reader.DeserializationListener)
6951 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006952
Richard Smithbdf2d932015-07-30 03:37:16 +00006953 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6954 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
6955 InstanceBits = Data.InstanceBits;
6956 FactoryBits = Data.FactoryBits;
6957 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
6958 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00006959 return true;
6960 }
6961
6962 /// \brief Retrieve the instance methods found by this visitor.
6963 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6964 return InstanceMethods;
6965 }
6966
6967 /// \brief Retrieve the instance methods found by this visitor.
6968 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6969 return FactoryMethods;
6970 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006971
6972 unsigned getInstanceBits() const { return InstanceBits; }
6973 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00006974 bool instanceHasMoreThanOneDecl() const {
6975 return InstanceHasMoreThanOneDecl;
6976 }
6977 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006978 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006979} } // end namespace clang::serialization
Guy Benyei11169dd2012-12-18 14:30:41 +00006980
6981/// \brief Add the given set of methods to the method list.
6982static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6983 ObjCMethodList &List) {
6984 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6985 S.addMethodToGlobalList(&List, Methods[I]);
6986 }
6987}
6988
6989void ASTReader::ReadMethodPool(Selector Sel) {
6990 // Get the selector generation and update it to the current generation.
6991 unsigned &Generation = SelectorGeneration[Sel];
6992 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00006993 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00006994
6995 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006996 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006997 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006998 ModuleMgr.visit(Visitor);
6999
Guy Benyei11169dd2012-12-18 14:30:41 +00007000 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007001 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007002 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007003
7004 ++NumMethodPoolHits;
7005
Guy Benyei11169dd2012-12-18 14:30:41 +00007006 if (!getSema())
7007 return;
7008
7009 Sema &S = *getSema();
7010 Sema::GlobalMethodPool::iterator Pos
7011 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007012
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007013 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007014 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007015 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007016 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007017
7018 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7019 // when building a module we keep every method individually and may need to
7020 // update hasMoreThanOneDecl as we add the methods.
7021 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7022 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007023}
7024
7025void ASTReader::ReadKnownNamespaces(
7026 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7027 Namespaces.clear();
7028
7029 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7030 if (NamespaceDecl *Namespace
7031 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7032 Namespaces.push_back(Namespace);
7033 }
7034}
7035
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007036void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007037 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007038 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7039 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007040 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007041 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007042 Undefined.insert(std::make_pair(D, Loc));
7043 }
7044}
Nick Lewycky8334af82013-01-26 00:35:08 +00007045
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007046void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7047 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7048 Exprs) {
7049 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7050 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7051 uint64_t Count = DelayedDeleteExprs[Idx++];
7052 for (uint64_t C = 0; C < Count; ++C) {
7053 SourceLocation DeleteLoc =
7054 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7055 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7056 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7057 }
7058 }
7059}
7060
Guy Benyei11169dd2012-12-18 14:30:41 +00007061void ASTReader::ReadTentativeDefinitions(
7062 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7063 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7064 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7065 if (Var)
7066 TentativeDefs.push_back(Var);
7067 }
7068 TentativeDefinitions.clear();
7069}
7070
7071void ASTReader::ReadUnusedFileScopedDecls(
7072 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7073 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7074 DeclaratorDecl *D
7075 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7076 if (D)
7077 Decls.push_back(D);
7078 }
7079 UnusedFileScopedDecls.clear();
7080}
7081
7082void ASTReader::ReadDelegatingConstructors(
7083 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7084 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7085 CXXConstructorDecl *D
7086 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7087 if (D)
7088 Decls.push_back(D);
7089 }
7090 DelegatingCtorDecls.clear();
7091}
7092
7093void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7094 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7095 TypedefNameDecl *D
7096 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7097 if (D)
7098 Decls.push_back(D);
7099 }
7100 ExtVectorDecls.clear();
7101}
7102
Nico Weber72889432014-09-06 01:25:55 +00007103void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7104 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7105 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7106 ++I) {
7107 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7108 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7109 if (D)
7110 Decls.insert(D);
7111 }
7112 UnusedLocalTypedefNameCandidates.clear();
7113}
7114
Guy Benyei11169dd2012-12-18 14:30:41 +00007115void ASTReader::ReadReferencedSelectors(
7116 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7117 if (ReferencedSelectorsData.empty())
7118 return;
7119
7120 // If there are @selector references added them to its pool. This is for
7121 // implementation of -Wselector.
7122 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7123 unsigned I = 0;
7124 while (I < DataSize) {
7125 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7126 SourceLocation SelLoc
7127 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7128 Sels.push_back(std::make_pair(Sel, SelLoc));
7129 }
7130 ReferencedSelectorsData.clear();
7131}
7132
7133void ASTReader::ReadWeakUndeclaredIdentifiers(
7134 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7135 if (WeakUndeclaredIdentifiers.empty())
7136 return;
7137
7138 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7139 IdentifierInfo *WeakId
7140 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7141 IdentifierInfo *AliasId
7142 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7143 SourceLocation Loc
7144 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7145 bool Used = WeakUndeclaredIdentifiers[I++];
7146 WeakInfo WI(AliasId, Loc);
7147 WI.setUsed(Used);
7148 WeakIDs.push_back(std::make_pair(WeakId, WI));
7149 }
7150 WeakUndeclaredIdentifiers.clear();
7151}
7152
7153void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7154 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7155 ExternalVTableUse VT;
7156 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7157 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7158 VT.DefinitionRequired = VTableUses[Idx++];
7159 VTables.push_back(VT);
7160 }
7161
7162 VTableUses.clear();
7163}
7164
7165void ASTReader::ReadPendingInstantiations(
7166 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7167 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7168 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7169 SourceLocation Loc
7170 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7171
7172 Pending.push_back(std::make_pair(D, Loc));
7173 }
7174 PendingInstantiations.clear();
7175}
7176
Richard Smithe40f2ba2013-08-07 21:41:30 +00007177void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007178 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007179 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7180 /* In loop */) {
7181 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7182
7183 LateParsedTemplate *LT = new LateParsedTemplate;
7184 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7185
7186 ModuleFile *F = getOwningModuleFile(LT->D);
7187 assert(F && "No module");
7188
7189 unsigned TokN = LateParsedTemplates[Idx++];
7190 LT->Toks.reserve(TokN);
7191 for (unsigned T = 0; T < TokN; ++T)
7192 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7193
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007194 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007195 }
7196
7197 LateParsedTemplates.clear();
7198}
7199
Guy Benyei11169dd2012-12-18 14:30:41 +00007200void ASTReader::LoadSelector(Selector Sel) {
7201 // It would be complicated to avoid reading the methods anyway. So don't.
7202 ReadMethodPool(Sel);
7203}
7204
7205void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7206 assert(ID && "Non-zero identifier ID required");
7207 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7208 IdentifiersLoaded[ID - 1] = II;
7209 if (DeserializationListener)
7210 DeserializationListener->IdentifierRead(ID, II);
7211}
7212
7213/// \brief Set the globally-visible declarations associated with the given
7214/// identifier.
7215///
7216/// If the AST reader is currently in a state where the given declaration IDs
7217/// cannot safely be resolved, they are queued until it is safe to resolve
7218/// them.
7219///
7220/// \param II an IdentifierInfo that refers to one or more globally-visible
7221/// declarations.
7222///
7223/// \param DeclIDs the set of declaration IDs with the name @p II that are
7224/// visible at global scope.
7225///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007226/// \param Decls if non-null, this vector will be populated with the set of
7227/// deserialized declarations. These declarations will not be pushed into
7228/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007229void
7230ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7231 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007232 SmallVectorImpl<Decl *> *Decls) {
7233 if (NumCurrentElementsDeserializing && !Decls) {
7234 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007235 return;
7236 }
7237
7238 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007239 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007240 // Queue this declaration so that it will be added to the
7241 // translation unit scope and identifier's declaration chain
7242 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007243 PreloadedDeclIDs.push_back(DeclIDs[I]);
7244 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007245 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007246
7247 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7248
7249 // If we're simply supposed to record the declarations, do so now.
7250 if (Decls) {
7251 Decls->push_back(D);
7252 continue;
7253 }
7254
7255 // Introduce this declaration into the translation-unit scope
7256 // and add it to the declaration chain for this identifier, so
7257 // that (unqualified) name lookup will find it.
7258 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007259 }
7260}
7261
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007262IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007263 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007264 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007265
7266 if (IdentifiersLoaded.empty()) {
7267 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007268 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007269 }
7270
7271 ID -= 1;
7272 if (!IdentifiersLoaded[ID]) {
7273 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7274 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7275 ModuleFile *M = I->second;
7276 unsigned Index = ID - M->BaseIdentifierID;
7277 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7278
7279 // All of the strings in the AST file are preceded by a 16-bit length.
7280 // Extract that 16-bit length to avoid having to execute strlen().
7281 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7282 // unsigned integers. This is important to avoid integer overflow when
7283 // we cast them to 'unsigned'.
7284 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7285 unsigned StrLen = (((unsigned) StrLenPtr[0])
7286 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007287 IdentifiersLoaded[ID]
7288 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007289 if (DeserializationListener)
7290 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7291 }
7292
7293 return IdentifiersLoaded[ID];
7294}
7295
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007296IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7297 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007298}
7299
7300IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7301 if (LocalID < NUM_PREDEF_IDENT_IDS)
7302 return LocalID;
7303
7304 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7305 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7306 assert(I != M.IdentifierRemap.end()
7307 && "Invalid index into identifier index remap");
7308
7309 return LocalID + I->second;
7310}
7311
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007312MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007313 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007314 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007315
7316 if (MacrosLoaded.empty()) {
7317 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007318 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007319 }
7320
7321 ID -= NUM_PREDEF_MACRO_IDS;
7322 if (!MacrosLoaded[ID]) {
7323 GlobalMacroMapType::iterator I
7324 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7325 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7326 ModuleFile *M = I->second;
7327 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007328 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7329
7330 if (DeserializationListener)
7331 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7332 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007333 }
7334
7335 return MacrosLoaded[ID];
7336}
7337
7338MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7339 if (LocalID < NUM_PREDEF_MACRO_IDS)
7340 return LocalID;
7341
7342 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7343 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7344 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7345
7346 return LocalID + I->second;
7347}
7348
7349serialization::SubmoduleID
7350ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7351 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7352 return LocalID;
7353
7354 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7355 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7356 assert(I != M.SubmoduleRemap.end()
7357 && "Invalid index into submodule index remap");
7358
7359 return LocalID + I->second;
7360}
7361
7362Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7363 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7364 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007365 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007366 }
7367
7368 if (GlobalID > SubmodulesLoaded.size()) {
7369 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007370 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007371 }
7372
7373 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7374}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007375
7376Module *ASTReader::getModule(unsigned ID) {
7377 return getSubmodule(ID);
7378}
7379
Adrian Prantl15bcf702015-06-30 17:39:43 +00007380ExternalASTSource::ASTSourceDescriptor
7381ASTReader::getSourceDescriptor(const Module &M) {
7382 StringRef Dir, Filename;
7383 if (M.Directory)
7384 Dir = M.Directory->getName();
7385 if (auto *File = M.getASTFile())
7386 Filename = File->getName();
7387 return ASTReader::ASTSourceDescriptor{
7388 M.getFullModuleName(), Dir, Filename,
7389 M.Signature
7390 };
7391}
7392
7393llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7394ASTReader::getSourceDescriptor(unsigned ID) {
7395 if (const Module *M = getSubmodule(ID))
7396 return getSourceDescriptor(*M);
7397
7398 // If there is only a single PCH, return it instead.
7399 // Chained PCH are not suported.
7400 if (ModuleMgr.size() == 1) {
7401 ModuleFile &MF = ModuleMgr.getPrimaryModule();
7402 return ASTReader::ASTSourceDescriptor{
7403 MF.OriginalSourceFileName, MF.OriginalDir,
7404 MF.FileName,
7405 MF.Signature
7406 };
7407 }
7408 return None;
7409}
7410
Guy Benyei11169dd2012-12-18 14:30:41 +00007411Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7412 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7413}
7414
7415Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7416 if (ID == 0)
7417 return Selector();
7418
7419 if (ID > SelectorsLoaded.size()) {
7420 Error("selector ID out of range in AST file");
7421 return Selector();
7422 }
7423
Craig Toppera13603a2014-05-22 05:54:18 +00007424 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007425 // Load this selector from the selector table.
7426 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7427 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7428 ModuleFile &M = *I->second;
7429 ASTSelectorLookupTrait Trait(*this, M);
7430 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7431 SelectorsLoaded[ID - 1] =
7432 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7433 if (DeserializationListener)
7434 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7435 }
7436
7437 return SelectorsLoaded[ID - 1];
7438}
7439
7440Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7441 return DecodeSelector(ID);
7442}
7443
7444uint32_t ASTReader::GetNumExternalSelectors() {
7445 // ID 0 (the null selector) is considered an external selector.
7446 return getTotalNumSelectors() + 1;
7447}
7448
7449serialization::SelectorID
7450ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7451 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7452 return LocalID;
7453
7454 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7455 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7456 assert(I != M.SelectorRemap.end()
7457 && "Invalid index into selector index remap");
7458
7459 return LocalID + I->second;
7460}
7461
7462DeclarationName
7463ASTReader::ReadDeclarationName(ModuleFile &F,
7464 const RecordData &Record, unsigned &Idx) {
7465 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7466 switch (Kind) {
7467 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007468 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007469
7470 case DeclarationName::ObjCZeroArgSelector:
7471 case DeclarationName::ObjCOneArgSelector:
7472 case DeclarationName::ObjCMultiArgSelector:
7473 return DeclarationName(ReadSelector(F, Record, Idx));
7474
7475 case DeclarationName::CXXConstructorName:
7476 return Context.DeclarationNames.getCXXConstructorName(
7477 Context.getCanonicalType(readType(F, Record, Idx)));
7478
7479 case DeclarationName::CXXDestructorName:
7480 return Context.DeclarationNames.getCXXDestructorName(
7481 Context.getCanonicalType(readType(F, Record, Idx)));
7482
7483 case DeclarationName::CXXConversionFunctionName:
7484 return Context.DeclarationNames.getCXXConversionFunctionName(
7485 Context.getCanonicalType(readType(F, Record, Idx)));
7486
7487 case DeclarationName::CXXOperatorName:
7488 return Context.DeclarationNames.getCXXOperatorName(
7489 (OverloadedOperatorKind)Record[Idx++]);
7490
7491 case DeclarationName::CXXLiteralOperatorName:
7492 return Context.DeclarationNames.getCXXLiteralOperatorName(
7493 GetIdentifierInfo(F, Record, Idx));
7494
7495 case DeclarationName::CXXUsingDirective:
7496 return DeclarationName::getUsingDirectiveName();
7497 }
7498
7499 llvm_unreachable("Invalid NameKind!");
7500}
7501
7502void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7503 DeclarationNameLoc &DNLoc,
7504 DeclarationName Name,
7505 const RecordData &Record, unsigned &Idx) {
7506 switch (Name.getNameKind()) {
7507 case DeclarationName::CXXConstructorName:
7508 case DeclarationName::CXXDestructorName:
7509 case DeclarationName::CXXConversionFunctionName:
7510 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7511 break;
7512
7513 case DeclarationName::CXXOperatorName:
7514 DNLoc.CXXOperatorName.BeginOpNameLoc
7515 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7516 DNLoc.CXXOperatorName.EndOpNameLoc
7517 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7518 break;
7519
7520 case DeclarationName::CXXLiteralOperatorName:
7521 DNLoc.CXXLiteralOperatorName.OpNameLoc
7522 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7523 break;
7524
7525 case DeclarationName::Identifier:
7526 case DeclarationName::ObjCZeroArgSelector:
7527 case DeclarationName::ObjCOneArgSelector:
7528 case DeclarationName::ObjCMultiArgSelector:
7529 case DeclarationName::CXXUsingDirective:
7530 break;
7531 }
7532}
7533
7534void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7535 DeclarationNameInfo &NameInfo,
7536 const RecordData &Record, unsigned &Idx) {
7537 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7538 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7539 DeclarationNameLoc DNLoc;
7540 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7541 NameInfo.setInfo(DNLoc);
7542}
7543
7544void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7545 const RecordData &Record, unsigned &Idx) {
7546 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7547 unsigned NumTPLists = Record[Idx++];
7548 Info.NumTemplParamLists = NumTPLists;
7549 if (NumTPLists) {
7550 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7551 for (unsigned i=0; i != NumTPLists; ++i)
7552 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7553 }
7554}
7555
7556TemplateName
7557ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7558 unsigned &Idx) {
7559 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7560 switch (Kind) {
7561 case TemplateName::Template:
7562 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7563
7564 case TemplateName::OverloadedTemplate: {
7565 unsigned size = Record[Idx++];
7566 UnresolvedSet<8> Decls;
7567 while (size--)
7568 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7569
7570 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7571 }
7572
7573 case TemplateName::QualifiedTemplate: {
7574 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7575 bool hasTemplKeyword = Record[Idx++];
7576 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7577 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7578 }
7579
7580 case TemplateName::DependentTemplate: {
7581 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7582 if (Record[Idx++]) // isIdentifier
7583 return Context.getDependentTemplateName(NNS,
7584 GetIdentifierInfo(F, Record,
7585 Idx));
7586 return Context.getDependentTemplateName(NNS,
7587 (OverloadedOperatorKind)Record[Idx++]);
7588 }
7589
7590 case TemplateName::SubstTemplateTemplateParm: {
7591 TemplateTemplateParmDecl *param
7592 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7593 if (!param) return TemplateName();
7594 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7595 return Context.getSubstTemplateTemplateParm(param, replacement);
7596 }
7597
7598 case TemplateName::SubstTemplateTemplateParmPack: {
7599 TemplateTemplateParmDecl *Param
7600 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7601 if (!Param)
7602 return TemplateName();
7603
7604 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7605 if (ArgPack.getKind() != TemplateArgument::Pack)
7606 return TemplateName();
7607
7608 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7609 }
7610 }
7611
7612 llvm_unreachable("Unhandled template name kind!");
7613}
7614
Richard Smith2bb3c342015-08-09 01:05:31 +00007615TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
7616 const RecordData &Record,
7617 unsigned &Idx,
7618 bool Canonicalize) {
7619 if (Canonicalize) {
7620 // The caller wants a canonical template argument. Sometimes the AST only
7621 // wants template arguments in canonical form (particularly as the template
7622 // argument lists of template specializations) so ensure we preserve that
7623 // canonical form across serialization.
7624 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
7625 return Context.getCanonicalTemplateArgument(Arg);
7626 }
7627
Guy Benyei11169dd2012-12-18 14:30:41 +00007628 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7629 switch (Kind) {
7630 case TemplateArgument::Null:
7631 return TemplateArgument();
7632 case TemplateArgument::Type:
7633 return TemplateArgument(readType(F, Record, Idx));
7634 case TemplateArgument::Declaration: {
7635 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007636 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007637 }
7638 case TemplateArgument::NullPtr:
7639 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7640 case TemplateArgument::Integral: {
7641 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7642 QualType T = readType(F, Record, Idx);
7643 return TemplateArgument(Context, Value, T);
7644 }
7645 case TemplateArgument::Template:
7646 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7647 case TemplateArgument::TemplateExpansion: {
7648 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007649 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007650 if (unsigned NumExpansions = Record[Idx++])
7651 NumTemplateExpansions = NumExpansions - 1;
7652 return TemplateArgument(Name, NumTemplateExpansions);
7653 }
7654 case TemplateArgument::Expression:
7655 return TemplateArgument(ReadExpr(F));
7656 case TemplateArgument::Pack: {
7657 unsigned NumArgs = Record[Idx++];
7658 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7659 for (unsigned I = 0; I != NumArgs; ++I)
7660 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00007661 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00007662 }
7663 }
7664
7665 llvm_unreachable("Unhandled template argument kind!");
7666}
7667
7668TemplateParameterList *
7669ASTReader::ReadTemplateParameterList(ModuleFile &F,
7670 const RecordData &Record, unsigned &Idx) {
7671 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7672 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7673 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7674
7675 unsigned NumParams = Record[Idx++];
7676 SmallVector<NamedDecl *, 16> Params;
7677 Params.reserve(NumParams);
7678 while (NumParams--)
7679 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7680
7681 TemplateParameterList* TemplateParams =
7682 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7683 Params.data(), Params.size(), RAngleLoc);
7684 return TemplateParams;
7685}
7686
7687void
7688ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007689ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007690 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00007691 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007692 unsigned NumTemplateArgs = Record[Idx++];
7693 TemplArgs.reserve(NumTemplateArgs);
7694 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00007695 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00007696}
7697
7698/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007699void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007700 const RecordData &Record, unsigned &Idx) {
7701 unsigned NumDecls = Record[Idx++];
7702 Set.reserve(Context, NumDecls);
7703 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007704 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007705 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007706 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007707 }
7708}
7709
7710CXXBaseSpecifier
7711ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7712 const RecordData &Record, unsigned &Idx) {
7713 bool isVirtual = static_cast<bool>(Record[Idx++]);
7714 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7715 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7716 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7717 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7718 SourceRange Range = ReadSourceRange(F, Record, Idx);
7719 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7720 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7721 EllipsisLoc);
7722 Result.setInheritConstructors(inheritConstructors);
7723 return Result;
7724}
7725
Richard Smithc2bb8182015-03-24 06:36:48 +00007726CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007727ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7728 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007729 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007730 assert(NumInitializers && "wrote ctor initializers but have no inits");
7731 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7732 for (unsigned i = 0; i != NumInitializers; ++i) {
7733 TypeSourceInfo *TInfo = nullptr;
7734 bool IsBaseVirtual = false;
7735 FieldDecl *Member = nullptr;
7736 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007737
Richard Smithc2bb8182015-03-24 06:36:48 +00007738 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7739 switch (Type) {
7740 case CTOR_INITIALIZER_BASE:
7741 TInfo = GetTypeSourceInfo(F, Record, Idx);
7742 IsBaseVirtual = Record[Idx++];
7743 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007744
Richard Smithc2bb8182015-03-24 06:36:48 +00007745 case CTOR_INITIALIZER_DELEGATING:
7746 TInfo = GetTypeSourceInfo(F, Record, Idx);
7747 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007748
Richard Smithc2bb8182015-03-24 06:36:48 +00007749 case CTOR_INITIALIZER_MEMBER:
7750 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7751 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007752
Richard Smithc2bb8182015-03-24 06:36:48 +00007753 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7754 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7755 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007756 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007757
7758 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7759 Expr *Init = ReadExpr(F);
7760 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7761 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7762 bool IsWritten = Record[Idx++];
7763 unsigned SourceOrderOrNumArrayIndices;
7764 SmallVector<VarDecl *, 8> Indices;
7765 if (IsWritten) {
7766 SourceOrderOrNumArrayIndices = Record[Idx++];
7767 } else {
7768 SourceOrderOrNumArrayIndices = Record[Idx++];
7769 Indices.reserve(SourceOrderOrNumArrayIndices);
7770 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7771 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7772 }
7773
7774 CXXCtorInitializer *BOMInit;
7775 if (Type == CTOR_INITIALIZER_BASE) {
7776 BOMInit = new (Context)
7777 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7778 RParenLoc, MemberOrEllipsisLoc);
7779 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7780 BOMInit = new (Context)
7781 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7782 } else if (IsWritten) {
7783 if (Member)
7784 BOMInit = new (Context) CXXCtorInitializer(
7785 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7786 else
7787 BOMInit = new (Context)
7788 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7789 LParenLoc, Init, RParenLoc);
7790 } else {
7791 if (IndirectMember) {
7792 assert(Indices.empty() && "Indirect field improperly initialized");
7793 BOMInit = new (Context)
7794 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7795 LParenLoc, Init, RParenLoc);
7796 } else {
7797 BOMInit = CXXCtorInitializer::Create(
7798 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7799 Indices.data(), Indices.size());
7800 }
7801 }
7802
7803 if (IsWritten)
7804 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7805 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007806 }
7807
Richard Smithc2bb8182015-03-24 06:36:48 +00007808 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007809}
7810
7811NestedNameSpecifier *
7812ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7813 const RecordData &Record, unsigned &Idx) {
7814 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007815 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007816 for (unsigned I = 0; I != N; ++I) {
7817 NestedNameSpecifier::SpecifierKind Kind
7818 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7819 switch (Kind) {
7820 case NestedNameSpecifier::Identifier: {
7821 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7822 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7823 break;
7824 }
7825
7826 case NestedNameSpecifier::Namespace: {
7827 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7828 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7829 break;
7830 }
7831
7832 case NestedNameSpecifier::NamespaceAlias: {
7833 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7834 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7835 break;
7836 }
7837
7838 case NestedNameSpecifier::TypeSpec:
7839 case NestedNameSpecifier::TypeSpecWithTemplate: {
7840 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7841 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007842 return nullptr;
7843
Guy Benyei11169dd2012-12-18 14:30:41 +00007844 bool Template = Record[Idx++];
7845 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7846 break;
7847 }
7848
7849 case NestedNameSpecifier::Global: {
7850 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7851 // No associated value, and there can't be a prefix.
7852 break;
7853 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007854
7855 case NestedNameSpecifier::Super: {
7856 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7857 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7858 break;
7859 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007860 }
7861 Prev = NNS;
7862 }
7863 return NNS;
7864}
7865
7866NestedNameSpecifierLoc
7867ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7868 unsigned &Idx) {
7869 unsigned N = Record[Idx++];
7870 NestedNameSpecifierLocBuilder Builder;
7871 for (unsigned I = 0; I != N; ++I) {
7872 NestedNameSpecifier::SpecifierKind Kind
7873 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7874 switch (Kind) {
7875 case NestedNameSpecifier::Identifier: {
7876 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7877 SourceRange Range = ReadSourceRange(F, Record, Idx);
7878 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7879 break;
7880 }
7881
7882 case NestedNameSpecifier::Namespace: {
7883 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7884 SourceRange Range = ReadSourceRange(F, Record, Idx);
7885 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7886 break;
7887 }
7888
7889 case NestedNameSpecifier::NamespaceAlias: {
7890 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7891 SourceRange Range = ReadSourceRange(F, Record, Idx);
7892 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7893 break;
7894 }
7895
7896 case NestedNameSpecifier::TypeSpec:
7897 case NestedNameSpecifier::TypeSpecWithTemplate: {
7898 bool Template = Record[Idx++];
7899 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7900 if (!T)
7901 return NestedNameSpecifierLoc();
7902 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7903
7904 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7905 Builder.Extend(Context,
7906 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7907 T->getTypeLoc(), ColonColonLoc);
7908 break;
7909 }
7910
7911 case NestedNameSpecifier::Global: {
7912 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7913 Builder.MakeGlobal(Context, ColonColonLoc);
7914 break;
7915 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007916
7917 case NestedNameSpecifier::Super: {
7918 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7919 SourceRange Range = ReadSourceRange(F, Record, Idx);
7920 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
7921 break;
7922 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007923 }
7924 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007925
Guy Benyei11169dd2012-12-18 14:30:41 +00007926 return Builder.getWithLocInContext(Context);
7927}
7928
7929SourceRange
7930ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7931 unsigned &Idx) {
7932 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7933 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7934 return SourceRange(beg, end);
7935}
7936
7937/// \brief Read an integral value
7938llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7939 unsigned BitWidth = Record[Idx++];
7940 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7941 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7942 Idx += NumWords;
7943 return Result;
7944}
7945
7946/// \brief Read a signed integral value
7947llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7948 bool isUnsigned = Record[Idx++];
7949 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7950}
7951
7952/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007953llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7954 const llvm::fltSemantics &Sem,
7955 unsigned &Idx) {
7956 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007957}
7958
7959// \brief Read a string
7960std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7961 unsigned Len = Record[Idx++];
7962 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7963 Idx += Len;
7964 return Result;
7965}
7966
Richard Smith7ed1bc92014-12-05 22:42:13 +00007967std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
7968 unsigned &Idx) {
7969 std::string Filename = ReadString(Record, Idx);
7970 ResolveImportedPath(F, Filename);
7971 return Filename;
7972}
7973
Guy Benyei11169dd2012-12-18 14:30:41 +00007974VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7975 unsigned &Idx) {
7976 unsigned Major = Record[Idx++];
7977 unsigned Minor = Record[Idx++];
7978 unsigned Subminor = Record[Idx++];
7979 if (Minor == 0)
7980 return VersionTuple(Major);
7981 if (Subminor == 0)
7982 return VersionTuple(Major, Minor - 1);
7983 return VersionTuple(Major, Minor - 1, Subminor - 1);
7984}
7985
7986CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7987 const RecordData &Record,
7988 unsigned &Idx) {
7989 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7990 return CXXTemporary::Create(Context, Decl);
7991}
7992
7993DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007994 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007995}
7996
7997DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7998 return Diags.Report(Loc, DiagID);
7999}
8000
8001/// \brief Retrieve the identifier table associated with the
8002/// preprocessor.
8003IdentifierTable &ASTReader::getIdentifierTable() {
8004 return PP.getIdentifierTable();
8005}
8006
8007/// \brief Record that the given ID maps to the given switch-case
8008/// statement.
8009void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008010 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008011 "Already have a SwitchCase with this ID");
8012 (*CurrSwitchCaseStmts)[ID] = SC;
8013}
8014
8015/// \brief Retrieve the switch-case statement with the given ID.
8016SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008017 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008018 return (*CurrSwitchCaseStmts)[ID];
8019}
8020
8021void ASTReader::ClearSwitchCaseIDs() {
8022 CurrSwitchCaseStmts->clear();
8023}
8024
8025void ASTReader::ReadComments() {
8026 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008027 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008028 serialization::ModuleFile *> >::iterator
8029 I = CommentsCursors.begin(),
8030 E = CommentsCursors.end();
8031 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008032 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008033 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008034 serialization::ModuleFile &F = *I->second;
8035 SavedStreamPosition SavedPosition(Cursor);
8036
8037 RecordData Record;
8038 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008039 llvm::BitstreamEntry Entry =
8040 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008041
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008042 switch (Entry.Kind) {
8043 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8044 case llvm::BitstreamEntry::Error:
8045 Error("malformed block record in AST file");
8046 return;
8047 case llvm::BitstreamEntry::EndBlock:
8048 goto NextCursor;
8049 case llvm::BitstreamEntry::Record:
8050 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008051 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008052 }
8053
8054 // Read a record.
8055 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008056 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008057 case COMMENTS_RAW_COMMENT: {
8058 unsigned Idx = 0;
8059 SourceRange SR = ReadSourceRange(F, Record, Idx);
8060 RawComment::CommentKind Kind =
8061 (RawComment::CommentKind) Record[Idx++];
8062 bool IsTrailingComment = Record[Idx++];
8063 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008064 Comments.push_back(new (Context) RawComment(
8065 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8066 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008067 break;
8068 }
8069 }
8070 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008071 NextCursor:
8072 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008073 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008074}
8075
Richard Smithcd45dbc2014-04-19 03:48:30 +00008076std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8077 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008078 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008079 return M->getFullModuleName();
8080
8081 // Otherwise, use the name of the top-level module the decl is within.
8082 if (ModuleFile *M = getOwningModuleFile(D))
8083 return M->ModuleName;
8084
8085 // Not from a module.
8086 return "";
8087}
8088
Guy Benyei11169dd2012-12-18 14:30:41 +00008089void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008090 while (!PendingIdentifierInfos.empty() ||
8091 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008092 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008093 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008094 // If any identifiers with corresponding top-level declarations have
8095 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008096 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8097 TopLevelDeclsMap;
8098 TopLevelDeclsMap TopLevelDecls;
8099
Guy Benyei11169dd2012-12-18 14:30:41 +00008100 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008101 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008102 SmallVector<uint32_t, 4> DeclIDs =
8103 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008104 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008105
8106 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008107 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008108
Richard Smith851072e2014-05-19 20:59:20 +00008109 // For each decl chain that we wanted to complete while deserializing, mark
8110 // it as "still needs to be completed".
8111 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8112 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8113 }
8114 PendingIncompleteDeclChains.clear();
8115
Guy Benyei11169dd2012-12-18 14:30:41 +00008116 // Load pending declaration chains.
Richard Smithfe620d22015-03-05 23:24:12 +00008117 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
Richard Smithfe620d22015-03-05 23:24:12 +00008118 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
Richard Smithe687bf82015-03-16 20:54:07 +00008119 loadPendingDeclChain(PendingDeclChains[I]);
Richard Smithfe620d22015-03-05 23:24:12 +00008120 }
8121 assert(PendingDeclChainsKnown.empty());
Guy Benyei11169dd2012-12-18 14:30:41 +00008122 PendingDeclChains.clear();
8123
Richard Smith9b88a4c2015-07-27 05:40:23 +00008124 assert(RedeclsDeserialized.empty() && "some redecls not wired up");
8125
Douglas Gregor6168bd22013-02-18 15:53:43 +00008126 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008127 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8128 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008129 IdentifierInfo *II = TLD->first;
8130 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008131 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008132 }
8133 }
8134
Guy Benyei11169dd2012-12-18 14:30:41 +00008135 // Load any pending macro definitions.
8136 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008137 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8138 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8139 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8140 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008141 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008142 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008143 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008144 if (Info.M->Kind != MK_ImplicitModule &&
8145 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008146 resolvePendingMacro(II, Info);
8147 }
8148 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008149 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008150 ++IDIdx) {
8151 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008152 if (Info.M->Kind == MK_ImplicitModule ||
8153 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008154 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008155 }
8156 }
8157 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008158
8159 // Wire up the DeclContexts for Decls that we delayed setting until
8160 // recursive loading is completed.
8161 while (!PendingDeclContextInfos.empty()) {
8162 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8163 PendingDeclContextInfos.pop_front();
8164 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8165 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8166 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8167 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008168
Richard Smithd1c46742014-04-30 02:24:17 +00008169 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008170 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008171 auto Update = PendingUpdateRecords.pop_back_val();
8172 ReadingKindTracker ReadingKind(Read_Decl, *this);
8173 loadDeclUpdateRecords(Update.first, Update.second);
8174 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008175 }
Richard Smith8a639892015-01-24 01:07:20 +00008176
8177 // At this point, all update records for loaded decls are in place, so any
8178 // fake class definitions should have become real.
8179 assert(PendingFakeDefinitionData.empty() &&
8180 "faked up a class definition but never saw the real one");
8181
Guy Benyei11169dd2012-12-18 14:30:41 +00008182 // If we deserialized any C++ or Objective-C class definitions, any
8183 // Objective-C protocol definitions, or any redeclarable templates, make sure
8184 // that all redeclarations point to the definitions. Note that this can only
8185 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008186 for (Decl *D : PendingDefinitions) {
8187 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008188 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008189 // Make sure that the TagType points at the definition.
8190 const_cast<TagType*>(TagT)->decl = TD;
8191 }
Richard Smith8ce51082015-03-11 01:44:51 +00008192
Craig Topperc6914d02014-08-25 04:15:02 +00008193 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008194 for (auto *R = getMostRecentExistingDecl(RD); R;
8195 R = R->getPreviousDecl()) {
8196 assert((R == D) ==
8197 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008198 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008199 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008200 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008201 }
8202
8203 continue;
8204 }
Richard Smith8ce51082015-03-11 01:44:51 +00008205
Craig Topperc6914d02014-08-25 04:15:02 +00008206 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008207 // Make sure that the ObjCInterfaceType points at the definition.
8208 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8209 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008210
8211 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8212 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8213
Guy Benyei11169dd2012-12-18 14:30:41 +00008214 continue;
8215 }
Richard Smith8ce51082015-03-11 01:44:51 +00008216
Craig Topperc6914d02014-08-25 04:15:02 +00008217 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008218 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8219 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8220
Guy Benyei11169dd2012-12-18 14:30:41 +00008221 continue;
8222 }
Richard Smith8ce51082015-03-11 01:44:51 +00008223
Craig Topperc6914d02014-08-25 04:15:02 +00008224 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008225 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8226 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008227 }
8228 PendingDefinitions.clear();
8229
8230 // Load the bodies of any functions or methods we've encountered. We do
8231 // this now (delayed) so that we can be sure that the declaration chains
8232 // have been fully wired up.
Richard Smith8ce51082015-03-11 01:44:51 +00008233 // FIXME: There seems to be no point in delaying this, it does not depend
8234 // on the redecl chains having been wired up.
Guy Benyei11169dd2012-12-18 14:30:41 +00008235 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8236 PBEnd = PendingBodies.end();
8237 PB != PBEnd; ++PB) {
8238 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8239 // FIXME: Check for =delete/=default?
8240 // FIXME: Complain about ODR violations here?
8241 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8242 FD->setLazyBody(PB->second);
8243 continue;
8244 }
8245
8246 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8247 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8248 MD->setLazyBody(PB->second);
8249 }
8250 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008251
8252 // Do some cleanup.
8253 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8254 getContext().deduplicateMergedDefinitonsFor(ND);
8255 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008256}
8257
8258void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008259 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8260 return;
8261
Richard Smitha0ce9c42014-07-29 23:23:27 +00008262 // Trigger the import of the full definition of each class that had any
8263 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008264 // These updates may in turn find and diagnose some ODR failures, so take
8265 // ownership of the set first.
8266 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8267 PendingOdrMergeFailures.clear();
8268 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008269 Merge.first->buildLookup();
8270 Merge.first->decls_begin();
8271 Merge.first->bases_begin();
8272 Merge.first->vbases_begin();
8273 for (auto *RD : Merge.second) {
8274 RD->decls_begin();
8275 RD->bases_begin();
8276 RD->vbases_begin();
8277 }
8278 }
8279
8280 // For each declaration from a merged context, check that the canonical
8281 // definition of that context also contains a declaration of the same
8282 // entity.
8283 //
8284 // Caution: this loop does things that might invalidate iterators into
8285 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8286 while (!PendingOdrMergeChecks.empty()) {
8287 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8288
8289 // FIXME: Skip over implicit declarations for now. This matters for things
8290 // like implicitly-declared special member functions. This isn't entirely
8291 // correct; we can end up with multiple unmerged declarations of the same
8292 // implicit entity.
8293 if (D->isImplicit())
8294 continue;
8295
8296 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008297
8298 bool Found = false;
8299 const Decl *DCanon = D->getCanonicalDecl();
8300
Richard Smith01bdb7a2014-08-28 05:44:07 +00008301 for (auto RI : D->redecls()) {
8302 if (RI->getLexicalDeclContext() == CanonDef) {
8303 Found = true;
8304 break;
8305 }
8306 }
8307 if (Found)
8308 continue;
8309
Richard Smith0f4e2c42015-08-06 04:23:48 +00008310 // Quick check failed, time to do the slow thing. Note, we can't just
8311 // look up the name of D in CanonDef here, because the member that is
8312 // in CanonDef might not be found by name lookup (it might have been
8313 // replaced by a more recent declaration in the lookup table), and we
8314 // can't necessarily find it in the redeclaration chain because it might
8315 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008316 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008317 for (auto *CanonMember : CanonDef->decls()) {
8318 if (CanonMember->getCanonicalDecl() == DCanon) {
8319 // This can happen if the declaration is merely mergeable and not
8320 // actually redeclarable (we looked for redeclarations earlier).
8321 //
8322 // FIXME: We should be able to detect this more efficiently, without
8323 // pulling in all of the members of CanonDef.
8324 Found = true;
8325 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008326 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008327 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8328 if (ND->getDeclName() == D->getDeclName())
8329 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008330 }
8331
8332 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008333 // The AST doesn't like TagDecls becoming invalid after they've been
8334 // completed. We only really need to mark FieldDecls as invalid here.
8335 if (!isa<TagDecl>(D))
8336 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008337
8338 // Ensure we don't accidentally recursively enter deserialization while
8339 // we're producing our diagnostic.
8340 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008341
8342 std::string CanonDefModule =
8343 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8344 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8345 << D << getOwningModuleNameForDiagnostic(D)
8346 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8347
8348 if (Candidates.empty())
8349 Diag(cast<Decl>(CanonDef)->getLocation(),
8350 diag::note_module_odr_violation_no_possible_decls) << D;
8351 else {
8352 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8353 Diag(Candidates[I]->getLocation(),
8354 diag::note_module_odr_violation_possible_decl)
8355 << Candidates[I];
8356 }
8357
8358 DiagnosedOdrMergeFailures.insert(CanonDef);
8359 }
8360 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008361
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008362 if (OdrMergeFailures.empty())
8363 return;
8364
8365 // Ensure we don't accidentally recursively enter deserialization while
8366 // we're producing our diagnostics.
8367 Deserializing RecursionGuard(this);
8368
Richard Smithcd45dbc2014-04-19 03:48:30 +00008369 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008370 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008371 // If we've already pointed out a specific problem with this class, don't
8372 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008373 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008374 continue;
8375
8376 bool Diagnosed = false;
8377 for (auto *RD : Merge.second) {
8378 // Multiple different declarations got merged together; tell the user
8379 // where they came from.
8380 if (Merge.first != RD) {
8381 // FIXME: Walk the definition, figure out what's different,
8382 // and diagnose that.
8383 if (!Diagnosed) {
8384 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8385 Diag(Merge.first->getLocation(),
8386 diag::err_module_odr_violation_different_definitions)
8387 << Merge.first << Module.empty() << Module;
8388 Diagnosed = true;
8389 }
8390
8391 Diag(RD->getLocation(),
8392 diag::note_module_odr_violation_different_definitions)
8393 << getOwningModuleNameForDiagnostic(RD);
8394 }
8395 }
8396
8397 if (!Diagnosed) {
8398 // All definitions are updates to the same declaration. This happens if a
8399 // module instantiates the declaration of a class template specialization
8400 // and two or more other modules instantiate its definition.
8401 //
8402 // FIXME: Indicate which modules had instantiations of this definition.
8403 // FIXME: How can this even happen?
8404 Diag(Merge.first->getLocation(),
8405 diag::err_module_odr_violation_different_instantiations)
8406 << Merge.first;
8407 }
8408 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008409}
8410
Richard Smithce18a182015-07-14 00:26:00 +00008411void ASTReader::StartedDeserializing() {
8412 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8413 ReadTimer->startTimer();
8414}
8415
Guy Benyei11169dd2012-12-18 14:30:41 +00008416void ASTReader::FinishedDeserializing() {
8417 assert(NumCurrentElementsDeserializing &&
8418 "FinishedDeserializing not paired with StartedDeserializing");
8419 if (NumCurrentElementsDeserializing == 1) {
8420 // We decrease NumCurrentElementsDeserializing only after pending actions
8421 // are finished, to avoid recursively re-calling finishPendingActions().
8422 finishPendingActions();
8423 }
8424 --NumCurrentElementsDeserializing;
8425
Richard Smitha0ce9c42014-07-29 23:23:27 +00008426 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008427 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008428 while (!PendingExceptionSpecUpdates.empty()) {
8429 auto Updates = std::move(PendingExceptionSpecUpdates);
8430 PendingExceptionSpecUpdates.clear();
8431 for (auto Update : Updates) {
8432 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8433 SemaObj->UpdateExceptionSpec(Update.second,
8434 FPT->getExtProtoInfo().ExceptionSpec);
8435 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008436 }
8437
Richard Smithce18a182015-07-14 00:26:00 +00008438 if (ReadTimer)
8439 ReadTimer->stopTimer();
8440
Richard Smith0f4e2c42015-08-06 04:23:48 +00008441 diagnoseOdrViolations();
8442
Richard Smith04d05b52014-03-23 00:27:18 +00008443 // We are not in recursive loading, so it's safe to pass the "interesting"
8444 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008445 if (Consumer)
8446 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008447 }
8448}
8449
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008450void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008451 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8452 // Remove any fake results before adding any real ones.
8453 auto It = PendingFakeLookupResults.find(II);
8454 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008455 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008456 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008457 // FIXME: this works around module+PCH performance issue.
8458 // Rather than erase the result from the map, which is O(n), just clear
8459 // the vector of NamedDecls.
8460 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008461 }
8462 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008463
8464 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8465 SemaObj->TUScope->AddDecl(D);
8466 } else if (SemaObj->TUScope) {
8467 // Adding the decl to IdResolver may have failed because it was already in
8468 // (even though it was not added in scope). If it is already in, make sure
8469 // it gets in the scope as well.
8470 if (std::find(SemaObj->IdResolver.begin(Name),
8471 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8472 SemaObj->TUScope->AddDecl(D);
8473 }
8474}
8475
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008476ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008477 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008478 StringRef isysroot, bool DisableValidation,
8479 bool AllowASTWithCompilerErrors,
Nico Weber824285e2014-05-08 04:26:47 +00008480 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Richard Smithce18a182015-07-14 00:26:00 +00008481 bool UseGlobalIndex,
8482 std::unique_ptr<llvm::Timer> ReadTimer)
Craig Toppera13603a2014-05-22 05:54:18 +00008483 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008484 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008485 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008486 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008487 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
Richard Smithce18a182015-07-14 00:26:00 +00008488 ReadTimer(std::move(ReadTimer)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008489 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008490 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8491 AllowConfigurationMismatch(AllowConfigurationMismatch),
8492 ValidateSystemInputs(ValidateSystemInputs),
8493 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008494 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8495 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8496 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8497 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008498 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8499 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8500 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8501 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8502 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8503 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008504 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008505 SourceMgr.setExternalSLocEntrySource(this);
8506}
8507
8508ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008509 if (OwnsDeserializationListener)
8510 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00008511}