blob: 3045629a333e19561dafa565eb2d41641cfb52dc [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".
738static bool isInterestingIdentifier(IdentifierInfo &II) {
739 return II.isPoisoned() ||
740 II.isExtensionToken() ||
741 II.getObjCOrBuiltinID() ||
742 II.hasRevertedTokenIDToIdentifier() ||
743 II.hadMacroDefinition() ||
744 II.getFETokenInfo<void>();
745}
746
Guy Benyei11169dd2012-12-18 14:30:41 +0000747IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
748 const unsigned char* d,
749 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000750 using namespace llvm::support;
751 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000752 bool IsInteresting = RawID & 0x01;
753
754 // Wipe out the "is interesting" bit.
755 RawID = RawID >> 1;
756
757 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
758 if (!IsInteresting) {
759 // For uninteresting identifiers, just build the IdentifierInfo
760 // and associate it with the persistent ID.
761 IdentifierInfo *II = KnownII;
762 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000763 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000764 KnownII = II;
765 }
766 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000767 if (!II->isFromAST()) {
768 bool WasInteresting = isInterestingIdentifier(*II);
769 II->setIsFromAST();
770 if (WasInteresting)
771 II->setChangedSinceDeserialization();
772 }
773 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000774 return II;
775 }
776
Justin Bogner57ba0b22014-03-28 22:03:24 +0000777 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
778 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000779 bool CPlusPlusOperatorKeyword = Bits & 0x01;
780 Bits >>= 1;
781 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
782 Bits >>= 1;
783 bool Poisoned = Bits & 0x01;
784 Bits >>= 1;
785 bool ExtensionToken = Bits & 0x01;
786 Bits >>= 1;
787 bool hadMacroDefinition = Bits & 0x01;
788 Bits >>= 1;
789
790 assert(Bits == 0 && "Extra bits in the identifier?");
791 DataLen -= 8;
792
793 // Build the IdentifierInfo itself and link the identifier ID with
794 // the new IdentifierInfo.
795 IdentifierInfo *II = KnownII;
796 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000797 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000798 KnownII = II;
799 }
800 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000801 if (!II->isFromAST()) {
802 bool WasInteresting = isInterestingIdentifier(*II);
803 II->setIsFromAST();
804 if (WasInteresting)
805 II->setChangedSinceDeserialization();
806 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000807
808 // Set or check the various bits in the IdentifierInfo structure.
809 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000810 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000811 II->RevertTokenIDToIdentifier();
812 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
813 assert(II->isExtensionToken() == ExtensionToken &&
814 "Incorrect extension token flag");
815 (void)ExtensionToken;
816 if (Poisoned)
817 II->setIsPoisoned(true);
818 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
819 "Incorrect C++ operator keyword flag");
820 (void)CPlusPlusOperatorKeyword;
821
822 // If this identifier is a macro, deserialize the macro
823 // definition.
824 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000825 uint32_t MacroDirectivesOffset =
826 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000827 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000828
Richard Smithd7329392015-04-21 21:46:32 +0000829 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000830 }
831
832 Reader.SetIdentifierInfo(ID, II);
833
834 // Read all of the declarations visible at global scope with this
835 // name.
836 if (DataLen > 0) {
837 SmallVector<uint32_t, 4> DeclIDs;
838 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000839 DeclIDs.push_back(Reader.getGlobalDeclID(
840 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000841 Reader.SetGloballyVisibleDecls(II, DeclIDs);
842 }
843
844 return II;
845}
846
847unsigned
Richard Smith3b637412015-07-14 18:42:41 +0000848ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000849 llvm::FoldingSetNodeID ID;
850 ID.AddInteger(Key.Kind);
851
852 switch (Key.Kind) {
853 case DeclarationName::Identifier:
854 case DeclarationName::CXXLiteralOperatorName:
855 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
856 break;
857 case DeclarationName::ObjCZeroArgSelector:
858 case DeclarationName::ObjCOneArgSelector:
859 case DeclarationName::ObjCMultiArgSelector:
860 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
861 break;
862 case DeclarationName::CXXOperatorName:
863 ID.AddInteger((OverloadedOperatorKind)Key.Data);
864 break;
865 case DeclarationName::CXXConstructorName:
866 case DeclarationName::CXXDestructorName:
867 case DeclarationName::CXXConversionFunctionName:
868 case DeclarationName::CXXUsingDirective:
869 break;
870 }
871
872 return ID.ComputeHash();
873}
874
875ASTDeclContextNameLookupTrait::internal_key_type
876ASTDeclContextNameLookupTrait::GetInternalKey(
Richard Smith3b637412015-07-14 18:42:41 +0000877 const external_key_type& Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000878 DeclNameKey Key;
879 Key.Kind = Name.getNameKind();
880 switch (Name.getNameKind()) {
881 case DeclarationName::Identifier:
882 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
883 break;
884 case DeclarationName::ObjCZeroArgSelector:
885 case DeclarationName::ObjCOneArgSelector:
886 case DeclarationName::ObjCMultiArgSelector:
887 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
888 break;
889 case DeclarationName::CXXOperatorName:
890 Key.Data = Name.getCXXOverloadedOperator();
891 break;
892 case DeclarationName::CXXLiteralOperatorName:
893 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
894 break;
895 case DeclarationName::CXXConstructorName:
896 case DeclarationName::CXXDestructorName:
897 case DeclarationName::CXXConversionFunctionName:
898 case DeclarationName::CXXUsingDirective:
899 Key.Data = 0;
900 break;
901 }
902
903 return Key;
904}
905
906std::pair<unsigned, unsigned>
907ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000908 using namespace llvm::support;
909 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
910 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000911 return std::make_pair(KeyLen, DataLen);
912}
913
914ASTDeclContextNameLookupTrait::internal_key_type
915ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000916 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000917
918 DeclNameKey Key;
919 Key.Kind = (DeclarationName::NameKind)*d++;
920 switch (Key.Kind) {
921 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000922 Key.Data = (uint64_t)Reader.getLocalIdentifier(
923 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000924 break;
925 case DeclarationName::ObjCZeroArgSelector:
926 case DeclarationName::ObjCOneArgSelector:
927 case DeclarationName::ObjCMultiArgSelector:
928 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000929 (uint64_t)Reader.getLocalSelector(
930 F, endian::readNext<uint32_t, little, unaligned>(
931 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000932 break;
933 case DeclarationName::CXXOperatorName:
934 Key.Data = *d++; // OverloadedOperatorKind
935 break;
936 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000937 Key.Data = (uint64_t)Reader.getLocalIdentifier(
938 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000939 break;
940 case DeclarationName::CXXConstructorName:
941 case DeclarationName::CXXDestructorName:
942 case DeclarationName::CXXConversionFunctionName:
943 case DeclarationName::CXXUsingDirective:
944 Key.Data = 0;
945 break;
946 }
947
948 return Key;
949}
950
951ASTDeclContextNameLookupTrait::data_type
952ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
953 const unsigned char* d,
954 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000955 using namespace llvm::support;
956 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000957 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
958 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000959 return std::make_pair(Start, Start + NumDecls);
960}
961
962bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000963 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000964 const std::pair<uint64_t, uint64_t> &Offsets,
965 DeclContextInfo &Info) {
966 SavedStreamPosition SavedPosition(Cursor);
967 // First the lexical decls.
968 if (Offsets.first != 0) {
969 Cursor.JumpToBit(Offsets.first);
970
971 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000972 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000973 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000974 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000975 if (RecCode != DECL_CONTEXT_LEXICAL) {
976 Error("Expected lexical block");
977 return true;
978 }
979
Chris Lattner0e6c9402013-01-20 02:38:54 +0000980 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
981 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000982 }
983
984 // Now the lookup table.
985 if (Offsets.second != 0) {
986 Cursor.JumpToBit(Offsets.second);
987
988 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000989 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000990 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000991 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000992 if (RecCode != DECL_CONTEXT_VISIBLE) {
993 Error("Expected visible lookup table block");
994 return true;
995 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000996 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
997 (const unsigned char *)Blob.data() + Record[0],
998 (const unsigned char *)Blob.data() + sizeof(uint32_t),
999 (const unsigned char *)Blob.data(),
1000 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +00001001 }
1002
1003 return false;
1004}
1005
1006void ASTReader::Error(StringRef Msg) {
1007 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +00001008 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
1009 Diag(diag::note_module_cache_path)
1010 << PP.getHeaderSearchInfo().getModuleCachePath();
1011 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001012}
1013
1014void ASTReader::Error(unsigned DiagID,
1015 StringRef Arg1, StringRef Arg2) {
1016 if (Diags.isDiagnosticInFlight())
1017 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1018 else
1019 Diag(DiagID) << Arg1 << Arg2;
1020}
1021
1022//===----------------------------------------------------------------------===//
1023// Source Manager Deserialization
1024//===----------------------------------------------------------------------===//
1025
1026/// \brief Read the line table in the source manager block.
1027/// \returns true if there was an error.
1028bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001029 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001030 unsigned Idx = 0;
1031 LineTableInfo &LineTable = SourceMgr.getLineTable();
1032
1033 // Parse the file names
1034 std::map<int, int> FileIDs;
1035 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1036 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001037 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001038 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1039 }
1040
1041 // Parse the line entries
1042 std::vector<LineEntry> Entries;
1043 while (Idx < Record.size()) {
1044 int FID = Record[Idx++];
1045 assert(FID >= 0 && "Serialized line entries for non-local file.");
1046 // Remap FileID from 1-based old view.
1047 FID += F.SLocEntryBaseID - 1;
1048
1049 // Extract the line entries
1050 unsigned NumEntries = Record[Idx++];
1051 assert(NumEntries && "Numentries is 00000");
1052 Entries.clear();
1053 Entries.reserve(NumEntries);
1054 for (unsigned I = 0; I != NumEntries; ++I) {
1055 unsigned FileOffset = Record[Idx++];
1056 unsigned LineNo = Record[Idx++];
1057 int FilenameID = FileIDs[Record[Idx++]];
1058 SrcMgr::CharacteristicKind FileKind
1059 = (SrcMgr::CharacteristicKind)Record[Idx++];
1060 unsigned IncludeOffset = Record[Idx++];
1061 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1062 FileKind, IncludeOffset));
1063 }
1064 LineTable.AddEntry(FileID::get(FID), Entries);
1065 }
1066
1067 return false;
1068}
1069
1070/// \brief Read a source manager block
1071bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1072 using namespace SrcMgr;
1073
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001074 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001075
1076 // Set the source-location entry cursor to the current position in
1077 // the stream. This cursor will be used to read the contents of the
1078 // source manager block initially, and then lazily read
1079 // source-location entries as needed.
1080 SLocEntryCursor = F.Stream;
1081
1082 // The stream itself is going to skip over the source manager block.
1083 if (F.Stream.SkipBlock()) {
1084 Error("malformed block record in AST file");
1085 return true;
1086 }
1087
1088 // Enter the source manager block.
1089 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1090 Error("malformed source manager block record in AST file");
1091 return true;
1092 }
1093
1094 RecordData Record;
1095 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001096 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1097
1098 switch (E.Kind) {
1099 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1100 case llvm::BitstreamEntry::Error:
1101 Error("malformed block record in AST file");
1102 return true;
1103 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001104 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001105 case llvm::BitstreamEntry::Record:
1106 // The interesting case.
1107 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001108 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001109
Guy Benyei11169dd2012-12-18 14:30:41 +00001110 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001111 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001112 StringRef Blob;
1113 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001114 default: // Default behavior: ignore.
1115 break;
1116
1117 case SM_SLOC_FILE_ENTRY:
1118 case SM_SLOC_BUFFER_ENTRY:
1119 case SM_SLOC_EXPANSION_ENTRY:
1120 // Once we hit one of the source location entries, we're done.
1121 return false;
1122 }
1123 }
1124}
1125
1126/// \brief If a header file is not found at the path that we expect it to be
1127/// and the PCH file was moved from its original location, try to resolve the
1128/// file by assuming that header+PCH were moved together and the header is in
1129/// the same place relative to the PCH.
1130static std::string
1131resolveFileRelativeToOriginalDir(const std::string &Filename,
1132 const std::string &OriginalDir,
1133 const std::string &CurrDir) {
1134 assert(OriginalDir != CurrDir &&
1135 "No point trying to resolve the file if the PCH dir didn't change");
1136 using namespace llvm::sys;
1137 SmallString<128> filePath(Filename);
1138 fs::make_absolute(filePath);
1139 assert(path::is_absolute(OriginalDir));
1140 SmallString<128> currPCHPath(CurrDir);
1141
1142 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1143 fileDirE = path::end(path::parent_path(filePath));
1144 path::const_iterator origDirI = path::begin(OriginalDir),
1145 origDirE = path::end(OriginalDir);
1146 // Skip the common path components from filePath and OriginalDir.
1147 while (fileDirI != fileDirE && origDirI != origDirE &&
1148 *fileDirI == *origDirI) {
1149 ++fileDirI;
1150 ++origDirI;
1151 }
1152 for (; origDirI != origDirE; ++origDirI)
1153 path::append(currPCHPath, "..");
1154 path::append(currPCHPath, fileDirI, fileDirE);
1155 path::append(currPCHPath, path::filename(Filename));
1156 return currPCHPath.str();
1157}
1158
1159bool ASTReader::ReadSLocEntry(int ID) {
1160 if (ID == 0)
1161 return false;
1162
1163 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1164 Error("source location entry ID out-of-range for AST file");
1165 return true;
1166 }
1167
1168 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1169 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001170 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001171 unsigned BaseOffset = F->SLocEntryBaseOffset;
1172
1173 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001174 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1175 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001176 Error("incorrectly-formatted source location entry in AST file");
1177 return true;
1178 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001179
Guy Benyei11169dd2012-12-18 14:30:41 +00001180 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001181 StringRef Blob;
1182 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001183 default:
1184 Error("incorrectly-formatted source location entry in AST file");
1185 return true;
1186
1187 case SM_SLOC_FILE_ENTRY: {
1188 // We will detect whether a file changed and return 'Failure' for it, but
1189 // we will also try to fail gracefully by setting up the SLocEntry.
1190 unsigned InputID = Record[4];
1191 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001192 const FileEntry *File = IF.getFile();
1193 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001194
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001195 // Note that we only check if a File was returned. If it was out-of-date
1196 // we have complained but we will continue creating a FileID to recover
1197 // gracefully.
1198 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001199 return true;
1200
1201 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1202 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1203 // This is the module's main file.
1204 IncludeLoc = getImportLocation(F);
1205 }
1206 SrcMgr::CharacteristicKind
1207 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1208 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1209 ID, BaseOffset + Record[0]);
1210 SrcMgr::FileInfo &FileInfo =
1211 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1212 FileInfo.NumCreatedFIDs = Record[5];
1213 if (Record[3])
1214 FileInfo.setHasLineDirectives();
1215
1216 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1217 unsigned NumFileDecls = Record[7];
1218 if (NumFileDecls) {
1219 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1220 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1221 NumFileDecls));
1222 }
1223
1224 const SrcMgr::ContentCache *ContentCache
1225 = SourceMgr.getOrCreateContentCache(File,
1226 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1227 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1228 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1229 unsigned Code = SLocEntryCursor.ReadCode();
1230 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001231 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001232
1233 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1234 Error("AST record has invalid code");
1235 return true;
1236 }
1237
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001238 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001239 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001240 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001241 }
1242
1243 break;
1244 }
1245
1246 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001247 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001248 unsigned Offset = Record[0];
1249 SrcMgr::CharacteristicKind
1250 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1251 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001252 if (IncludeLoc.isInvalid() &&
1253 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001254 IncludeLoc = getImportLocation(F);
1255 }
1256 unsigned Code = SLocEntryCursor.ReadCode();
1257 Record.clear();
1258 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001259 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001260
1261 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1262 Error("AST record has invalid code");
1263 return true;
1264 }
1265
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001266 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1267 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001268 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001269 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001270 break;
1271 }
1272
1273 case SM_SLOC_EXPANSION_ENTRY: {
1274 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1275 SourceMgr.createExpansionLoc(SpellingLoc,
1276 ReadSourceLocation(*F, Record[2]),
1277 ReadSourceLocation(*F, Record[3]),
1278 Record[4],
1279 ID,
1280 BaseOffset + Record[0]);
1281 break;
1282 }
1283 }
1284
1285 return false;
1286}
1287
1288std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1289 if (ID == 0)
1290 return std::make_pair(SourceLocation(), "");
1291
1292 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1293 Error("source location entry ID out-of-range for AST file");
1294 return std::make_pair(SourceLocation(), "");
1295 }
1296
1297 // Find which module file this entry lands in.
1298 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001299 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001300 return std::make_pair(SourceLocation(), "");
1301
1302 // FIXME: Can we map this down to a particular submodule? That would be
1303 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001304 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001305}
1306
1307/// \brief Find the location where the module F is imported.
1308SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1309 if (F->ImportLoc.isValid())
1310 return F->ImportLoc;
1311
1312 // Otherwise we have a PCH. It's considered to be "imported" at the first
1313 // location of its includer.
1314 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001315 // Main file is the importer.
1316 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1317 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001318 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001319 return F->ImportedBy[0]->FirstLoc;
1320}
1321
1322/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1323/// specified cursor. Read the abbreviations that are at the top of the block
1324/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001325bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001326 if (Cursor.EnterSubBlock(BlockID)) {
1327 Error("malformed block record in AST file");
1328 return Failure;
1329 }
1330
1331 while (true) {
1332 uint64_t Offset = Cursor.GetCurrentBitNo();
1333 unsigned Code = Cursor.ReadCode();
1334
1335 // We expect all abbrevs to be at the start of the block.
1336 if (Code != llvm::bitc::DEFINE_ABBREV) {
1337 Cursor.JumpToBit(Offset);
1338 return false;
1339 }
1340 Cursor.ReadAbbrevRecord();
1341 }
1342}
1343
Richard Smithe40f2ba2013-08-07 21:41:30 +00001344Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001345 unsigned &Idx) {
1346 Token Tok;
1347 Tok.startToken();
1348 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1349 Tok.setLength(Record[Idx++]);
1350 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1351 Tok.setIdentifierInfo(II);
1352 Tok.setKind((tok::TokenKind)Record[Idx++]);
1353 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1354 return Tok;
1355}
1356
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001357MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001358 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001359
1360 // Keep track of where we are in the stream, then jump back there
1361 // after reading this macro.
1362 SavedStreamPosition SavedPosition(Stream);
1363
1364 Stream.JumpToBit(Offset);
1365 RecordData Record;
1366 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001367 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001368
Guy Benyei11169dd2012-12-18 14:30:41 +00001369 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001370 // Advance to the next record, but if we get to the end of the block, don't
1371 // pop it (removing all the abbreviations from the cursor) since we want to
1372 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001373 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001374 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1375
1376 switch (Entry.Kind) {
1377 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1378 case llvm::BitstreamEntry::Error:
1379 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001380 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001381 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001382 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001383 case llvm::BitstreamEntry::Record:
1384 // The interesting case.
1385 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001386 }
1387
1388 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001389 Record.clear();
1390 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001391 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001392 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001393 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001394 case PP_MACRO_DIRECTIVE_HISTORY:
1395 return Macro;
1396
Guy Benyei11169dd2012-12-18 14:30:41 +00001397 case PP_MACRO_OBJECT_LIKE:
1398 case PP_MACRO_FUNCTION_LIKE: {
1399 // If we already have a macro, that means that we've hit the end
1400 // of the definition of the macro we were looking for. We're
1401 // done.
1402 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001403 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001404
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001405 unsigned NextIndex = 1; // Skip identifier ID.
1406 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001407 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001408 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001409 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001410 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001411 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001412
Guy Benyei11169dd2012-12-18 14:30:41 +00001413 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1414 // Decode function-like macro info.
1415 bool isC99VarArgs = Record[NextIndex++];
1416 bool isGNUVarArgs = Record[NextIndex++];
1417 bool hasCommaPasting = Record[NextIndex++];
1418 MacroArgs.clear();
1419 unsigned NumArgs = Record[NextIndex++];
1420 for (unsigned i = 0; i != NumArgs; ++i)
1421 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1422
1423 // Install function-like macro info.
1424 MI->setIsFunctionLike();
1425 if (isC99VarArgs) MI->setIsC99Varargs();
1426 if (isGNUVarArgs) MI->setIsGNUVarargs();
1427 if (hasCommaPasting) MI->setHasCommaPasting();
1428 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1429 PP.getPreprocessorAllocator());
1430 }
1431
Guy Benyei11169dd2012-12-18 14:30:41 +00001432 // Remember that we saw this macro last so that we add the tokens that
1433 // form its body to it.
1434 Macro = MI;
1435
1436 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1437 Record[NextIndex]) {
1438 // We have a macro definition. Register the association
1439 PreprocessedEntityID
1440 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1441 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001442 PreprocessingRecord::PPEntityID PPID =
1443 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1444 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1445 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001446 if (PPDef)
1447 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001448 }
1449
1450 ++NumMacrosRead;
1451 break;
1452 }
1453
1454 case PP_TOKEN: {
1455 // If we see a TOKEN before a PP_MACRO_*, then the file is
1456 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001457 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001458
John McCallf413f5e2013-05-03 00:10:13 +00001459 unsigned Idx = 0;
1460 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001461 Macro->AddTokenToBody(Tok);
1462 break;
1463 }
1464 }
1465 }
1466}
1467
1468PreprocessedEntityID
1469ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1470 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1471 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1472 assert(I != M.PreprocessedEntityRemap.end()
1473 && "Invalid index into preprocessed entity index remap");
1474
1475 return LocalID + I->second;
1476}
1477
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001478unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1479 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001480}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001481
Guy Benyei11169dd2012-12-18 14:30:41 +00001482HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001483HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1484 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
Richard Smith7ed1bc92014-12-05 22:42:13 +00001485 FE->getName(), /*Imported*/false };
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001486 return ikey;
1487}
Guy Benyei11169dd2012-12-18 14:30:41 +00001488
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001489bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1490 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001491 return false;
1492
Richard Smith7ed1bc92014-12-05 22:42:13 +00001493 if (llvm::sys::path::is_absolute(a.Filename) &&
1494 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001495 return true;
1496
Guy Benyei11169dd2012-12-18 14:30:41 +00001497 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001498 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001499 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1500 if (!Key.Imported)
1501 return FileMgr.getFile(Key.Filename);
1502
1503 std::string Resolved = Key.Filename;
1504 Reader.ResolveImportedPath(M, Resolved);
1505 return FileMgr.getFile(Resolved);
1506 };
1507
1508 const FileEntry *FEA = GetFile(a);
1509 const FileEntry *FEB = GetFile(b);
1510 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001511}
1512
1513std::pair<unsigned, unsigned>
1514HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001515 using namespace llvm::support;
1516 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001518 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001519}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001520
1521HeaderFileInfoTrait::internal_key_type
1522HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001523 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001524 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001525 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1526 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001527 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001528 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001529 return ikey;
1530}
1531
Guy Benyei11169dd2012-12-18 14:30:41 +00001532HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001533HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001534 unsigned DataLen) {
1535 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001536 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001537 HeaderFileInfo HFI;
1538 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001539 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1540 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001541 HFI.isImport = (Flags >> 5) & 0x01;
1542 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1543 HFI.DirInfo = (Flags >> 2) & 0x03;
1544 HFI.Resolved = (Flags >> 1) & 0x01;
1545 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001546 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1547 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1548 M, endian::readNext<uint32_t, little, unaligned>(d));
1549 if (unsigned FrameworkOffset =
1550 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001551 // The framework offset is 1 greater than the actual offset,
1552 // since 0 is used as an indicator for "no framework name".
1553 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1554 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1555 }
1556
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001557 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001558 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001559 if (LocalSMID) {
1560 // This header is part of a module. Associate it with the module to enable
1561 // implicit module import.
1562 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1563 Module *Mod = Reader.getSubmodule(GlobalSMID);
1564 HFI.isModuleHeader = true;
1565 FileManager &FileMgr = Reader.getFileManager();
1566 ModuleMap &ModMap =
1567 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001568 // FIXME: This information should be propagated through the
1569 // SUBMODULE_HEADER etc records rather than from here.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001570 // FIXME: We don't ever mark excluded headers.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001571 std::string Filename = key.Filename;
1572 if (key.Imported)
1573 Reader.ResolveImportedPath(M, Filename);
1574 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Hans Wennborg0101b542014-12-02 02:13:09 +00001575 ModMap.addHeader(Mod, H, HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001576 }
1577 }
1578
Guy Benyei11169dd2012-12-18 14:30:41 +00001579 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1580 (void)End;
1581
1582 // This HeaderFileInfo was externally loaded.
1583 HFI.External = true;
1584 return HFI;
1585}
1586
Richard Smithd7329392015-04-21 21:46:32 +00001587void ASTReader::addPendingMacro(IdentifierInfo *II,
1588 ModuleFile *M,
1589 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001590 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1591 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001592}
1593
1594void ASTReader::ReadDefinedMacros() {
1595 // Note that we are loading defined macros.
1596 Deserializing Macros(this);
1597
1598 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1599 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001600 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001601
1602 // If there was no preprocessor block, skip this file.
1603 if (!MacroCursor.getBitStreamReader())
1604 continue;
1605
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001606 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001607 Cursor.JumpToBit((*I)->MacroStartOffset);
1608
1609 RecordData Record;
1610 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001611 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1612
1613 switch (E.Kind) {
1614 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1615 case llvm::BitstreamEntry::Error:
1616 Error("malformed block record in AST file");
1617 return;
1618 case llvm::BitstreamEntry::EndBlock:
1619 goto NextCursor;
1620
1621 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001622 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001623 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001624 default: // Default behavior: ignore.
1625 break;
1626
1627 case PP_MACRO_OBJECT_LIKE:
1628 case PP_MACRO_FUNCTION_LIKE:
1629 getLocalIdentifier(**I, Record[0]);
1630 break;
1631
1632 case PP_TOKEN:
1633 // Ignore tokens.
1634 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001635 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001636 break;
1637 }
1638 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001639 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001640 }
1641}
1642
1643namespace {
1644 /// \brief Visitor class used to look up identifirs in an AST file.
1645 class IdentifierLookupVisitor {
1646 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001647 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001648 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001649 unsigned &NumIdentifierLookups;
1650 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001651 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001652
Guy Benyei11169dd2012-12-18 14:30:41 +00001653 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001654 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1655 unsigned &NumIdentifierLookups,
1656 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001657 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1658 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001659 NumIdentifierLookups(NumIdentifierLookups),
1660 NumIdentifierLookupHits(NumIdentifierLookupHits),
1661 Found()
1662 {
1663 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001664
1665 static bool visit(ModuleFile &M, void *UserData) {
1666 IdentifierLookupVisitor *This
1667 = static_cast<IdentifierLookupVisitor *>(UserData);
1668
1669 // If we've already searched this module file, skip it now.
1670 if (M.Generation <= This->PriorGeneration)
1671 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001672
Guy Benyei11169dd2012-12-18 14:30:41 +00001673 ASTIdentifierLookupTable *IdTable
1674 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1675 if (!IdTable)
1676 return false;
1677
1678 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1679 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001680 ++This->NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001681 ASTIdentifierLookupTable::iterator Pos =
1682 IdTable->find_hashed(This->Name, This->NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001683 if (Pos == IdTable->end())
1684 return false;
1685
1686 // Dereferencing the iterator has the effect of building the
1687 // IdentifierInfo node and populating it with the various
1688 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001689 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001690 This->Found = *Pos;
1691 return true;
1692 }
1693
1694 // \brief Retrieve the identifier info found within the module
1695 // files.
1696 IdentifierInfo *getIdentifierInfo() const { return Found; }
1697 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001698}
Guy Benyei11169dd2012-12-18 14:30:41 +00001699
1700void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1701 // Note that we are loading an identifier.
1702 Deserializing AnIdentifier(this);
1703
1704 unsigned PriorGeneration = 0;
1705 if (getContext().getLangOpts().Modules)
1706 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001707
1708 // If there is a global index, look there first to determine which modules
1709 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001710 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001711 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001712 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001713 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1714 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001715 }
1716 }
1717
Douglas Gregor7211ac12013-01-25 23:32:03 +00001718 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001719 NumIdentifierLookups,
1720 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001721 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001722 markIdentifierUpToDate(&II);
1723}
1724
1725void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1726 if (!II)
1727 return;
1728
1729 II->setOutOfDate(false);
1730
1731 // Update the generation for this identifier.
1732 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001733 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001734}
1735
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001736void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1737 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001738 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001739
1740 BitstreamCursor &Cursor = M.MacroCursor;
1741 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001742 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001743
Richard Smith713369b2015-04-23 20:40:50 +00001744 struct ModuleMacroRecord {
1745 SubmoduleID SubModID;
1746 MacroInfo *MI;
1747 SmallVector<SubmoduleID, 8> Overrides;
1748 };
1749 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001750
Richard Smithd7329392015-04-21 21:46:32 +00001751 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1752 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1753 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001754 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001755 while (true) {
1756 llvm::BitstreamEntry Entry =
1757 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1758 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1759 Error("malformed block record in AST file");
1760 return;
1761 }
1762
1763 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001764 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001765 case PP_MACRO_DIRECTIVE_HISTORY:
1766 break;
1767
1768 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001769 ModuleMacros.push_back(ModuleMacroRecord());
1770 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001771 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1772 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001773 for (int I = 2, N = Record.size(); I != N; ++I)
1774 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001775 continue;
1776 }
1777
1778 default:
1779 Error("malformed block record in AST file");
1780 return;
1781 }
1782
1783 // We found the macro directive history; that's the last record
1784 // for this macro.
1785 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001786 }
1787
Richard Smithd7329392015-04-21 21:46:32 +00001788 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001789 {
1790 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001791 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001792 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001793 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001794 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001795 Module *Mod = getSubmodule(ModID);
1796 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001797 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001798 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001799 }
1800
1801 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001802 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001803 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001804 }
1805 }
1806
1807 // Don't read the directive history for a module; we don't have anywhere
1808 // to put it.
1809 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1810 return;
1811
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001812 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001813 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001814 unsigned Idx = 0, N = Record.size();
1815 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001816 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001817 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001818 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1819 switch (K) {
1820 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001821 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001822 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001823 break;
1824 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001825 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001826 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001827 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001828 }
1829 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001830 bool isPublic = Record[Idx++];
1831 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1832 break;
1833 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001834
1835 if (!Latest)
1836 Latest = MD;
1837 if (Earliest)
1838 Earliest->setPrevious(MD);
1839 Earliest = MD;
1840 }
1841
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001842 if (Latest)
1843 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001844}
1845
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001846ASTReader::InputFileInfo
1847ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001848 // Go find this input file.
1849 BitstreamCursor &Cursor = F.InputFilesCursor;
1850 SavedStreamPosition SavedPosition(Cursor);
1851 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1852
1853 unsigned Code = Cursor.ReadCode();
1854 RecordData Record;
1855 StringRef Blob;
1856
1857 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1858 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1859 "invalid record type for input file");
1860 (void)Result;
1861
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001862 std::string Filename;
1863 off_t StoredSize;
1864 time_t StoredTime;
1865 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001866
Ben Langmuir198c1682014-03-07 07:27:49 +00001867 assert(Record[0] == ID && "Bogus stored ID or offset");
1868 StoredSize = static_cast<off_t>(Record[1]);
1869 StoredTime = static_cast<time_t>(Record[2]);
1870 Overridden = static_cast<bool>(Record[3]);
1871 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001872 ResolveImportedPath(F, Filename);
1873
Hans Wennborg73945142014-03-14 17:45:06 +00001874 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1875 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001876}
1877
1878std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001879 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00001880}
1881
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001882InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001883 // If this ID is bogus, just return an empty input file.
1884 if (ID == 0 || ID > F.InputFilesLoaded.size())
1885 return InputFile();
1886
1887 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001888 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001889 return F.InputFilesLoaded[ID-1];
1890
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001891 if (F.InputFilesLoaded[ID-1].isNotFound())
1892 return InputFile();
1893
Guy Benyei11169dd2012-12-18 14:30:41 +00001894 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001895 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001896 SavedStreamPosition SavedPosition(Cursor);
1897 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1898
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001899 InputFileInfo FI = readInputFileInfo(F, ID);
1900 off_t StoredSize = FI.StoredSize;
1901 time_t StoredTime = FI.StoredTime;
1902 bool Overridden = FI.Overridden;
1903 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001904
Ben Langmuir198c1682014-03-07 07:27:49 +00001905 const FileEntry *File
1906 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1907 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1908
1909 // If we didn't find the file, resolve it relative to the
1910 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00001911 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00001912 F.OriginalDir != CurrentDir) {
1913 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1914 F.OriginalDir,
1915 CurrentDir);
1916 if (!Resolved.empty())
1917 File = FileMgr.getFile(Resolved);
1918 }
1919
1920 // For an overridden file, create a virtual file with the stored
1921 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00001922 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001923 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1924 }
1925
Craig Toppera13603a2014-05-22 05:54:18 +00001926 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001927 if (Complain) {
1928 std::string ErrorStr = "could not find file '";
1929 ErrorStr += Filename;
1930 ErrorStr += "' referenced by AST file";
1931 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001932 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001933 // Record that we didn't find the file.
1934 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1935 return InputFile();
1936 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001937
Ben Langmuir198c1682014-03-07 07:27:49 +00001938 // Check if there was a request to override the contents of the file
1939 // that was part of the precompiled header. Overridding such a file
1940 // can lead to problems when lexing using the source locations from the
1941 // PCH.
1942 SourceManager &SM = getSourceManager();
1943 if (!Overridden && SM.isFileOverridden(File)) {
1944 if (Complain)
1945 Error(diag::err_fe_pch_file_overridden, Filename);
1946 // After emitting the diagnostic, recover by disabling the override so
1947 // that the original file will be used.
1948 SM.disableFileContentsOverride(File);
1949 // The FileEntry is a virtual file entry with the size of the contents
1950 // that would override the original contents. Set it to the original's
1951 // size/time.
1952 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1953 StoredSize, StoredTime);
1954 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001955
Ben Langmuir198c1682014-03-07 07:27:49 +00001956 bool IsOutOfDate = false;
1957
1958 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00001959 if (!Overridden && //
1960 (StoredSize != File->getSize() ||
1961#if defined(LLVM_ON_WIN32)
1962 false
1963#else
Ben Langmuir198c1682014-03-07 07:27:49 +00001964 // In our regression testing, the Windows file system seems to
1965 // have inconsistent modification times that sometimes
1966 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00001967 //
1968 // This also happens in networked file systems, so disable this
1969 // check if validation is disabled or if we have an explicitly
1970 // built PCM file.
1971 //
1972 // FIXME: Should we also do this for PCH files? They could also
1973 // reasonably get shared across a network during a distributed build.
1974 (StoredTime != File->getModificationTime() && !DisableValidation &&
1975 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001976#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00001977 )) {
1978 if (Complain) {
1979 // Build a list of the PCH imports that got us here (in reverse).
1980 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1981 while (ImportStack.back()->ImportedBy.size() > 0)
1982 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00001983
Ben Langmuir198c1682014-03-07 07:27:49 +00001984 // The top-level PCH is stale.
1985 StringRef TopLevelPCHName(ImportStack.back()->FileName);
1986 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00001987
Ben Langmuir198c1682014-03-07 07:27:49 +00001988 // Print the import stack.
1989 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
1990 Diag(diag::note_pch_required_by)
1991 << Filename << ImportStack[0]->FileName;
1992 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00001993 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00001994 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00001995 }
1996
Ben Langmuir198c1682014-03-07 07:27:49 +00001997 if (!Diags.isDiagnosticInFlight())
1998 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00001999 }
2000
Ben Langmuir198c1682014-03-07 07:27:49 +00002001 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002002 }
2003
Ben Langmuir198c1682014-03-07 07:27:49 +00002004 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2005
2006 // Note that we've loaded this input file.
2007 F.InputFilesLoaded[ID-1] = IF;
2008 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002009}
2010
Richard Smith7ed1bc92014-12-05 22:42:13 +00002011/// \brief If we are loading a relocatable PCH or module file, and the filename
2012/// is not an absolute path, add the system or module root to the beginning of
2013/// the file name.
2014void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2015 // Resolve relative to the base directory, if we have one.
2016 if (!M.BaseDirectory.empty())
2017 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002018}
2019
Richard Smith7ed1bc92014-12-05 22:42:13 +00002020void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002021 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2022 return;
2023
Richard Smith7ed1bc92014-12-05 22:42:13 +00002024 SmallString<128> Buffer;
2025 llvm::sys::path::append(Buffer, Prefix, Filename);
2026 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002027}
2028
2029ASTReader::ASTReadResult
2030ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002031 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002032 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002033 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002034 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002035
2036 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2037 Error("malformed block record in AST file");
2038 return Failure;
2039 }
2040
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002041 // Should we allow the configuration of the module file to differ from the
2042 // configuration of the current translation unit in a compatible way?
2043 //
2044 // FIXME: Allow this for files explicitly specified with -include-pch too.
2045 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2046
Guy Benyei11169dd2012-12-18 14:30:41 +00002047 // Read all of the records and blocks in the control block.
2048 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002049 unsigned NumInputs = 0;
2050 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002051 while (1) {
2052 llvm::BitstreamEntry Entry = Stream.advance();
2053
2054 switch (Entry.Kind) {
2055 case llvm::BitstreamEntry::Error:
2056 Error("malformed block record in AST file");
2057 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002058 case llvm::BitstreamEntry::EndBlock: {
2059 // Validate input files.
2060 const HeaderSearchOptions &HSOpts =
2061 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002062
Richard Smitha1825302014-10-23 22:18:29 +00002063 // All user input files reside at the index range [0, NumUserInputs), and
2064 // system input files reside at [NumUserInputs, NumInputs).
Ben Langmuiracb803e2014-11-10 22:13:10 +00002065 if (!DisableValidation) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002066 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002067
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002068 // If we are reading a module, we will create a verification timestamp,
2069 // so we verify all input files. Otherwise, verify only user input
2070 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002071
2072 unsigned N = NumUserInputs;
2073 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002074 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002075 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002076 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002077 N = NumInputs;
2078
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002079 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002080 InputFile IF = getInputFile(F, I+1, Complain);
2081 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002082 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002083 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002084 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002085
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002086 if (Listener)
2087 Listener->visitModuleFile(F.FileName);
2088
Ben Langmuircb69b572014-03-07 06:40:32 +00002089 if (Listener && Listener->needsInputFileVisitation()) {
2090 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2091 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002092 for (unsigned I = 0; I < N; ++I) {
2093 bool IsSystem = I >= NumUserInputs;
2094 InputFileInfo FI = readInputFileInfo(F, I+1);
2095 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2096 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002097 }
2098
Guy Benyei11169dd2012-12-18 14:30:41 +00002099 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002100 }
2101
Chris Lattnere7b154b2013-01-19 21:39:22 +00002102 case llvm::BitstreamEntry::SubBlock:
2103 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002104 case INPUT_FILES_BLOCK_ID:
2105 F.InputFilesCursor = Stream;
2106 if (Stream.SkipBlock() || // Skip with the main cursor
2107 // Read the abbreviations
2108 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2109 Error("malformed block record in AST file");
2110 return Failure;
2111 }
2112 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002113
Guy Benyei11169dd2012-12-18 14:30:41 +00002114 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002115 if (Stream.SkipBlock()) {
2116 Error("malformed block record in AST file");
2117 return Failure;
2118 }
2119 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002120 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002121
2122 case llvm::BitstreamEntry::Record:
2123 // The interesting case.
2124 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002125 }
2126
2127 // Read and process a record.
2128 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002129 StringRef Blob;
2130 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002131 case METADATA: {
2132 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2133 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002134 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2135 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002136 return VersionMismatch;
2137 }
2138
2139 bool hasErrors = Record[5];
2140 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2141 Diag(diag::err_pch_with_compiler_errors);
2142 return HadErrors;
2143 }
2144
2145 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002146 // Relative paths in a relocatable PCH are relative to our sysroot.
2147 if (F.RelocatablePCH)
2148 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002149
2150 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002151 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002152 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2153 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002154 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002155 return VersionMismatch;
2156 }
2157 break;
2158 }
2159
Ben Langmuir487ea142014-10-23 18:05:36 +00002160 case SIGNATURE:
2161 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2162 F.Signature = Record[0];
2163 break;
2164
Guy Benyei11169dd2012-12-18 14:30:41 +00002165 case IMPORTS: {
2166 // Load each of the imported PCH files.
2167 unsigned Idx = 0, N = Record.size();
2168 while (Idx < N) {
2169 // Read information about the AST file.
2170 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2171 // The import location will be the local one for now; we will adjust
2172 // all import locations of module imports after the global source
2173 // location info are setup.
2174 SourceLocation ImportLoc =
2175 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002176 off_t StoredSize = (off_t)Record[Idx++];
2177 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002178 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002179 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002180
2181 // Load the AST file.
2182 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00002183 StoredSize, StoredModTime, StoredSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00002184 ClientLoadCapabilities)) {
2185 case Failure: return Failure;
2186 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002187 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002188 case OutOfDate: return OutOfDate;
2189 case VersionMismatch: return VersionMismatch;
2190 case ConfigurationMismatch: return ConfigurationMismatch;
2191 case HadErrors: return HadErrors;
2192 case Success: break;
2193 }
2194 }
2195 break;
2196 }
2197
Richard Smith7f330cd2015-03-18 01:42:29 +00002198 case KNOWN_MODULE_FILES:
2199 break;
2200
Guy Benyei11169dd2012-12-18 14:30:41 +00002201 case LANGUAGE_OPTIONS: {
2202 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002203 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002204 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002205 ParseLanguageOptions(Record, Complain, *Listener,
2206 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002207 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002208 return ConfigurationMismatch;
2209 break;
2210 }
2211
2212 case TARGET_OPTIONS: {
2213 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2214 if (Listener && &F == *ModuleMgr.begin() &&
Chandler Carruth0d745bc2015-03-14 04:47:43 +00002215 ParseTargetOptions(Record, Complain, *Listener,
2216 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002217 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002218 return ConfigurationMismatch;
2219 break;
2220 }
2221
2222 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002223 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002224 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002225 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002226 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002227 !DisableValidation)
2228 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002229 break;
2230 }
2231
2232 case FILE_SYSTEM_OPTIONS: {
2233 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2234 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002235 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002236 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002237 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002238 return ConfigurationMismatch;
2239 break;
2240 }
2241
2242 case HEADER_SEARCH_OPTIONS: {
2243 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2244 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002245 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002246 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002247 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002248 return ConfigurationMismatch;
2249 break;
2250 }
2251
2252 case PREPROCESSOR_OPTIONS: {
2253 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2254 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002255 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002256 ParsePreprocessorOptions(Record, Complain, *Listener,
2257 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002258 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002259 return ConfigurationMismatch;
2260 break;
2261 }
2262
2263 case ORIGINAL_FILE:
2264 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002265 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002266 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002267 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002268 break;
2269
2270 case ORIGINAL_FILE_ID:
2271 F.OriginalSourceFileID = FileID::get(Record[0]);
2272 break;
2273
2274 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002275 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002276 break;
2277
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002278 case MODULE_NAME:
2279 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002280 if (Listener)
2281 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002282 break;
2283
Richard Smith223d3f22014-12-06 03:21:08 +00002284 case MODULE_DIRECTORY: {
2285 assert(!F.ModuleName.empty() &&
2286 "MODULE_DIRECTORY found before MODULE_NAME");
2287 // If we've already loaded a module map file covering this module, we may
2288 // have a better path for it (relative to the current build).
2289 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2290 if (M && M->Directory) {
2291 // If we're implicitly loading a module, the base directory can't
2292 // change between the build and use.
2293 if (F.Kind != MK_ExplicitModule) {
2294 const DirectoryEntry *BuildDir =
2295 PP.getFileManager().getDirectory(Blob);
2296 if (!BuildDir || BuildDir != M->Directory) {
2297 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2298 Diag(diag::err_imported_module_relocated)
2299 << F.ModuleName << Blob << M->Directory->getName();
2300 return OutOfDate;
2301 }
2302 }
2303 F.BaseDirectory = M->Directory->getName();
2304 } else {
2305 F.BaseDirectory = Blob;
2306 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002307 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002308 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002309
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002310 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002311 if (ASTReadResult Result =
2312 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2313 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002314 break;
2315
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002316 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002317 NumInputs = Record[0];
2318 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002319 F.InputFileOffsets =
2320 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002321 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002322 break;
2323 }
2324 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002325}
2326
Ben Langmuir2c9af442014-04-10 17:57:43 +00002327ASTReader::ASTReadResult
2328ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002329 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002330
2331 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2332 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002333 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002334 }
2335
2336 // Read all of the records and blocks for the AST file.
2337 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002338 while (1) {
2339 llvm::BitstreamEntry Entry = Stream.advance();
2340
2341 switch (Entry.Kind) {
2342 case llvm::BitstreamEntry::Error:
2343 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002344 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002345 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002346 // Outside of C++, we do not store a lookup map for the translation unit.
2347 // Instead, mark it as needing a lookup map to be built if this module
2348 // contains any declarations lexically within it (which it always does!).
2349 // This usually has no cost, since we very rarely need the lookup map for
2350 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002351 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002352 if (DC->hasExternalLexicalStorage() &&
2353 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002354 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002355
Ben Langmuir2c9af442014-04-10 17:57:43 +00002356 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002357 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002358 case llvm::BitstreamEntry::SubBlock:
2359 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002360 case DECLTYPES_BLOCK_ID:
2361 // We lazily load the decls block, but we want to set up the
2362 // DeclsCursor cursor to point into it. Clone our current bitcode
2363 // cursor to it, enter the block and read the abbrevs in that block.
2364 // With the main cursor, we just skip over it.
2365 F.DeclsCursor = Stream;
2366 if (Stream.SkipBlock() || // Skip with the main cursor.
2367 // Read the abbrevs.
2368 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2369 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002370 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 }
2372 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002373
Guy Benyei11169dd2012-12-18 14:30:41 +00002374 case PREPROCESSOR_BLOCK_ID:
2375 F.MacroCursor = Stream;
2376 if (!PP.getExternalSource())
2377 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002378
Guy Benyei11169dd2012-12-18 14:30:41 +00002379 if (Stream.SkipBlock() ||
2380 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2381 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002382 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002383 }
2384 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2385 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002386
Guy Benyei11169dd2012-12-18 14:30:41 +00002387 case PREPROCESSOR_DETAIL_BLOCK_ID:
2388 F.PreprocessorDetailCursor = Stream;
2389 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002390 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002391 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002392 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002393 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002394 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002395 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002396 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2397
Guy Benyei11169dd2012-12-18 14:30:41 +00002398 if (!PP.getPreprocessingRecord())
2399 PP.createPreprocessingRecord();
2400 if (!PP.getPreprocessingRecord()->getExternalSource())
2401 PP.getPreprocessingRecord()->SetExternalSource(*this);
2402 break;
2403
2404 case SOURCE_MANAGER_BLOCK_ID:
2405 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002406 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002407 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002408
Guy Benyei11169dd2012-12-18 14:30:41 +00002409 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002410 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2411 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002412 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002413
Guy Benyei11169dd2012-12-18 14:30:41 +00002414 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002415 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002416 if (Stream.SkipBlock() ||
2417 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2418 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002419 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002420 }
2421 CommentsCursors.push_back(std::make_pair(C, &F));
2422 break;
2423 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002424
Guy Benyei11169dd2012-12-18 14:30:41 +00002425 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002426 if (Stream.SkipBlock()) {
2427 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002428 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002429 }
2430 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002431 }
2432 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002433
2434 case llvm::BitstreamEntry::Record:
2435 // The interesting case.
2436 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002437 }
2438
2439 // Read and process a record.
2440 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002441 StringRef Blob;
2442 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002443 default: // Default behavior: ignore.
2444 break;
2445
2446 case TYPE_OFFSET: {
2447 if (F.LocalNumTypes != 0) {
2448 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002449 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002450 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002451 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002452 F.LocalNumTypes = Record[0];
2453 unsigned LocalBaseTypeIndex = Record[1];
2454 F.BaseTypeIndex = getTotalNumTypes();
2455
2456 if (F.LocalNumTypes > 0) {
2457 // Introduce the global -> local mapping for types within this module.
2458 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2459
2460 // Introduce the local -> global mapping for types within this module.
2461 F.TypeRemap.insertOrReplace(
2462 std::make_pair(LocalBaseTypeIndex,
2463 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002464
2465 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002466 }
2467 break;
2468 }
2469
2470 case DECL_OFFSET: {
2471 if (F.LocalNumDecls != 0) {
2472 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002473 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002474 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002475 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002476 F.LocalNumDecls = Record[0];
2477 unsigned LocalBaseDeclID = Record[1];
2478 F.BaseDeclID = getTotalNumDecls();
2479
2480 if (F.LocalNumDecls > 0) {
2481 // Introduce the global -> local mapping for declarations within this
2482 // module.
2483 GlobalDeclMap.insert(
2484 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2485
2486 // Introduce the local -> global mapping for declarations within this
2487 // module.
2488 F.DeclRemap.insertOrReplace(
2489 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2490
2491 // Introduce the global -> local mapping for declarations within this
2492 // module.
2493 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002494
Ben Langmuir52ca6782014-10-20 16:27:32 +00002495 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2496 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002497 break;
2498 }
2499
2500 case TU_UPDATE_LEXICAL: {
2501 DeclContext *TU = Context.getTranslationUnitDecl();
2502 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002503 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002504 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002505 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002506 TU->setHasExternalLexicalStorage(true);
2507 break;
2508 }
2509
2510 case UPDATE_VISIBLE: {
2511 unsigned Idx = 0;
2512 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2513 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002514 ASTDeclContextNameLookupTable::Create(
2515 (const unsigned char *)Blob.data() + Record[Idx++],
2516 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2517 (const unsigned char *)Blob.data(),
2518 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002519 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002520 auto *DC = cast<DeclContext>(D);
2521 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002522 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2523 delete LookupTable;
2524 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002525 } else
2526 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2527 break;
2528 }
2529
2530 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002531 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002532 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002533 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2534 (const unsigned char *)F.IdentifierTableData + Record[0],
2535 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2536 (const unsigned char *)F.IdentifierTableData,
2537 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002538
2539 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2540 }
2541 break;
2542
2543 case IDENTIFIER_OFFSET: {
2544 if (F.LocalNumIdentifiers != 0) {
2545 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002546 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002547 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002548 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002549 F.LocalNumIdentifiers = Record[0];
2550 unsigned LocalBaseIdentifierID = Record[1];
2551 F.BaseIdentifierID = getTotalNumIdentifiers();
2552
2553 if (F.LocalNumIdentifiers > 0) {
2554 // Introduce the global -> local mapping for identifiers within this
2555 // module.
2556 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2557 &F));
2558
2559 // Introduce the local -> global mapping for identifiers within this
2560 // module.
2561 F.IdentifierRemap.insertOrReplace(
2562 std::make_pair(LocalBaseIdentifierID,
2563 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002564
Ben Langmuir52ca6782014-10-20 16:27:32 +00002565 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2566 + F.LocalNumIdentifiers);
2567 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002568 break;
2569 }
2570
Ben Langmuir332aafe2014-01-31 01:06:56 +00002571 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002572 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2573 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002574 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002575 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002576 break;
2577
2578 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002579 if (SpecialTypes.empty()) {
2580 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2581 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2582 break;
2583 }
2584
2585 if (SpecialTypes.size() != Record.size()) {
2586 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002587 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002588 }
2589
2590 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2591 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2592 if (!SpecialTypes[I])
2593 SpecialTypes[I] = ID;
2594 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2595 // merge step?
2596 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002597 break;
2598
2599 case STATISTICS:
2600 TotalNumStatements += Record[0];
2601 TotalNumMacros += Record[1];
2602 TotalLexicalDeclContexts += Record[2];
2603 TotalVisibleDeclContexts += Record[3];
2604 break;
2605
2606 case UNUSED_FILESCOPED_DECLS:
2607 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2608 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2609 break;
2610
2611 case DELEGATING_CTORS:
2612 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2613 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2614 break;
2615
2616 case WEAK_UNDECLARED_IDENTIFIERS:
2617 if (Record.size() % 4 != 0) {
2618 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002619 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002620 }
2621
2622 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2623 // files. This isn't the way to do it :)
2624 WeakUndeclaredIdentifiers.clear();
2625
2626 // Translate the weak, undeclared identifiers into global IDs.
2627 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2628 WeakUndeclaredIdentifiers.push_back(
2629 getGlobalIdentifierID(F, Record[I++]));
2630 WeakUndeclaredIdentifiers.push_back(
2631 getGlobalIdentifierID(F, Record[I++]));
2632 WeakUndeclaredIdentifiers.push_back(
2633 ReadSourceLocation(F, Record, I).getRawEncoding());
2634 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2635 }
2636 break;
2637
Guy Benyei11169dd2012-12-18 14:30:41 +00002638 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002639 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002640 F.LocalNumSelectors = Record[0];
2641 unsigned LocalBaseSelectorID = Record[1];
2642 F.BaseSelectorID = getTotalNumSelectors();
2643
2644 if (F.LocalNumSelectors > 0) {
2645 // Introduce the global -> local mapping for selectors within this
2646 // module.
2647 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2648
2649 // Introduce the local -> global mapping for selectors within this
2650 // module.
2651 F.SelectorRemap.insertOrReplace(
2652 std::make_pair(LocalBaseSelectorID,
2653 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002654
2655 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002656 }
2657 break;
2658 }
2659
2660 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002661 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002662 if (Record[0])
2663 F.SelectorLookupTable
2664 = ASTSelectorLookupTable::Create(
2665 F.SelectorLookupTableData + Record[0],
2666 F.SelectorLookupTableData,
2667 ASTSelectorLookupTrait(*this, F));
2668 TotalNumMethodPoolEntries += Record[1];
2669 break;
2670
2671 case REFERENCED_SELECTOR_POOL:
2672 if (!Record.empty()) {
2673 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2674 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2675 Record[Idx++]));
2676 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2677 getRawEncoding());
2678 }
2679 }
2680 break;
2681
2682 case PP_COUNTER_VALUE:
2683 if (!Record.empty() && Listener)
2684 Listener->ReadCounter(F, Record[0]);
2685 break;
2686
2687 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002688 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002689 F.NumFileSortedDecls = Record[0];
2690 break;
2691
2692 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002693 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002694 F.LocalNumSLocEntries = Record[0];
2695 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002696 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002697 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002698 SLocSpaceSize);
2699 // Make our entry in the range map. BaseID is negative and growing, so
2700 // we invert it. Because we invert it, though, we need the other end of
2701 // the range.
2702 unsigned RangeStart =
2703 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2704 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2705 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2706
2707 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2708 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2709 GlobalSLocOffsetMap.insert(
2710 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2711 - SLocSpaceSize,&F));
2712
2713 // Initialize the remapping table.
2714 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002715 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002716 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002717 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002718 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2719
2720 TotalNumSLocEntries += F.LocalNumSLocEntries;
2721 break;
2722 }
2723
2724 case MODULE_OFFSET_MAP: {
2725 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002726 const unsigned char *Data = (const unsigned char*)Blob.data();
2727 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002728
2729 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2730 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2731 F.SLocRemap.insert(std::make_pair(0U, 0));
2732 F.SLocRemap.insert(std::make_pair(2U, 1));
2733 }
2734
Guy Benyei11169dd2012-12-18 14:30:41 +00002735 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002736 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2737 RemapBuilder;
2738 RemapBuilder SLocRemap(F.SLocRemap);
2739 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2740 RemapBuilder MacroRemap(F.MacroRemap);
2741 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2742 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2743 RemapBuilder SelectorRemap(F.SelectorRemap);
2744 RemapBuilder DeclRemap(F.DeclRemap);
2745 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002746
2747 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002748 using namespace llvm::support;
2749 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002750 StringRef Name = StringRef((const char*)Data, Len);
2751 Data += Len;
2752 ModuleFile *OM = ModuleMgr.lookup(Name);
2753 if (!OM) {
2754 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002755 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002756 }
2757
Justin Bogner57ba0b22014-03-28 22:03:24 +00002758 uint32_t SLocOffset =
2759 endian::readNext<uint32_t, little, unaligned>(Data);
2760 uint32_t IdentifierIDOffset =
2761 endian::readNext<uint32_t, little, unaligned>(Data);
2762 uint32_t MacroIDOffset =
2763 endian::readNext<uint32_t, little, unaligned>(Data);
2764 uint32_t PreprocessedEntityIDOffset =
2765 endian::readNext<uint32_t, little, unaligned>(Data);
2766 uint32_t SubmoduleIDOffset =
2767 endian::readNext<uint32_t, little, unaligned>(Data);
2768 uint32_t SelectorIDOffset =
2769 endian::readNext<uint32_t, little, unaligned>(Data);
2770 uint32_t DeclIDOffset =
2771 endian::readNext<uint32_t, little, unaligned>(Data);
2772 uint32_t TypeIndexOffset =
2773 endian::readNext<uint32_t, little, unaligned>(Data);
2774
Ben Langmuir785180e2014-10-20 16:27:30 +00002775 uint32_t None = std::numeric_limits<uint32_t>::max();
2776
2777 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2778 RemapBuilder &Remap) {
2779 if (Offset != None)
2780 Remap.insert(std::make_pair(Offset,
2781 static_cast<int>(BaseOffset - Offset)));
2782 };
2783 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2784 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2785 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2786 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2787 PreprocessedEntityRemap);
2788 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2789 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2790 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2791 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002792
2793 // Global -> local mappings.
2794 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2795 }
2796 break;
2797 }
2798
2799 case SOURCE_MANAGER_LINE_TABLE:
2800 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002801 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002802 break;
2803
2804 case SOURCE_LOCATION_PRELOADS: {
2805 // Need to transform from the local view (1-based IDs) to the global view,
2806 // which is based off F.SLocEntryBaseID.
2807 if (!F.PreloadSLocEntries.empty()) {
2808 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002809 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002810 }
2811
2812 F.PreloadSLocEntries.swap(Record);
2813 break;
2814 }
2815
2816 case EXT_VECTOR_DECLS:
2817 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2818 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2819 break;
2820
2821 case VTABLE_USES:
2822 if (Record.size() % 3 != 0) {
2823 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002824 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002825 }
2826
2827 // Later tables overwrite earlier ones.
2828 // FIXME: Modules will have some trouble with this. This is clearly not
2829 // the right way to do this.
2830 VTableUses.clear();
2831
2832 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2833 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2834 VTableUses.push_back(
2835 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2836 VTableUses.push_back(Record[Idx++]);
2837 }
2838 break;
2839
Guy Benyei11169dd2012-12-18 14:30:41 +00002840 case PENDING_IMPLICIT_INSTANTIATIONS:
2841 if (PendingInstantiations.size() % 2 != 0) {
2842 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002843 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002844 }
2845
2846 if (Record.size() % 2 != 0) {
2847 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002848 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002849 }
2850
2851 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2852 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2853 PendingInstantiations.push_back(
2854 ReadSourceLocation(F, Record, I).getRawEncoding());
2855 }
2856 break;
2857
2858 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002859 if (Record.size() != 2) {
2860 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002861 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002862 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002863 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2864 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2865 break;
2866
2867 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002868 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2869 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2870 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002871
2872 unsigned LocalBasePreprocessedEntityID = Record[0];
2873
2874 unsigned StartingID;
2875 if (!PP.getPreprocessingRecord())
2876 PP.createPreprocessingRecord();
2877 if (!PP.getPreprocessingRecord()->getExternalSource())
2878 PP.getPreprocessingRecord()->SetExternalSource(*this);
2879 StartingID
2880 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00002881 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00002882 F.BasePreprocessedEntityID = StartingID;
2883
2884 if (F.NumPreprocessedEntities > 0) {
2885 // Introduce the global -> local mapping for preprocessed entities in
2886 // this module.
2887 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2888
2889 // Introduce the local -> global mapping for preprocessed entities in
2890 // this module.
2891 F.PreprocessedEntityRemap.insertOrReplace(
2892 std::make_pair(LocalBasePreprocessedEntityID,
2893 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2894 }
2895
2896 break;
2897 }
2898
2899 case DECL_UPDATE_OFFSETS: {
2900 if (Record.size() % 2 != 0) {
2901 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002902 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002903 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00002904 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
2905 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
2906 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
2907
2908 // If we've already loaded the decl, perform the updates when we finish
2909 // loading this block.
2910 if (Decl *D = GetExistingDecl(ID))
2911 PendingUpdateRecords.push_back(std::make_pair(ID, D));
2912 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002913 break;
2914 }
2915
2916 case DECL_REPLACEMENTS: {
2917 if (Record.size() % 3 != 0) {
2918 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002919 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002920 }
2921 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2922 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2923 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2924 break;
2925 }
2926
2927 case OBJC_CATEGORIES_MAP: {
2928 if (F.LocalNumObjCCategoriesInMap != 0) {
2929 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002930 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002931 }
2932
2933 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002934 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002935 break;
2936 }
2937
2938 case OBJC_CATEGORIES:
2939 F.ObjCCategories.swap(Record);
2940 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00002941
Guy Benyei11169dd2012-12-18 14:30:41 +00002942 case CXX_BASE_SPECIFIER_OFFSETS: {
2943 if (F.LocalNumCXXBaseSpecifiers != 0) {
2944 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002945 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002946 }
Richard Smithc2bb8182015-03-24 06:36:48 +00002947
Guy Benyei11169dd2012-12-18 14:30:41 +00002948 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002949 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00002950 break;
2951 }
2952
2953 case CXX_CTOR_INITIALIZERS_OFFSETS: {
2954 if (F.LocalNumCXXCtorInitializers != 0) {
2955 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
2956 return Failure;
2957 }
2958
2959 F.LocalNumCXXCtorInitializers = Record[0];
2960 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002961 break;
2962 }
2963
2964 case DIAG_PRAGMA_MAPPINGS:
2965 if (F.PragmaDiagMappings.empty())
2966 F.PragmaDiagMappings.swap(Record);
2967 else
2968 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2969 Record.begin(), Record.end());
2970 break;
2971
2972 case CUDA_SPECIAL_DECL_REFS:
2973 // Later tables overwrite earlier ones.
2974 // FIXME: Modules will have trouble with this.
2975 CUDASpecialDeclRefs.clear();
2976 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2977 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2978 break;
2979
2980 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002981 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002982 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00002983 if (Record[0]) {
2984 F.HeaderFileInfoTable
2985 = HeaderFileInfoLookupTable::Create(
2986 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2987 (const unsigned char *)F.HeaderFileInfoTableData,
2988 HeaderFileInfoTrait(*this, F,
2989 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00002990 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002991
2992 PP.getHeaderSearchInfo().SetExternalSource(this);
2993 if (!PP.getHeaderSearchInfo().getExternalLookup())
2994 PP.getHeaderSearchInfo().SetExternalLookup(this);
2995 }
2996 break;
2997 }
2998
2999 case FP_PRAGMA_OPTIONS:
3000 // Later tables overwrite earlier ones.
3001 FPPragmaOptions.swap(Record);
3002 break;
3003
3004 case OPENCL_EXTENSIONS:
3005 // Later tables overwrite earlier ones.
3006 OpenCLExtensions.swap(Record);
3007 break;
3008
3009 case TENTATIVE_DEFINITIONS:
3010 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3011 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3012 break;
3013
3014 case KNOWN_NAMESPACES:
3015 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3016 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3017 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003018
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003019 case UNDEFINED_BUT_USED:
3020 if (UndefinedButUsed.size() % 2 != 0) {
3021 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003022 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003023 }
3024
3025 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003026 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003027 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003028 }
3029 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003030 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3031 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003032 ReadSourceLocation(F, Record, I).getRawEncoding());
3033 }
3034 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003035 case DELETE_EXPRS_TO_ANALYZE:
3036 for (unsigned I = 0, N = Record.size(); I != N;) {
3037 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3038 const uint64_t Count = Record[I++];
3039 DelayedDeleteExprs.push_back(Count);
3040 for (uint64_t C = 0; C < Count; ++C) {
3041 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3042 bool IsArrayForm = Record[I++] == 1;
3043 DelayedDeleteExprs.push_back(IsArrayForm);
3044 }
3045 }
3046 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003047
Guy Benyei11169dd2012-12-18 14:30:41 +00003048 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003049 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003050 // If we aren't loading a module (which has its own exports), make
3051 // all of the imported modules visible.
3052 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003053 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3054 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3055 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3056 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003057 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003058 }
3059 }
3060 break;
3061 }
3062
3063 case LOCAL_REDECLARATIONS: {
3064 F.RedeclarationChains.swap(Record);
3065 break;
3066 }
3067
3068 case LOCAL_REDECLARATIONS_MAP: {
3069 if (F.LocalNumRedeclarationsInMap != 0) {
3070 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003071 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003072 }
3073
3074 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003075 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003076 break;
3077 }
3078
Guy Benyei11169dd2012-12-18 14:30:41 +00003079 case MACRO_OFFSET: {
3080 if (F.LocalNumMacros != 0) {
3081 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003082 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003083 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003084 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003085 F.LocalNumMacros = Record[0];
3086 unsigned LocalBaseMacroID = Record[1];
3087 F.BaseMacroID = getTotalNumMacros();
3088
3089 if (F.LocalNumMacros > 0) {
3090 // Introduce the global -> local mapping for macros within this module.
3091 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3092
3093 // Introduce the local -> global mapping for macros within this module.
3094 F.MacroRemap.insertOrReplace(
3095 std::make_pair(LocalBaseMacroID,
3096 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003097
3098 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003099 }
3100 break;
3101 }
3102
Richard Smithe40f2ba2013-08-07 21:41:30 +00003103 case LATE_PARSED_TEMPLATE: {
3104 LateParsedTemplates.append(Record.begin(), Record.end());
3105 break;
3106 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003107
3108 case OPTIMIZE_PRAGMA_OPTIONS:
3109 if (Record.size() != 1) {
3110 Error("invalid pragma optimize record");
3111 return Failure;
3112 }
3113 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3114 break;
Nico Weber72889432014-09-06 01:25:55 +00003115
3116 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3117 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3118 UnusedLocalTypedefNameCandidates.push_back(
3119 getGlobalDeclID(F, Record[I]));
3120 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003121 }
3122 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003123}
3124
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003125ASTReader::ASTReadResult
3126ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3127 const ModuleFile *ImportedBy,
3128 unsigned ClientLoadCapabilities) {
3129 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003130 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003131
Richard Smithe842a472014-10-22 02:05:46 +00003132 if (F.Kind == MK_ExplicitModule) {
3133 // For an explicitly-loaded module, we don't care whether the original
3134 // module map file exists or matches.
3135 return Success;
3136 }
3137
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003138 // Try to resolve ModuleName in the current header search context and
3139 // verify that it is found in the same module map file as we saved. If the
3140 // top-level AST file is a main file, skip this check because there is no
3141 // usable header search context.
3142 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003143 "MODULE_NAME should come before MODULE_MAP_FILE");
3144 if (F.Kind == MK_ImplicitModule &&
3145 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3146 // An implicitly-loaded module file should have its module listed in some
3147 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003148 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003149 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3150 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3151 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003152 assert(ImportedBy && "top-level import should be verified");
3153 if ((ClientLoadCapabilities & ARR_Missing) == 0)
Richard Smithe842a472014-10-22 02:05:46 +00003154 Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3155 << ImportedBy->FileName
3156 << F.ModuleMapPath;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003157 return Missing;
3158 }
3159
Richard Smithe842a472014-10-22 02:05:46 +00003160 assert(M->Name == F.ModuleName && "found module with different name");
3161
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003162 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003163 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003164 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3165 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003166 assert(ImportedBy && "top-level import should be verified");
3167 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3168 Diag(diag::err_imported_module_modmap_changed)
3169 << F.ModuleName << ImportedBy->FileName
3170 << ModMap->getName() << F.ModuleMapPath;
3171 return OutOfDate;
3172 }
3173
3174 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3175 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3176 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003177 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003178 const FileEntry *F =
3179 FileMgr.getFile(Filename, false, false);
3180 if (F == nullptr) {
3181 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3182 Error("could not find file '" + Filename +"' referenced by AST file");
3183 return OutOfDate;
3184 }
3185 AdditionalStoredMaps.insert(F);
3186 }
3187
3188 // Check any additional module map files (e.g. module.private.modulemap)
3189 // that are not in the pcm.
3190 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3191 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3192 // Remove files that match
3193 // Note: SmallPtrSet::erase is really remove
3194 if (!AdditionalStoredMaps.erase(ModMap)) {
3195 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3196 Diag(diag::err_module_different_modmap)
3197 << F.ModuleName << /*new*/0 << ModMap->getName();
3198 return OutOfDate;
3199 }
3200 }
3201 }
3202
3203 // Check any additional module map files that are in the pcm, but not
3204 // found in header search. Cases that match are already removed.
3205 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3206 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3207 Diag(diag::err_module_different_modmap)
3208 << F.ModuleName << /*not new*/1 << ModMap->getName();
3209 return OutOfDate;
3210 }
3211 }
3212
3213 if (Listener)
3214 Listener->ReadModuleMapFile(F.ModuleMapPath);
3215 return Success;
3216}
3217
3218
Douglas Gregorc1489562013-02-12 23:36:21 +00003219/// \brief Move the given method to the back of the global list of methods.
3220static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3221 // Find the entry for this selector in the method pool.
3222 Sema::GlobalMethodPool::iterator Known
3223 = S.MethodPool.find(Method->getSelector());
3224 if (Known == S.MethodPool.end())
3225 return;
3226
3227 // Retrieve the appropriate method list.
3228 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3229 : Known->second.second;
3230 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003231 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003232 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003233 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003234 Found = true;
3235 } else {
3236 // Keep searching.
3237 continue;
3238 }
3239 }
3240
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003241 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003242 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003243 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003244 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003245 }
3246}
3247
Richard Smithde711422015-04-23 21:20:19 +00003248void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003249 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003250 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003251 bool wasHidden = D->Hidden;
3252 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003253
Richard Smith49f906a2014-03-01 00:08:04 +00003254 if (wasHidden && SemaObj) {
3255 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3256 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003257 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003258 }
3259 }
3260}
3261
Richard Smith49f906a2014-03-01 00:08:04 +00003262void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003263 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003264 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003265 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003266 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003267 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003268 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003269 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003270
3271 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003272 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003273 // there is nothing more to do.
3274 continue;
3275 }
Richard Smith49f906a2014-03-01 00:08:04 +00003276
Guy Benyei11169dd2012-12-18 14:30:41 +00003277 if (!Mod->isAvailable()) {
3278 // Modules that aren't available cannot be made visible.
3279 continue;
3280 }
3281
3282 // Update the module's name visibility.
3283 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003284
Guy Benyei11169dd2012-12-18 14:30:41 +00003285 // If we've already deserialized any names from this module,
3286 // mark them as visible.
3287 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3288 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003289 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003290 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003291 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003292 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3293 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003294 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003295
Guy Benyei11169dd2012-12-18 14:30:41 +00003296 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003297 SmallVector<Module *, 16> Exports;
3298 Mod->getExportedModules(Exports);
3299 for (SmallVectorImpl<Module *>::iterator
3300 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3301 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003302 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003303 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003304 }
3305 }
3306}
3307
Douglas Gregore060e572013-01-25 01:03:03 +00003308bool ASTReader::loadGlobalIndex() {
3309 if (GlobalIndex)
3310 return false;
3311
3312 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3313 !Context.getLangOpts().Modules)
3314 return true;
3315
3316 // Try to load the global index.
3317 TriedLoadingGlobalIndex = true;
3318 StringRef ModuleCachePath
3319 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3320 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003321 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003322 if (!Result.first)
3323 return true;
3324
3325 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003326 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003327 return false;
3328}
3329
3330bool ASTReader::isGlobalIndexUnavailable() const {
3331 return Context.getLangOpts().Modules && UseGlobalIndex &&
3332 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3333}
3334
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003335static void updateModuleTimestamp(ModuleFile &MF) {
3336 // Overwrite the timestamp file contents so that file's mtime changes.
3337 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003338 std::error_code EC;
3339 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3340 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003341 return;
3342 OS << "Timestamp file\n";
3343}
3344
Guy Benyei11169dd2012-12-18 14:30:41 +00003345ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3346 ModuleKind Type,
3347 SourceLocation ImportLoc,
3348 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003349 llvm::SaveAndRestore<SourceLocation>
3350 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3351
Richard Smithd1c46742014-04-30 02:24:17 +00003352 // Defer any pending actions until we get to the end of reading the AST file.
3353 Deserializing AnASTFile(this);
3354
Guy Benyei11169dd2012-12-18 14:30:41 +00003355 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003356 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003357
3358 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003359 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003360 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003361 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003362 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003363 ClientLoadCapabilities)) {
3364 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003365 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003366 case OutOfDate:
3367 case VersionMismatch:
3368 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003369 case HadErrors: {
3370 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3371 for (const ImportedModule &IM : Loaded)
3372 LoadedSet.insert(IM.Mod);
3373
Douglas Gregor7029ce12013-03-19 00:28:20 +00003374 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003375 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003376 Context.getLangOpts().Modules
3377 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003378 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003379
3380 // If we find that any modules are unusable, the global index is going
3381 // to be out-of-date. Just remove it.
3382 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003383 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003384 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003385 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003386 case Success:
3387 break;
3388 }
3389
3390 // Here comes stuff that we only do once the entire chain is loaded.
3391
3392 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003393 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3394 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003395 M != MEnd; ++M) {
3396 ModuleFile &F = *M->Mod;
3397
3398 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003399 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3400 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003401
3402 // Once read, set the ModuleFile bit base offset and update the size in
3403 // bits of all files we've seen.
3404 F.GlobalBitOffset = TotalModulesSizeInBits;
3405 TotalModulesSizeInBits += F.SizeInBits;
3406 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3407
3408 // Preload SLocEntries.
3409 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3410 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3411 // Load it through the SourceManager and don't call ReadSLocEntry()
3412 // directly because the entry may have already been loaded in which case
3413 // calling ReadSLocEntry() directly would trigger an assertion in
3414 // SourceManager.
3415 SourceMgr.getLoadedSLocEntryByID(Index);
3416 }
3417 }
3418
Douglas Gregor603cd862013-03-22 18:50:14 +00003419 // Setup the import locations and notify the module manager that we've
3420 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003421 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3422 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003423 M != MEnd; ++M) {
3424 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003425
3426 ModuleMgr.moduleFileAccepted(&F);
3427
3428 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003429 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003430 if (!M->ImportedBy)
3431 F.ImportLoc = M->ImportLoc;
3432 else
3433 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3434 M->ImportLoc.getRawEncoding());
3435 }
3436
3437 // Mark all of the identifiers in the identifier table as being out of date,
3438 // so that various accessors know to check the loaded modules when the
3439 // identifier is used.
3440 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3441 IdEnd = PP.getIdentifierTable().end();
3442 Id != IdEnd; ++Id)
3443 Id->second->setOutOfDate(true);
3444
3445 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003446 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3447 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003448 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3449 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003450
3451 switch (Unresolved.Kind) {
3452 case UnresolvedModuleRef::Conflict:
3453 if (ResolvedMod) {
3454 Module::Conflict Conflict;
3455 Conflict.Other = ResolvedMod;
3456 Conflict.Message = Unresolved.String.str();
3457 Unresolved.Mod->Conflicts.push_back(Conflict);
3458 }
3459 continue;
3460
3461 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003462 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003463 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003464 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003465
Douglas Gregorfb912652013-03-20 21:10:35 +00003466 case UnresolvedModuleRef::Export:
3467 if (ResolvedMod || Unresolved.IsWildcard)
3468 Unresolved.Mod->Exports.push_back(
3469 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3470 continue;
3471 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003472 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003473 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003474
3475 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3476 // Might be unnecessary as use declarations are only used to build the
3477 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003478
3479 InitializeContext();
3480
Richard Smith3d8e97e2013-10-18 06:54:39 +00003481 if (SemaObj)
3482 UpdateSema();
3483
Guy Benyei11169dd2012-12-18 14:30:41 +00003484 if (DeserializationListener)
3485 DeserializationListener->ReaderInitialized(this);
3486
3487 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3488 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3489 PrimaryModule.OriginalSourceFileID
3490 = FileID::get(PrimaryModule.SLocEntryBaseID
3491 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3492
3493 // If this AST file is a precompiled preamble, then set the
3494 // preamble file ID of the source manager to the file source file
3495 // from which the preamble was built.
3496 if (Type == MK_Preamble) {
3497 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3498 } else if (Type == MK_MainFile) {
3499 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3500 }
3501 }
3502
3503 // For any Objective-C class definitions we have already loaded, make sure
3504 // that we load any additional categories.
3505 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3506 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3507 ObjCClassesLoaded[I],
3508 PreviousGeneration);
3509 }
Douglas Gregore060e572013-01-25 01:03:03 +00003510
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003511 if (PP.getHeaderSearchInfo()
3512 .getHeaderSearchOpts()
3513 .ModulesValidateOncePerBuildSession) {
3514 // Now we are certain that the module and all modules it depends on are
3515 // up to date. Create or update timestamp files for modules that are
3516 // located in the module cache (not for PCH files that could be anywhere
3517 // in the filesystem).
3518 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3519 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003520 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003521 updateModuleTimestamp(*M.Mod);
3522 }
3523 }
3524 }
3525
Guy Benyei11169dd2012-12-18 14:30:41 +00003526 return Success;
3527}
3528
Ben Langmuir487ea142014-10-23 18:05:36 +00003529static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3530
Ben Langmuir70a1b812015-03-24 04:43:52 +00003531/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3532static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3533 return Stream.Read(8) == 'C' &&
3534 Stream.Read(8) == 'P' &&
3535 Stream.Read(8) == 'C' &&
3536 Stream.Read(8) == 'H';
3537}
3538
Guy Benyei11169dd2012-12-18 14:30:41 +00003539ASTReader::ASTReadResult
3540ASTReader::ReadASTCore(StringRef FileName,
3541 ModuleKind Type,
3542 SourceLocation ImportLoc,
3543 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003544 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003545 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003546 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003547 unsigned ClientLoadCapabilities) {
3548 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003549 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003550 ModuleManager::AddModuleResult AddResult
3551 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003552 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003553 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003554 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003555
Douglas Gregor7029ce12013-03-19 00:28:20 +00003556 switch (AddResult) {
3557 case ModuleManager::AlreadyLoaded:
3558 return Success;
3559
3560 case ModuleManager::NewlyLoaded:
3561 // Load module file below.
3562 break;
3563
3564 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003565 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003566 // it.
3567 if (ClientLoadCapabilities & ARR_Missing)
3568 return Missing;
3569
3570 // Otherwise, return an error.
3571 {
3572 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3573 + ErrorStr;
3574 Error(Msg);
3575 }
3576 return Failure;
3577
3578 case ModuleManager::OutOfDate:
3579 // We couldn't load the module file because it is out-of-date. If the
3580 // client can handle out-of-date, return it.
3581 if (ClientLoadCapabilities & ARR_OutOfDate)
3582 return OutOfDate;
3583
3584 // Otherwise, return an error.
3585 {
3586 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3587 + ErrorStr;
3588 Error(Msg);
3589 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003590 return Failure;
3591 }
3592
Douglas Gregor7029ce12013-03-19 00:28:20 +00003593 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003594
3595 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3596 // module?
3597 if (FileName != "-") {
3598 CurrentDir = llvm::sys::path::parent_path(FileName);
3599 if (CurrentDir.empty()) CurrentDir = ".";
3600 }
3601
3602 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003603 BitstreamCursor &Stream = F.Stream;
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003604 PCHContainerOps.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003605 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003606 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3607
Guy Benyei11169dd2012-12-18 14:30:41 +00003608 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003609 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003610 Diag(diag::err_not_a_pch_file) << FileName;
3611 return Failure;
3612 }
3613
3614 // This is used for compatibility with older PCH formats.
3615 bool HaveReadControlBlock = false;
3616
Chris Lattnerefa77172013-01-20 00:00:22 +00003617 while (1) {
3618 llvm::BitstreamEntry Entry = Stream.advance();
3619
3620 switch (Entry.Kind) {
3621 case llvm::BitstreamEntry::Error:
3622 case llvm::BitstreamEntry::EndBlock:
3623 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003624 Error("invalid record at top-level of AST file");
3625 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003626
3627 case llvm::BitstreamEntry::SubBlock:
3628 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003629 }
3630
Guy Benyei11169dd2012-12-18 14:30:41 +00003631 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003632 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003633 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3634 if (Stream.ReadBlockInfoBlock()) {
3635 Error("malformed BlockInfoBlock in AST file");
3636 return Failure;
3637 }
3638 break;
3639 case CONTROL_BLOCK_ID:
3640 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003641 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003642 case Success:
3643 break;
3644
3645 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003646 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003647 case OutOfDate: return OutOfDate;
3648 case VersionMismatch: return VersionMismatch;
3649 case ConfigurationMismatch: return ConfigurationMismatch;
3650 case HadErrors: return HadErrors;
3651 }
3652 break;
3653 case AST_BLOCK_ID:
3654 if (!HaveReadControlBlock) {
3655 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003656 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003657 return VersionMismatch;
3658 }
3659
3660 // Record that we've loaded this module.
3661 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3662 return Success;
3663
3664 default:
3665 if (Stream.SkipBlock()) {
3666 Error("malformed block record in AST file");
3667 return Failure;
3668 }
3669 break;
3670 }
3671 }
3672
3673 return Success;
3674}
3675
Richard Smitha7e2cc62015-05-01 01:53:09 +00003676void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003677 // If there's a listener, notify them that we "read" the translation unit.
3678 if (DeserializationListener)
3679 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3680 Context.getTranslationUnitDecl());
3681
Guy Benyei11169dd2012-12-18 14:30:41 +00003682 // FIXME: Find a better way to deal with collisions between these
3683 // built-in types. Right now, we just ignore the problem.
3684
3685 // Load the special types.
3686 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3687 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3688 if (!Context.CFConstantStringTypeDecl)
3689 Context.setCFConstantStringType(GetType(String));
3690 }
3691
3692 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3693 QualType FileType = GetType(File);
3694 if (FileType.isNull()) {
3695 Error("FILE type is NULL");
3696 return;
3697 }
3698
3699 if (!Context.FILEDecl) {
3700 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3701 Context.setFILEDecl(Typedef->getDecl());
3702 else {
3703 const TagType *Tag = FileType->getAs<TagType>();
3704 if (!Tag) {
3705 Error("Invalid FILE type in AST file");
3706 return;
3707 }
3708 Context.setFILEDecl(Tag->getDecl());
3709 }
3710 }
3711 }
3712
3713 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3714 QualType Jmp_bufType = GetType(Jmp_buf);
3715 if (Jmp_bufType.isNull()) {
3716 Error("jmp_buf type is NULL");
3717 return;
3718 }
3719
3720 if (!Context.jmp_bufDecl) {
3721 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3722 Context.setjmp_bufDecl(Typedef->getDecl());
3723 else {
3724 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3725 if (!Tag) {
3726 Error("Invalid jmp_buf type in AST file");
3727 return;
3728 }
3729 Context.setjmp_bufDecl(Tag->getDecl());
3730 }
3731 }
3732 }
3733
3734 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3735 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3736 if (Sigjmp_bufType.isNull()) {
3737 Error("sigjmp_buf type is NULL");
3738 return;
3739 }
3740
3741 if (!Context.sigjmp_bufDecl) {
3742 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3743 Context.setsigjmp_bufDecl(Typedef->getDecl());
3744 else {
3745 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3746 assert(Tag && "Invalid sigjmp_buf type in AST file");
3747 Context.setsigjmp_bufDecl(Tag->getDecl());
3748 }
3749 }
3750 }
3751
3752 if (unsigned ObjCIdRedef
3753 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3754 if (Context.ObjCIdRedefinitionType.isNull())
3755 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3756 }
3757
3758 if (unsigned ObjCClassRedef
3759 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3760 if (Context.ObjCClassRedefinitionType.isNull())
3761 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3762 }
3763
3764 if (unsigned ObjCSelRedef
3765 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3766 if (Context.ObjCSelRedefinitionType.isNull())
3767 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3768 }
3769
3770 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3771 QualType Ucontext_tType = GetType(Ucontext_t);
3772 if (Ucontext_tType.isNull()) {
3773 Error("ucontext_t type is NULL");
3774 return;
3775 }
3776
3777 if (!Context.ucontext_tDecl) {
3778 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3779 Context.setucontext_tDecl(Typedef->getDecl());
3780 else {
3781 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3782 assert(Tag && "Invalid ucontext_t type in AST file");
3783 Context.setucontext_tDecl(Tag->getDecl());
3784 }
3785 }
3786 }
3787 }
3788
3789 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3790
3791 // If there were any CUDA special declarations, deserialize them.
3792 if (!CUDASpecialDeclRefs.empty()) {
3793 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3794 Context.setcudaConfigureCallDecl(
3795 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3796 }
Richard Smith56be7542014-03-21 00:33:59 +00003797
Guy Benyei11169dd2012-12-18 14:30:41 +00003798 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00003799 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00003800 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00003801 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003802 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003803 /*ImportLoc=*/Import.ImportLoc);
3804 PP.makeModuleVisible(Imported, Import.ImportLoc);
3805 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003806 }
3807 ImportedModules.clear();
3808}
3809
3810void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00003811 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00003812}
3813
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003814/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3815/// cursor into the start of the given block ID, returning false on success and
3816/// true on failure.
3817static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003818 while (1) {
3819 llvm::BitstreamEntry Entry = Cursor.advance();
3820 switch (Entry.Kind) {
3821 case llvm::BitstreamEntry::Error:
3822 case llvm::BitstreamEntry::EndBlock:
3823 return true;
3824
3825 case llvm::BitstreamEntry::Record:
3826 // Ignore top-level records.
3827 Cursor.skipRecord(Entry.ID);
3828 break;
3829
3830 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003831 if (Entry.ID == BlockID) {
3832 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003833 return true;
3834 // Found it!
3835 return false;
3836 }
3837
3838 if (Cursor.SkipBlock())
3839 return true;
3840 }
3841 }
3842}
3843
Ben Langmuir70a1b812015-03-24 04:43:52 +00003844/// \brief Reads and return the signature record from \p StreamFile's control
3845/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00003846static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
3847 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00003848 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00003849 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00003850
3851 // Scan for the CONTROL_BLOCK_ID block.
3852 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
3853 return 0;
3854
3855 // Scan for SIGNATURE inside the control block.
3856 ASTReader::RecordData Record;
3857 while (1) {
3858 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3859 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
3860 Entry.Kind != llvm::BitstreamEntry::Record)
3861 return 0;
3862
3863 Record.clear();
3864 StringRef Blob;
3865 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
3866 return Record[0];
3867 }
3868}
3869
Guy Benyei11169dd2012-12-18 14:30:41 +00003870/// \brief Retrieve the name of the original source file name
3871/// directly from the AST file, without actually loading the AST
3872/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003873std::string ASTReader::getOriginalSourceFile(
3874 const std::string &ASTFileName, FileManager &FileMgr,
3875 const PCHContainerOperations &PCHContainerOps, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003876 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00003877 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00003878 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00003879 Diags.Report(diag::err_fe_unable_to_read_pch_file)
3880 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00003881 return std::string();
3882 }
3883
3884 // Initialize the stream
3885 llvm::BitstreamReader StreamFile;
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003886 PCHContainerOps.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00003887 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003888
3889 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003890 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003891 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3892 return std::string();
3893 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003894
Chris Lattnere7b154b2013-01-19 21:39:22 +00003895 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003896 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003897 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3898 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003899 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003900
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003901 // Scan for ORIGINAL_FILE inside the control block.
3902 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003903 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003904 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003905 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3906 return std::string();
3907
3908 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3909 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3910 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003911 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003912
Guy Benyei11169dd2012-12-18 14:30:41 +00003913 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003914 StringRef Blob;
3915 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3916 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003917 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003918}
3919
3920namespace {
3921 class SimplePCHValidator : public ASTReaderListener {
3922 const LangOptions &ExistingLangOpts;
3923 const TargetOptions &ExistingTargetOpts;
3924 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003925 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00003926 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003927
Guy Benyei11169dd2012-12-18 14:30:41 +00003928 public:
3929 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3930 const TargetOptions &ExistingTargetOpts,
3931 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003932 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00003933 FileManager &FileMgr)
3934 : ExistingLangOpts(ExistingLangOpts),
3935 ExistingTargetOpts(ExistingTargetOpts),
3936 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003937 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00003938 FileMgr(FileMgr)
3939 {
3940 }
3941
Richard Smith1e2cf0d2014-10-31 02:28:58 +00003942 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
3943 bool AllowCompatibleDifferences) override {
3944 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
3945 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00003946 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00003947 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
3948 bool AllowCompatibleDifferences) override {
3949 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
3950 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00003951 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003952 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
3953 StringRef SpecificModuleCachePath,
3954 bool Complain) override {
3955 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
3956 ExistingModuleCachePath,
3957 nullptr, ExistingLangOpts);
3958 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003959 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3960 bool Complain,
3961 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00003962 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00003963 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00003964 }
3965 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003966}
Guy Benyei11169dd2012-12-18 14:30:41 +00003967
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003968bool ASTReader::readASTFileControlBlock(
3969 StringRef Filename, FileManager &FileMgr,
3970 const PCHContainerOperations &PCHContainerOps,
3971 ASTReaderListener &Listener) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003972 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00003973 // FIXME: This allows use of the VFS; we do not allow use of the
3974 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00003975 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00003976 if (!Buffer) {
3977 return true;
3978 }
3979
3980 // Initialize the stream
3981 llvm::BitstreamReader StreamFile;
Adrian Prantlbc068582015-07-08 01:00:30 +00003982 PCHContainerOps.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00003983 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003984
3985 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003986 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00003987 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003988
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003989 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003990 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003991 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003992
3993 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00003994 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00003995 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003996 BitstreamCursor InputFilesCursor;
3997 if (NeedsInputFiles) {
3998 InputFilesCursor = Stream;
3999 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4000 return true;
4001
4002 // Read the abbreviations
4003 while (true) {
4004 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4005 unsigned Code = InputFilesCursor.ReadCode();
4006
4007 // We expect all abbrevs to be at the start of the block.
4008 if (Code != llvm::bitc::DEFINE_ABBREV) {
4009 InputFilesCursor.JumpToBit(Offset);
4010 break;
4011 }
4012 InputFilesCursor.ReadAbbrevRecord();
4013 }
4014 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004015
4016 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004017 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004018 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004019 while (1) {
4020 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4021 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4022 return false;
4023
4024 if (Entry.Kind != llvm::BitstreamEntry::Record)
4025 return true;
4026
Guy Benyei11169dd2012-12-18 14:30:41 +00004027 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004028 StringRef Blob;
4029 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004030 switch ((ControlRecordTypes)RecCode) {
4031 case METADATA: {
4032 if (Record[0] != VERSION_MAJOR)
4033 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004034
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004035 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004036 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004037
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004038 break;
4039 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004040 case MODULE_NAME:
4041 Listener.ReadModuleName(Blob);
4042 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004043 case MODULE_DIRECTORY:
4044 ModuleDir = Blob;
4045 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004046 case MODULE_MAP_FILE: {
4047 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004048 auto Path = ReadString(Record, Idx);
4049 ResolveImportedPath(Path, ModuleDir);
4050 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004051 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004052 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004053 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004054 if (ParseLanguageOptions(Record, false, Listener,
4055 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004056 return true;
4057 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004058
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004059 case TARGET_OPTIONS:
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004060 if (ParseTargetOptions(Record, false, Listener,
4061 /*AllowCompatibleConfigurationMismatch*/ false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004062 return true;
4063 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004064
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004065 case DIAGNOSTIC_OPTIONS:
4066 if (ParseDiagnosticOptions(Record, false, Listener))
4067 return true;
4068 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004069
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004070 case FILE_SYSTEM_OPTIONS:
4071 if (ParseFileSystemOptions(Record, false, Listener))
4072 return true;
4073 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004074
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004075 case HEADER_SEARCH_OPTIONS:
4076 if (ParseHeaderSearchOptions(Record, false, Listener))
4077 return true;
4078 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004079
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004080 case PREPROCESSOR_OPTIONS: {
4081 std::string IgnoredSuggestedPredefines;
4082 if (ParsePreprocessorOptions(Record, false, Listener,
4083 IgnoredSuggestedPredefines))
4084 return true;
4085 break;
4086 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004087
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004088 case INPUT_FILE_OFFSETS: {
4089 if (!NeedsInputFiles)
4090 break;
4091
4092 unsigned NumInputFiles = Record[0];
4093 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004094 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004095 for (unsigned I = 0; I != NumInputFiles; ++I) {
4096 // Go find this input file.
4097 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004098
4099 if (isSystemFile && !NeedsSystemInputFiles)
4100 break; // the rest are system input files
4101
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004102 BitstreamCursor &Cursor = InputFilesCursor;
4103 SavedStreamPosition SavedPosition(Cursor);
4104 Cursor.JumpToBit(InputFileOffs[I]);
4105
4106 unsigned Code = Cursor.ReadCode();
4107 RecordData Record;
4108 StringRef Blob;
4109 bool shouldContinue = false;
4110 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4111 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004112 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004113 std::string Filename = Blob;
4114 ResolveImportedPath(Filename, ModuleDir);
4115 shouldContinue =
4116 Listener.visitInputFile(Filename, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004117 break;
4118 }
4119 if (!shouldContinue)
4120 break;
4121 }
4122 break;
4123 }
4124
Richard Smithd4b230b2014-10-27 23:01:16 +00004125 case IMPORTS: {
4126 if (!NeedsImports)
4127 break;
4128
4129 unsigned Idx = 0, N = Record.size();
4130 while (Idx < N) {
4131 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004132 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004133 std::string Filename = ReadString(Record, Idx);
4134 ResolveImportedPath(Filename, ModuleDir);
4135 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004136 }
4137 break;
4138 }
4139
Richard Smith7f330cd2015-03-18 01:42:29 +00004140 case KNOWN_MODULE_FILES: {
4141 // Known-but-not-technically-used module files are treated as imports.
4142 if (!NeedsImports)
4143 break;
4144
4145 unsigned Idx = 0, N = Record.size();
4146 while (Idx < N) {
4147 std::string Filename = ReadString(Record, Idx);
4148 ResolveImportedPath(Filename, ModuleDir);
4149 Listener.visitImport(Filename);
4150 }
4151 break;
4152 }
4153
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004154 default:
4155 // No other validation to perform.
4156 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004157 }
4158 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004159}
4160
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004161bool ASTReader::isAcceptableASTFile(
4162 StringRef Filename, FileManager &FileMgr,
4163 const PCHContainerOperations &PCHContainerOps, const LangOptions &LangOpts,
4164 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4165 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004166 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4167 ExistingModuleCachePath, FileMgr);
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004168 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerOps,
4169 validator);
Guy Benyei11169dd2012-12-18 14:30:41 +00004170}
4171
Ben Langmuir2c9af442014-04-10 17:57:43 +00004172ASTReader::ASTReadResult
4173ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004174 // Enter the submodule block.
4175 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4176 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004177 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004178 }
4179
4180 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4181 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004182 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004183 RecordData Record;
4184 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004185 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4186
4187 switch (Entry.Kind) {
4188 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4189 case llvm::BitstreamEntry::Error:
4190 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004191 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004192 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004193 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004194 case llvm::BitstreamEntry::Record:
4195 // The interesting case.
4196 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004197 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004198
Guy Benyei11169dd2012-12-18 14:30:41 +00004199 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004200 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004201 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004202 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4203
4204 if ((Kind == SUBMODULE_METADATA) != First) {
4205 Error("submodule metadata record should be at beginning of block");
4206 return Failure;
4207 }
4208 First = false;
4209
4210 // Submodule information is only valid if we have a current module.
4211 // FIXME: Should we error on these cases?
4212 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4213 Kind != SUBMODULE_DEFINITION)
4214 continue;
4215
4216 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004217 default: // Default behavior: ignore.
4218 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004219
Richard Smith03478d92014-10-23 22:12:14 +00004220 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004221 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004222 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004223 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004224 }
Richard Smith03478d92014-10-23 22:12:14 +00004225
Chris Lattner0e6c9402013-01-20 02:38:54 +00004226 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004227 unsigned Idx = 0;
4228 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4229 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4230 bool IsFramework = Record[Idx++];
4231 bool IsExplicit = Record[Idx++];
4232 bool IsSystem = Record[Idx++];
4233 bool IsExternC = Record[Idx++];
4234 bool InferSubmodules = Record[Idx++];
4235 bool InferExplicitSubmodules = Record[Idx++];
4236 bool InferExportWildcard = Record[Idx++];
4237 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004238
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004239 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004240 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004241 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004242
Guy Benyei11169dd2012-12-18 14:30:41 +00004243 // Retrieve this (sub)module from the module map, creating it if
4244 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004245 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004246 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004247
4248 // FIXME: set the definition loc for CurrentModule, or call
4249 // ModMap.setInferredModuleAllowedBy()
4250
Guy Benyei11169dd2012-12-18 14:30:41 +00004251 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4252 if (GlobalIndex >= SubmodulesLoaded.size() ||
4253 SubmodulesLoaded[GlobalIndex]) {
4254 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004255 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004256 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004257
Douglas Gregor7029ce12013-03-19 00:28:20 +00004258 if (!ParentModule) {
4259 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4260 if (CurFile != F.File) {
4261 if (!Diags.isDiagnosticInFlight()) {
4262 Diag(diag::err_module_file_conflict)
4263 << CurrentModule->getTopLevelModuleName()
4264 << CurFile->getName()
4265 << F.File->getName();
4266 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004267 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004268 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004269 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004270
4271 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004272 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004273
Adrian Prantl15bcf702015-06-30 17:39:43 +00004274 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004275 CurrentModule->IsFromModuleFile = true;
4276 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004277 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004278 CurrentModule->InferSubmodules = InferSubmodules;
4279 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4280 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004281 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004282 if (DeserializationListener)
4283 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4284
4285 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004286
Douglas Gregorfb912652013-03-20 21:10:35 +00004287 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004288 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004289 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004290 CurrentModule->UnresolvedConflicts.clear();
4291 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004292 break;
4293 }
4294
4295 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004296 std::string Filename = Blob;
4297 ResolveImportedPath(F, Filename);
4298 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004299 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004300 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4301 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004302 // This can be a spurious difference caused by changing the VFS to
4303 // point to a different copy of the file, and it is too late to
4304 // to rebuild safely.
4305 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4306 // after input file validation only real problems would remain and we
4307 // could just error. For now, assume it's okay.
4308 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004309 }
4310 }
4311 break;
4312 }
4313
Richard Smith202210b2014-10-24 20:23:01 +00004314 case SUBMODULE_HEADER:
4315 case SUBMODULE_EXCLUDED_HEADER:
4316 case SUBMODULE_PRIVATE_HEADER:
4317 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004318 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4319 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004320 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004321
Richard Smith202210b2014-10-24 20:23:01 +00004322 case SUBMODULE_TEXTUAL_HEADER:
4323 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4324 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4325 // them here.
4326 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004327
Guy Benyei11169dd2012-12-18 14:30:41 +00004328 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004329 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004330 break;
4331 }
4332
4333 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004334 std::string Dirname = Blob;
4335 ResolveImportedPath(F, Dirname);
4336 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004337 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004338 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4339 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004340 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4341 Error("mismatched umbrella directories in submodule");
4342 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004343 }
4344 }
4345 break;
4346 }
4347
4348 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004349 F.BaseSubmoduleID = getTotalNumSubmodules();
4350 F.LocalNumSubmodules = Record[0];
4351 unsigned LocalBaseSubmoduleID = Record[1];
4352 if (F.LocalNumSubmodules > 0) {
4353 // Introduce the global -> local mapping for submodules within this
4354 // module.
4355 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4356
4357 // Introduce the local -> global mapping for submodules within this
4358 // module.
4359 F.SubmoduleRemap.insertOrReplace(
4360 std::make_pair(LocalBaseSubmoduleID,
4361 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004362
Ben Langmuir52ca6782014-10-20 16:27:32 +00004363 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4364 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004365 break;
4366 }
4367
4368 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004369 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004370 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004371 Unresolved.File = &F;
4372 Unresolved.Mod = CurrentModule;
4373 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004374 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004375 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004376 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004377 }
4378 break;
4379 }
4380
4381 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004382 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004383 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004384 Unresolved.File = &F;
4385 Unresolved.Mod = CurrentModule;
4386 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004387 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004388 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004389 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004390 }
4391
4392 // Once we've loaded the set of exports, there's no reason to keep
4393 // the parsed, unresolved exports around.
4394 CurrentModule->UnresolvedExports.clear();
4395 break;
4396 }
4397 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004398 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004399 Context.getTargetInfo());
4400 break;
4401 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004402
4403 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004404 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004405 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004406 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004407
4408 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004409 CurrentModule->ConfigMacros.push_back(Blob.str());
4410 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004411
4412 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004413 UnresolvedModuleRef Unresolved;
4414 Unresolved.File = &F;
4415 Unresolved.Mod = CurrentModule;
4416 Unresolved.ID = Record[0];
4417 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4418 Unresolved.IsWildcard = false;
4419 Unresolved.String = Blob;
4420 UnresolvedModuleRefs.push_back(Unresolved);
4421 break;
4422 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004423 }
4424 }
4425}
4426
4427/// \brief Parse the record that corresponds to a LangOptions data
4428/// structure.
4429///
4430/// This routine parses the language options from the AST file and then gives
4431/// them to the AST listener if one is set.
4432///
4433/// \returns true if the listener deems the file unacceptable, false otherwise.
4434bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4435 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004436 ASTReaderListener &Listener,
4437 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004438 LangOptions LangOpts;
4439 unsigned Idx = 0;
4440#define LANGOPT(Name, Bits, Default, Description) \
4441 LangOpts.Name = Record[Idx++];
4442#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4443 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4444#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004445#define SANITIZER(NAME, ID) \
4446 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004447#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004448
Ben Langmuircd98cb72015-06-23 18:20:18 +00004449 for (unsigned N = Record[Idx++]; N; --N)
4450 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4451
Guy Benyei11169dd2012-12-18 14:30:41 +00004452 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4453 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4454 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004455
Ben Langmuird4a667a2015-06-23 18:20:23 +00004456 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004457
4458 // Comment options.
4459 for (unsigned N = Record[Idx++]; N; --N) {
4460 LangOpts.CommentOpts.BlockCommandNames.push_back(
4461 ReadString(Record, Idx));
4462 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004463 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004464
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004465 return Listener.ReadLanguageOptions(LangOpts, Complain,
4466 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004467}
4468
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004469bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4470 ASTReaderListener &Listener,
4471 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004472 unsigned Idx = 0;
4473 TargetOptions TargetOpts;
4474 TargetOpts.Triple = ReadString(Record, Idx);
4475 TargetOpts.CPU = ReadString(Record, Idx);
4476 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004477 for (unsigned N = Record[Idx++]; N; --N) {
4478 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4479 }
4480 for (unsigned N = Record[Idx++]; N; --N) {
4481 TargetOpts.Features.push_back(ReadString(Record, Idx));
4482 }
4483
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004484 return Listener.ReadTargetOptions(TargetOpts, Complain,
4485 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004486}
4487
4488bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4489 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004490 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004491 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004492#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004493#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004494 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004495#include "clang/Basic/DiagnosticOptions.def"
4496
Richard Smith3be1cb22014-08-07 00:24:21 +00004497 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004498 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004499 for (unsigned N = Record[Idx++]; N; --N)
4500 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004501
4502 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4503}
4504
4505bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4506 ASTReaderListener &Listener) {
4507 FileSystemOptions FSOpts;
4508 unsigned Idx = 0;
4509 FSOpts.WorkingDir = ReadString(Record, Idx);
4510 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4511}
4512
4513bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4514 bool Complain,
4515 ASTReaderListener &Listener) {
4516 HeaderSearchOptions HSOpts;
4517 unsigned Idx = 0;
4518 HSOpts.Sysroot = ReadString(Record, Idx);
4519
4520 // Include entries.
4521 for (unsigned N = Record[Idx++]; N; --N) {
4522 std::string Path = ReadString(Record, Idx);
4523 frontend::IncludeDirGroup Group
4524 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004525 bool IsFramework = Record[Idx++];
4526 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004527 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4528 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004529 }
4530
4531 // System header prefixes.
4532 for (unsigned N = Record[Idx++]; N; --N) {
4533 std::string Prefix = ReadString(Record, Idx);
4534 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004535 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004536 }
4537
4538 HSOpts.ResourceDir = ReadString(Record, Idx);
4539 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004540 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004541 HSOpts.DisableModuleHash = Record[Idx++];
4542 HSOpts.UseBuiltinIncludes = Record[Idx++];
4543 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4544 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4545 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004546 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004547
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004548 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4549 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004550}
4551
4552bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4553 bool Complain,
4554 ASTReaderListener &Listener,
4555 std::string &SuggestedPredefines) {
4556 PreprocessorOptions PPOpts;
4557 unsigned Idx = 0;
4558
4559 // Macro definitions/undefs
4560 for (unsigned N = Record[Idx++]; N; --N) {
4561 std::string Macro = ReadString(Record, Idx);
4562 bool IsUndef = Record[Idx++];
4563 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4564 }
4565
4566 // Includes
4567 for (unsigned N = Record[Idx++]; N; --N) {
4568 PPOpts.Includes.push_back(ReadString(Record, Idx));
4569 }
4570
4571 // Macro Includes
4572 for (unsigned N = Record[Idx++]; N; --N) {
4573 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4574 }
4575
4576 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004577 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004578 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4579 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4580 PPOpts.ObjCXXARCStandardLibrary =
4581 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4582 SuggestedPredefines.clear();
4583 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4584 SuggestedPredefines);
4585}
4586
4587std::pair<ModuleFile *, unsigned>
4588ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4589 GlobalPreprocessedEntityMapType::iterator
4590 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4591 assert(I != GlobalPreprocessedEntityMap.end() &&
4592 "Corrupted global preprocessed entity map");
4593 ModuleFile *M = I->second;
4594 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4595 return std::make_pair(M, LocalIndex);
4596}
4597
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004598llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004599ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4600 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4601 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4602 Mod.NumPreprocessedEntities);
4603
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004604 return llvm::make_range(PreprocessingRecord::iterator(),
4605 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004606}
4607
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004608llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004609ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004610 return llvm::make_range(
4611 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4612 ModuleDeclIterator(this, &Mod,
4613 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004614}
4615
4616PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4617 PreprocessedEntityID PPID = Index+1;
4618 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4619 ModuleFile &M = *PPInfo.first;
4620 unsigned LocalIndex = PPInfo.second;
4621 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4622
Guy Benyei11169dd2012-12-18 14:30:41 +00004623 if (!PP.getPreprocessingRecord()) {
4624 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004625 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004626 }
4627
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004628 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4629 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4630
4631 llvm::BitstreamEntry Entry =
4632 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4633 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004634 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004635
Guy Benyei11169dd2012-12-18 14:30:41 +00004636 // Read the record.
4637 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4638 ReadSourceLocation(M, PPOffs.End));
4639 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004640 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004641 RecordData Record;
4642 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004643 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4644 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004645 switch (RecType) {
4646 case PPD_MACRO_EXPANSION: {
4647 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004648 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004649 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004650 if (isBuiltin)
4651 Name = getLocalIdentifier(M, Record[1]);
4652 else {
Richard Smith66a81862015-05-04 02:25:31 +00004653 PreprocessedEntityID GlobalID =
4654 getGlobalPreprocessedEntityID(M, Record[1]);
4655 Def = cast<MacroDefinitionRecord>(
4656 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004657 }
4658
4659 MacroExpansion *ME;
4660 if (isBuiltin)
4661 ME = new (PPRec) MacroExpansion(Name, Range);
4662 else
4663 ME = new (PPRec) MacroExpansion(Def, Range);
4664
4665 return ME;
4666 }
4667
4668 case PPD_MACRO_DEFINITION: {
4669 // Decode the identifier info and then check again; if the macro is
4670 // still defined and associated with the identifier,
4671 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004672 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004673
4674 if (DeserializationListener)
4675 DeserializationListener->MacroDefinitionRead(PPID, MD);
4676
4677 return MD;
4678 }
4679
4680 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004681 const char *FullFileNameStart = Blob.data() + Record[0];
4682 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004683 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004684 if (!FullFileName.empty())
4685 File = PP.getFileManager().getFile(FullFileName);
4686
4687 // FIXME: Stable encoding
4688 InclusionDirective::InclusionKind Kind
4689 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4690 InclusionDirective *ID
4691 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004692 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004693 Record[1], Record[3],
4694 File,
4695 Range);
4696 return ID;
4697 }
4698 }
4699
4700 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4701}
4702
4703/// \brief \arg SLocMapI points at a chunk of a module that contains no
4704/// preprocessed entities or the entities it contains are not the ones we are
4705/// looking for. Find the next module that contains entities and return the ID
4706/// of the first entry.
4707PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4708 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4709 ++SLocMapI;
4710 for (GlobalSLocOffsetMapType::const_iterator
4711 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4712 ModuleFile &M = *SLocMapI->second;
4713 if (M.NumPreprocessedEntities)
4714 return M.BasePreprocessedEntityID;
4715 }
4716
4717 return getTotalNumPreprocessedEntities();
4718}
4719
4720namespace {
4721
4722template <unsigned PPEntityOffset::*PPLoc>
4723struct PPEntityComp {
4724 const ASTReader &Reader;
4725 ModuleFile &M;
4726
4727 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4728
4729 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4730 SourceLocation LHS = getLoc(L);
4731 SourceLocation RHS = getLoc(R);
4732 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4733 }
4734
4735 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4736 SourceLocation LHS = getLoc(L);
4737 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4738 }
4739
4740 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4741 SourceLocation RHS = getLoc(R);
4742 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4743 }
4744
4745 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4746 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4747 }
4748};
4749
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004750}
Guy Benyei11169dd2012-12-18 14:30:41 +00004751
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004752PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4753 bool EndsAfter) const {
4754 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004755 return getTotalNumPreprocessedEntities();
4756
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004757 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4758 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004759 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4760 "Corrupted global sloc offset map");
4761
4762 if (SLocMapI->second->NumPreprocessedEntities == 0)
4763 return findNextPreprocessedEntity(SLocMapI);
4764
4765 ModuleFile &M = *SLocMapI->second;
4766 typedef const PPEntityOffset *pp_iterator;
4767 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4768 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4769
4770 size_t Count = M.NumPreprocessedEntities;
4771 size_t Half;
4772 pp_iterator First = pp_begin;
4773 pp_iterator PPI;
4774
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004775 if (EndsAfter) {
4776 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4777 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4778 } else {
4779 // Do a binary search manually instead of using std::lower_bound because
4780 // The end locations of entities may be unordered (when a macro expansion
4781 // is inside another macro argument), but for this case it is not important
4782 // whether we get the first macro expansion or its containing macro.
4783 while (Count > 0) {
4784 Half = Count / 2;
4785 PPI = First;
4786 std::advance(PPI, Half);
4787 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4788 Loc)) {
4789 First = PPI;
4790 ++First;
4791 Count = Count - Half - 1;
4792 } else
4793 Count = Half;
4794 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004795 }
4796
4797 if (PPI == pp_end)
4798 return findNextPreprocessedEntity(SLocMapI);
4799
4800 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4801}
4802
Guy Benyei11169dd2012-12-18 14:30:41 +00004803/// \brief Returns a pair of [Begin, End) indices of preallocated
4804/// preprocessed entities that \arg Range encompasses.
4805std::pair<unsigned, unsigned>
4806 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4807 if (Range.isInvalid())
4808 return std::make_pair(0,0);
4809 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4810
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004811 PreprocessedEntityID BeginID =
4812 findPreprocessedEntity(Range.getBegin(), false);
4813 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004814 return std::make_pair(BeginID, EndID);
4815}
4816
4817/// \brief Optionally returns true or false if the preallocated preprocessed
4818/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004819Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004820 FileID FID) {
4821 if (FID.isInvalid())
4822 return false;
4823
4824 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4825 ModuleFile &M = *PPInfo.first;
4826 unsigned LocalIndex = PPInfo.second;
4827 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4828
4829 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4830 if (Loc.isInvalid())
4831 return false;
4832
4833 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4834 return true;
4835 else
4836 return false;
4837}
4838
4839namespace {
4840 /// \brief Visitor used to search for information about a header file.
4841 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004842 const FileEntry *FE;
4843
David Blaikie05785d12013-02-20 22:23:23 +00004844 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004845
4846 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004847 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4848 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004849
4850 static bool visit(ModuleFile &M, void *UserData) {
4851 HeaderFileInfoVisitor *This
4852 = static_cast<HeaderFileInfoVisitor *>(UserData);
4853
Guy Benyei11169dd2012-12-18 14:30:41 +00004854 HeaderFileInfoLookupTable *Table
4855 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4856 if (!Table)
4857 return false;
4858
4859 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00004860 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004861 if (Pos == Table->end())
4862 return false;
4863
4864 This->HFI = *Pos;
4865 return true;
4866 }
4867
David Blaikie05785d12013-02-20 22:23:23 +00004868 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004869 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004870}
Guy Benyei11169dd2012-12-18 14:30:41 +00004871
4872HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004873 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004874 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004875 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004876 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004877
4878 return HeaderFileInfo();
4879}
4880
4881void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4882 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004883 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004884 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4885 ModuleFile &F = *(*I);
4886 unsigned Idx = 0;
4887 DiagStates.clear();
4888 assert(!Diag.DiagStates.empty());
4889 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4890 while (Idx < F.PragmaDiagMappings.size()) {
4891 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4892 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4893 if (DiagStateID != 0) {
4894 Diag.DiagStatePoints.push_back(
4895 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4896 FullSourceLoc(Loc, SourceMgr)));
4897 continue;
4898 }
4899
4900 assert(DiagStateID == 0);
4901 // A new DiagState was created here.
4902 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4903 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4904 DiagStates.push_back(NewState);
4905 Diag.DiagStatePoints.push_back(
4906 DiagnosticsEngine::DiagStatePoint(NewState,
4907 FullSourceLoc(Loc, SourceMgr)));
4908 while (1) {
4909 assert(Idx < F.PragmaDiagMappings.size() &&
4910 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4911 if (Idx >= F.PragmaDiagMappings.size()) {
4912 break; // Something is messed up but at least avoid infinite loop in
4913 // release build.
4914 }
4915 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4916 if (DiagID == (unsigned)-1) {
4917 break; // no more diag/map pairs for this location.
4918 }
Alp Tokerc726c362014-06-10 09:31:37 +00004919 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
4920 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
4921 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00004922 }
4923 }
4924 }
4925}
4926
4927/// \brief Get the correct cursor and offset for loading a type.
4928ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4929 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4930 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4931 ModuleFile *M = I->second;
4932 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4933}
4934
4935/// \brief Read and return the type with the given index..
4936///
4937/// The index is the type ID, shifted and minus the number of predefs. This
4938/// routine actually reads the record corresponding to the type at the given
4939/// location. It is a helper routine for GetType, which deals with reading type
4940/// IDs.
4941QualType ASTReader::readTypeRecord(unsigned Index) {
4942 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004943 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00004944
4945 // Keep track of where we are in the stream, then jump back there
4946 // after reading this type.
4947 SavedStreamPosition SavedPosition(DeclsCursor);
4948
4949 ReadingKindTracker ReadingKind(Read_Type, *this);
4950
4951 // Note that we are loading a type record.
4952 Deserializing AType(this);
4953
4954 unsigned Idx = 0;
4955 DeclsCursor.JumpToBit(Loc.Offset);
4956 RecordData Record;
4957 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004958 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004959 case TYPE_EXT_QUAL: {
4960 if (Record.size() != 2) {
4961 Error("Incorrect encoding of extended qualifier type");
4962 return QualType();
4963 }
4964 QualType Base = readType(*Loc.F, Record, Idx);
4965 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4966 return Context.getQualifiedType(Base, Quals);
4967 }
4968
4969 case TYPE_COMPLEX: {
4970 if (Record.size() != 1) {
4971 Error("Incorrect encoding of complex type");
4972 return QualType();
4973 }
4974 QualType ElemType = readType(*Loc.F, Record, Idx);
4975 return Context.getComplexType(ElemType);
4976 }
4977
4978 case TYPE_POINTER: {
4979 if (Record.size() != 1) {
4980 Error("Incorrect encoding of pointer type");
4981 return QualType();
4982 }
4983 QualType PointeeType = readType(*Loc.F, Record, Idx);
4984 return Context.getPointerType(PointeeType);
4985 }
4986
Reid Kleckner8a365022013-06-24 17:51:48 +00004987 case TYPE_DECAYED: {
4988 if (Record.size() != 1) {
4989 Error("Incorrect encoding of decayed type");
4990 return QualType();
4991 }
4992 QualType OriginalType = readType(*Loc.F, Record, Idx);
4993 QualType DT = Context.getAdjustedParameterType(OriginalType);
4994 if (!isa<DecayedType>(DT))
4995 Error("Decayed type does not decay");
4996 return DT;
4997 }
4998
Reid Kleckner0503a872013-12-05 01:23:43 +00004999 case TYPE_ADJUSTED: {
5000 if (Record.size() != 2) {
5001 Error("Incorrect encoding of adjusted type");
5002 return QualType();
5003 }
5004 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5005 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5006 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5007 }
5008
Guy Benyei11169dd2012-12-18 14:30:41 +00005009 case TYPE_BLOCK_POINTER: {
5010 if (Record.size() != 1) {
5011 Error("Incorrect encoding of block pointer type");
5012 return QualType();
5013 }
5014 QualType PointeeType = readType(*Loc.F, Record, Idx);
5015 return Context.getBlockPointerType(PointeeType);
5016 }
5017
5018 case TYPE_LVALUE_REFERENCE: {
5019 if (Record.size() != 2) {
5020 Error("Incorrect encoding of lvalue reference type");
5021 return QualType();
5022 }
5023 QualType PointeeType = readType(*Loc.F, Record, Idx);
5024 return Context.getLValueReferenceType(PointeeType, Record[1]);
5025 }
5026
5027 case TYPE_RVALUE_REFERENCE: {
5028 if (Record.size() != 1) {
5029 Error("Incorrect encoding of rvalue reference type");
5030 return QualType();
5031 }
5032 QualType PointeeType = readType(*Loc.F, Record, Idx);
5033 return Context.getRValueReferenceType(PointeeType);
5034 }
5035
5036 case TYPE_MEMBER_POINTER: {
5037 if (Record.size() != 2) {
5038 Error("Incorrect encoding of member pointer type");
5039 return QualType();
5040 }
5041 QualType PointeeType = readType(*Loc.F, Record, Idx);
5042 QualType ClassType = readType(*Loc.F, Record, Idx);
5043 if (PointeeType.isNull() || ClassType.isNull())
5044 return QualType();
5045
5046 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5047 }
5048
5049 case TYPE_CONSTANT_ARRAY: {
5050 QualType ElementType = readType(*Loc.F, Record, Idx);
5051 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5052 unsigned IndexTypeQuals = Record[2];
5053 unsigned Idx = 3;
5054 llvm::APInt Size = ReadAPInt(Record, Idx);
5055 return Context.getConstantArrayType(ElementType, Size,
5056 ASM, IndexTypeQuals);
5057 }
5058
5059 case TYPE_INCOMPLETE_ARRAY: {
5060 QualType ElementType = readType(*Loc.F, Record, Idx);
5061 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5062 unsigned IndexTypeQuals = Record[2];
5063 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5064 }
5065
5066 case TYPE_VARIABLE_ARRAY: {
5067 QualType ElementType = readType(*Loc.F, Record, Idx);
5068 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5069 unsigned IndexTypeQuals = Record[2];
5070 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5071 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5072 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5073 ASM, IndexTypeQuals,
5074 SourceRange(LBLoc, RBLoc));
5075 }
5076
5077 case TYPE_VECTOR: {
5078 if (Record.size() != 3) {
5079 Error("incorrect encoding of vector type in AST file");
5080 return QualType();
5081 }
5082
5083 QualType ElementType = readType(*Loc.F, Record, Idx);
5084 unsigned NumElements = Record[1];
5085 unsigned VecKind = Record[2];
5086 return Context.getVectorType(ElementType, NumElements,
5087 (VectorType::VectorKind)VecKind);
5088 }
5089
5090 case TYPE_EXT_VECTOR: {
5091 if (Record.size() != 3) {
5092 Error("incorrect encoding of extended vector type in AST file");
5093 return QualType();
5094 }
5095
5096 QualType ElementType = readType(*Loc.F, Record, Idx);
5097 unsigned NumElements = Record[1];
5098 return Context.getExtVectorType(ElementType, NumElements);
5099 }
5100
5101 case TYPE_FUNCTION_NO_PROTO: {
5102 if (Record.size() != 6) {
5103 Error("incorrect encoding of no-proto function type");
5104 return QualType();
5105 }
5106 QualType ResultType = readType(*Loc.F, Record, Idx);
5107 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5108 (CallingConv)Record[4], Record[5]);
5109 return Context.getFunctionNoProtoType(ResultType, Info);
5110 }
5111
5112 case TYPE_FUNCTION_PROTO: {
5113 QualType ResultType = readType(*Loc.F, Record, Idx);
5114
5115 FunctionProtoType::ExtProtoInfo EPI;
5116 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5117 /*hasregparm*/ Record[2],
5118 /*regparm*/ Record[3],
5119 static_cast<CallingConv>(Record[4]),
5120 /*produces*/ Record[5]);
5121
5122 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005123
5124 EPI.Variadic = Record[Idx++];
5125 EPI.HasTrailingReturn = Record[Idx++];
5126 EPI.TypeQuals = Record[Idx++];
5127 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005128 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005129 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005130
5131 unsigned NumParams = Record[Idx++];
5132 SmallVector<QualType, 16> ParamTypes;
5133 for (unsigned I = 0; I != NumParams; ++I)
5134 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5135
Jordan Rose5c382722013-03-08 21:51:21 +00005136 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005137 }
5138
5139 case TYPE_UNRESOLVED_USING: {
5140 unsigned Idx = 0;
5141 return Context.getTypeDeclType(
5142 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5143 }
5144
5145 case TYPE_TYPEDEF: {
5146 if (Record.size() != 2) {
5147 Error("incorrect encoding of typedef type");
5148 return QualType();
5149 }
5150 unsigned Idx = 0;
5151 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5152 QualType Canonical = readType(*Loc.F, Record, Idx);
5153 if (!Canonical.isNull())
5154 Canonical = Context.getCanonicalType(Canonical);
5155 return Context.getTypedefType(Decl, Canonical);
5156 }
5157
5158 case TYPE_TYPEOF_EXPR:
5159 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5160
5161 case TYPE_TYPEOF: {
5162 if (Record.size() != 1) {
5163 Error("incorrect encoding of typeof(type) in AST file");
5164 return QualType();
5165 }
5166 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5167 return Context.getTypeOfType(UnderlyingType);
5168 }
5169
5170 case TYPE_DECLTYPE: {
5171 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5172 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5173 }
5174
5175 case TYPE_UNARY_TRANSFORM: {
5176 QualType BaseType = readType(*Loc.F, Record, Idx);
5177 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5178 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5179 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5180 }
5181
Richard Smith74aeef52013-04-26 16:15:35 +00005182 case TYPE_AUTO: {
5183 QualType Deduced = readType(*Loc.F, Record, Idx);
5184 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005185 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005186 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005187 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005188
5189 case TYPE_RECORD: {
5190 if (Record.size() != 2) {
5191 Error("incorrect encoding of record type");
5192 return QualType();
5193 }
5194 unsigned Idx = 0;
5195 bool IsDependent = Record[Idx++];
5196 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5197 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5198 QualType T = Context.getRecordType(RD);
5199 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5200 return T;
5201 }
5202
5203 case TYPE_ENUM: {
5204 if (Record.size() != 2) {
5205 Error("incorrect encoding of enum type");
5206 return QualType();
5207 }
5208 unsigned Idx = 0;
5209 bool IsDependent = Record[Idx++];
5210 QualType T
5211 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5212 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5213 return T;
5214 }
5215
5216 case TYPE_ATTRIBUTED: {
5217 if (Record.size() != 3) {
5218 Error("incorrect encoding of attributed type");
5219 return QualType();
5220 }
5221 QualType modifiedType = readType(*Loc.F, Record, Idx);
5222 QualType equivalentType = readType(*Loc.F, Record, Idx);
5223 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5224 return Context.getAttributedType(kind, modifiedType, equivalentType);
5225 }
5226
5227 case TYPE_PAREN: {
5228 if (Record.size() != 1) {
5229 Error("incorrect encoding of paren type");
5230 return QualType();
5231 }
5232 QualType InnerType = readType(*Loc.F, Record, Idx);
5233 return Context.getParenType(InnerType);
5234 }
5235
5236 case TYPE_PACK_EXPANSION: {
5237 if (Record.size() != 2) {
5238 Error("incorrect encoding of pack expansion type");
5239 return QualType();
5240 }
5241 QualType Pattern = readType(*Loc.F, Record, Idx);
5242 if (Pattern.isNull())
5243 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005244 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005245 if (Record[1])
5246 NumExpansions = Record[1] - 1;
5247 return Context.getPackExpansionType(Pattern, NumExpansions);
5248 }
5249
5250 case TYPE_ELABORATED: {
5251 unsigned Idx = 0;
5252 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5253 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5254 QualType NamedType = readType(*Loc.F, Record, Idx);
5255 return Context.getElaboratedType(Keyword, NNS, NamedType);
5256 }
5257
5258 case TYPE_OBJC_INTERFACE: {
5259 unsigned Idx = 0;
5260 ObjCInterfaceDecl *ItfD
5261 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5262 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5263 }
5264
5265 case TYPE_OBJC_OBJECT: {
5266 unsigned Idx = 0;
5267 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005268 unsigned NumTypeArgs = Record[Idx++];
5269 SmallVector<QualType, 4> TypeArgs;
5270 for (unsigned I = 0; I != NumTypeArgs; ++I)
5271 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005272 unsigned NumProtos = Record[Idx++];
5273 SmallVector<ObjCProtocolDecl*, 4> Protos;
5274 for (unsigned I = 0; I != NumProtos; ++I)
5275 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005276 bool IsKindOf = Record[Idx++];
5277 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005278 }
5279
5280 case TYPE_OBJC_OBJECT_POINTER: {
5281 unsigned Idx = 0;
5282 QualType Pointee = readType(*Loc.F, Record, Idx);
5283 return Context.getObjCObjectPointerType(Pointee);
5284 }
5285
5286 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5287 unsigned Idx = 0;
5288 QualType Parm = readType(*Loc.F, Record, Idx);
5289 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005290 return Context.getSubstTemplateTypeParmType(
5291 cast<TemplateTypeParmType>(Parm),
5292 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005293 }
5294
5295 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5296 unsigned Idx = 0;
5297 QualType Parm = readType(*Loc.F, Record, Idx);
5298 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5299 return Context.getSubstTemplateTypeParmPackType(
5300 cast<TemplateTypeParmType>(Parm),
5301 ArgPack);
5302 }
5303
5304 case TYPE_INJECTED_CLASS_NAME: {
5305 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5306 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5307 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5308 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005309 const Type *T = nullptr;
5310 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5311 if (const Type *Existing = DI->getTypeForDecl()) {
5312 T = Existing;
5313 break;
5314 }
5315 }
5316 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005317 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005318 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5319 DI->setTypeForDecl(T);
5320 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005321 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005322 }
5323
5324 case TYPE_TEMPLATE_TYPE_PARM: {
5325 unsigned Idx = 0;
5326 unsigned Depth = Record[Idx++];
5327 unsigned Index = Record[Idx++];
5328 bool Pack = Record[Idx++];
5329 TemplateTypeParmDecl *D
5330 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5331 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5332 }
5333
5334 case TYPE_DEPENDENT_NAME: {
5335 unsigned Idx = 0;
5336 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5337 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5338 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5339 QualType Canon = readType(*Loc.F, Record, Idx);
5340 if (!Canon.isNull())
5341 Canon = Context.getCanonicalType(Canon);
5342 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5343 }
5344
5345 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5346 unsigned Idx = 0;
5347 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5348 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5349 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5350 unsigned NumArgs = Record[Idx++];
5351 SmallVector<TemplateArgument, 8> Args;
5352 Args.reserve(NumArgs);
5353 while (NumArgs--)
5354 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5355 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5356 Args.size(), Args.data());
5357 }
5358
5359 case TYPE_DEPENDENT_SIZED_ARRAY: {
5360 unsigned Idx = 0;
5361
5362 // ArrayType
5363 QualType ElementType = readType(*Loc.F, Record, Idx);
5364 ArrayType::ArraySizeModifier ASM
5365 = (ArrayType::ArraySizeModifier)Record[Idx++];
5366 unsigned IndexTypeQuals = Record[Idx++];
5367
5368 // DependentSizedArrayType
5369 Expr *NumElts = ReadExpr(*Loc.F);
5370 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5371
5372 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5373 IndexTypeQuals, Brackets);
5374 }
5375
5376 case TYPE_TEMPLATE_SPECIALIZATION: {
5377 unsigned Idx = 0;
5378 bool IsDependent = Record[Idx++];
5379 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5380 SmallVector<TemplateArgument, 8> Args;
5381 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5382 QualType Underlying = readType(*Loc.F, Record, Idx);
5383 QualType T;
5384 if (Underlying.isNull())
5385 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5386 Args.size());
5387 else
5388 T = Context.getTemplateSpecializationType(Name, Args.data(),
5389 Args.size(), Underlying);
5390 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5391 return T;
5392 }
5393
5394 case TYPE_ATOMIC: {
5395 if (Record.size() != 1) {
5396 Error("Incorrect encoding of atomic type");
5397 return QualType();
5398 }
5399 QualType ValueType = readType(*Loc.F, Record, Idx);
5400 return Context.getAtomicType(ValueType);
5401 }
5402 }
5403 llvm_unreachable("Invalid TypeCode!");
5404}
5405
Richard Smith564417a2014-03-20 21:47:22 +00005406void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5407 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005408 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005409 const RecordData &Record, unsigned &Idx) {
5410 ExceptionSpecificationType EST =
5411 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005412 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005413 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005414 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005415 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005416 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005417 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005418 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005419 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005420 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5421 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005422 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005423 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005424 }
5425}
5426
Guy Benyei11169dd2012-12-18 14:30:41 +00005427class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5428 ASTReader &Reader;
5429 ModuleFile &F;
5430 const ASTReader::RecordData &Record;
5431 unsigned &Idx;
5432
5433 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5434 unsigned &I) {
5435 return Reader.ReadSourceLocation(F, R, I);
5436 }
5437
5438 template<typename T>
5439 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5440 return Reader.ReadDeclAs<T>(F, Record, Idx);
5441 }
5442
5443public:
5444 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5445 const ASTReader::RecordData &Record, unsigned &Idx)
5446 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5447 { }
5448
5449 // We want compile-time assurance that we've enumerated all of
5450 // these, so unfortunately we have to declare them first, then
5451 // define them out-of-line.
5452#define ABSTRACT_TYPELOC(CLASS, PARENT)
5453#define TYPELOC(CLASS, PARENT) \
5454 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5455#include "clang/AST/TypeLocNodes.def"
5456
5457 void VisitFunctionTypeLoc(FunctionTypeLoc);
5458 void VisitArrayTypeLoc(ArrayTypeLoc);
5459};
5460
5461void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5462 // nothing to do
5463}
5464void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5465 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5466 if (TL.needsExtraLocalData()) {
5467 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5468 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5469 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5470 TL.setModeAttr(Record[Idx++]);
5471 }
5472}
5473void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5474 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5475}
5476void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5477 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5478}
Reid Kleckner8a365022013-06-24 17:51:48 +00005479void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5480 // nothing to do
5481}
Reid Kleckner0503a872013-12-05 01:23:43 +00005482void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5483 // nothing to do
5484}
Guy Benyei11169dd2012-12-18 14:30:41 +00005485void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5486 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5487}
5488void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5489 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5490}
5491void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5492 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5493}
5494void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5495 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5496 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5497}
5498void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5499 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5500 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5501 if (Record[Idx++])
5502 TL.setSizeExpr(Reader.ReadExpr(F));
5503 else
Craig Toppera13603a2014-05-22 05:54:18 +00005504 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005505}
5506void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5507 VisitArrayTypeLoc(TL);
5508}
5509void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5510 VisitArrayTypeLoc(TL);
5511}
5512void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5513 VisitArrayTypeLoc(TL);
5514}
5515void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5516 DependentSizedArrayTypeLoc TL) {
5517 VisitArrayTypeLoc(TL);
5518}
5519void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5520 DependentSizedExtVectorTypeLoc TL) {
5521 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5522}
5523void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5524 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5525}
5526void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5527 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5528}
5529void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5530 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5531 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5532 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5533 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005534 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5535 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005536 }
5537}
5538void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5539 VisitFunctionTypeLoc(TL);
5540}
5541void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5542 VisitFunctionTypeLoc(TL);
5543}
5544void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5545 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5546}
5547void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5548 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5549}
5550void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5551 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5552 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5553 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5554}
5555void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5556 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5557 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5558 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5559 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5560}
5561void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5562 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5563}
5564void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5565 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5566 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5567 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5568 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5569}
5570void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5571 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5572}
5573void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5574 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5575}
5576void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5577 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5578}
5579void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5580 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5581 if (TL.hasAttrOperand()) {
5582 SourceRange range;
5583 range.setBegin(ReadSourceLocation(Record, Idx));
5584 range.setEnd(ReadSourceLocation(Record, Idx));
5585 TL.setAttrOperandParensRange(range);
5586 }
5587 if (TL.hasAttrExprOperand()) {
5588 if (Record[Idx++])
5589 TL.setAttrExprOperand(Reader.ReadExpr(F));
5590 else
Craig Toppera13603a2014-05-22 05:54:18 +00005591 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005592 } else if (TL.hasAttrEnumOperand())
5593 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5594}
5595void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5596 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5597}
5598void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5599 SubstTemplateTypeParmTypeLoc TL) {
5600 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5601}
5602void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5603 SubstTemplateTypeParmPackTypeLoc TL) {
5604 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5605}
5606void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5607 TemplateSpecializationTypeLoc TL) {
5608 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5609 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5610 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5611 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5612 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5613 TL.setArgLocInfo(i,
5614 Reader.GetTemplateArgumentLocInfo(F,
5615 TL.getTypePtr()->getArg(i).getKind(),
5616 Record, Idx));
5617}
5618void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5619 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5620 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5621}
5622void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5623 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5624 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5625}
5626void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5627 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5628}
5629void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5630 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5631 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5632 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5633}
5634void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5635 DependentTemplateSpecializationTypeLoc TL) {
5636 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5637 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5638 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5639 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5640 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5641 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5642 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5643 TL.setArgLocInfo(I,
5644 Reader.GetTemplateArgumentLocInfo(F,
5645 TL.getTypePtr()->getArg(I).getKind(),
5646 Record, Idx));
5647}
5648void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5649 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5650}
5651void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5652 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5653}
5654void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5655 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005656 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5657 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5658 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5659 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5660 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5661 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005662 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5663 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5664}
5665void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5666 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5667}
5668void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5669 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5670 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5671 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5672}
5673
5674TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5675 const RecordData &Record,
5676 unsigned &Idx) {
5677 QualType InfoTy = readType(F, Record, Idx);
5678 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005679 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005680
5681 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5682 TypeLocReader TLR(*this, F, Record, Idx);
5683 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5684 TLR.Visit(TL);
5685 return TInfo;
5686}
5687
5688QualType ASTReader::GetType(TypeID ID) {
5689 unsigned FastQuals = ID & Qualifiers::FastMask;
5690 unsigned Index = ID >> Qualifiers::FastWidth;
5691
5692 if (Index < NUM_PREDEF_TYPE_IDS) {
5693 QualType T;
5694 switch ((PredefinedTypeIDs)Index) {
5695 case PREDEF_TYPE_NULL_ID: return QualType();
5696 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5697 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5698
5699 case PREDEF_TYPE_CHAR_U_ID:
5700 case PREDEF_TYPE_CHAR_S_ID:
5701 // FIXME: Check that the signedness of CharTy is correct!
5702 T = Context.CharTy;
5703 break;
5704
5705 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5706 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5707 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5708 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5709 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5710 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5711 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5712 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5713 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5714 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5715 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5716 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5717 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5718 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5719 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5720 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5721 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5722 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5723 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5724 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5725 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5726 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5727 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5728 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5729 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5730 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5731 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5732 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005733 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5734 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5735 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5736 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5737 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5738 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005739 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005740 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005741 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5742
5743 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5744 T = Context.getAutoRRefDeductType();
5745 break;
5746
5747 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5748 T = Context.ARCUnbridgedCastTy;
5749 break;
5750
5751 case PREDEF_TYPE_VA_LIST_TAG:
5752 T = Context.getVaListTagType();
5753 break;
5754
5755 case PREDEF_TYPE_BUILTIN_FN:
5756 T = Context.BuiltinFnTy;
5757 break;
5758 }
5759
5760 assert(!T.isNull() && "Unknown predefined type");
5761 return T.withFastQualifiers(FastQuals);
5762 }
5763
5764 Index -= NUM_PREDEF_TYPE_IDS;
5765 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5766 if (TypesLoaded[Index].isNull()) {
5767 TypesLoaded[Index] = readTypeRecord(Index);
5768 if (TypesLoaded[Index].isNull())
5769 return QualType();
5770
5771 TypesLoaded[Index]->setFromAST();
5772 if (DeserializationListener)
5773 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5774 TypesLoaded[Index]);
5775 }
5776
5777 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5778}
5779
5780QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5781 return GetType(getGlobalTypeID(F, LocalID));
5782}
5783
5784serialization::TypeID
5785ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5786 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5787 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5788
5789 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5790 return LocalID;
5791
5792 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5793 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5794 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5795
5796 unsigned GlobalIndex = LocalIndex + I->second;
5797 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5798}
5799
5800TemplateArgumentLocInfo
5801ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5802 TemplateArgument::ArgKind Kind,
5803 const RecordData &Record,
5804 unsigned &Index) {
5805 switch (Kind) {
5806 case TemplateArgument::Expression:
5807 return ReadExpr(F);
5808 case TemplateArgument::Type:
5809 return GetTypeSourceInfo(F, Record, Index);
5810 case TemplateArgument::Template: {
5811 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5812 Index);
5813 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5814 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5815 SourceLocation());
5816 }
5817 case TemplateArgument::TemplateExpansion: {
5818 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5819 Index);
5820 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5821 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5822 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5823 EllipsisLoc);
5824 }
5825 case TemplateArgument::Null:
5826 case TemplateArgument::Integral:
5827 case TemplateArgument::Declaration:
5828 case TemplateArgument::NullPtr:
5829 case TemplateArgument::Pack:
5830 // FIXME: Is this right?
5831 return TemplateArgumentLocInfo();
5832 }
5833 llvm_unreachable("unexpected template argument loc");
5834}
5835
5836TemplateArgumentLoc
5837ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5838 const RecordData &Record, unsigned &Index) {
5839 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5840
5841 if (Arg.getKind() == TemplateArgument::Expression) {
5842 if (Record[Index++]) // bool InfoHasSameExpr.
5843 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5844 }
5845 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5846 Record, Index));
5847}
5848
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005849const ASTTemplateArgumentListInfo*
5850ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5851 const RecordData &Record,
5852 unsigned &Index) {
5853 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5854 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5855 unsigned NumArgsAsWritten = Record[Index++];
5856 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5857 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5858 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5859 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5860}
5861
Guy Benyei11169dd2012-12-18 14:30:41 +00005862Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5863 return GetDecl(ID);
5864}
5865
Richard Smith50895422015-01-31 03:04:55 +00005866template<typename TemplateSpecializationDecl>
5867static void completeRedeclChainForTemplateSpecialization(Decl *D) {
5868 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
5869 TSD->getSpecializedTemplate()->LoadLazySpecializations();
5870}
5871
Richard Smith053f6c62014-05-16 23:01:30 +00005872void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005873 if (NumCurrentElementsDeserializing) {
5874 // We arrange to not care about the complete redeclaration chain while we're
5875 // deserializing. Just remember that the AST has marked this one as complete
5876 // but that it's not actually complete yet, so we know we still need to
5877 // complete it later.
5878 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5879 return;
5880 }
5881
Richard Smith053f6c62014-05-16 23:01:30 +00005882 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5883
Richard Smith053f6c62014-05-16 23:01:30 +00005884 // If this is a named declaration, complete it by looking it up
5885 // within its context.
5886 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00005887 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00005888 // all mergeable entities within it.
5889 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5890 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5891 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
5892 auto *II = Name.getAsIdentifierInfo();
5893 if (isa<TranslationUnitDecl>(DC) && II) {
5894 // Outside of C++, we don't have a lookup table for the TU, so update
5895 // the identifier instead. In C++, either way should work fine.
5896 if (II->isOutOfDate())
5897 updateOutOfDateIdentifier(*II);
5898 } else
5899 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00005900 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
5901 // FIXME: It'd be nice to do something a bit more targeted here.
5902 D->getDeclContext()->decls_begin();
Richard Smith053f6c62014-05-16 23:01:30 +00005903 }
5904 }
Richard Smith50895422015-01-31 03:04:55 +00005905
5906 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
5907 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
5908 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
5909 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
5910 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5911 if (auto *Template = FD->getPrimaryTemplate())
5912 Template->LoadLazySpecializations();
5913 }
Richard Smith053f6c62014-05-16 23:01:30 +00005914}
5915
Richard Smithc2bb8182015-03-24 06:36:48 +00005916uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
5917 const RecordData &Record,
5918 unsigned &Idx) {
5919 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
5920 Error("malformed AST file: missing C++ ctor initializers");
5921 return 0;
5922 }
5923
5924 unsigned LocalID = Record[Idx++];
5925 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
5926}
5927
5928CXXCtorInitializer **
5929ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
5930 RecordLocation Loc = getLocalBitOffset(Offset);
5931 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
5932 SavedStreamPosition SavedPosition(Cursor);
5933 Cursor.JumpToBit(Loc.Offset);
5934 ReadingKindTracker ReadingKind(Read_Decl, *this);
5935
5936 RecordData Record;
5937 unsigned Code = Cursor.ReadCode();
5938 unsigned RecCode = Cursor.readRecord(Code, Record);
5939 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
5940 Error("malformed AST file: missing C++ ctor initializers");
5941 return nullptr;
5942 }
5943
5944 unsigned Idx = 0;
5945 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
5946}
5947
Richard Smithcd45dbc2014-04-19 03:48:30 +00005948uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
5949 const RecordData &Record,
5950 unsigned &Idx) {
5951 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
5952 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005953 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00005954 }
5955
Guy Benyei11169dd2012-12-18 14:30:41 +00005956 unsigned LocalID = Record[Idx++];
5957 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5958}
5959
5960CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5961 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005962 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005963 SavedStreamPosition SavedPosition(Cursor);
5964 Cursor.JumpToBit(Loc.Offset);
5965 ReadingKindTracker ReadingKind(Read_Decl, *this);
5966 RecordData Record;
5967 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005968 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00005969 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005970 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00005971 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005972 }
5973
5974 unsigned Idx = 0;
5975 unsigned NumBases = Record[Idx++];
5976 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5977 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5978 for (unsigned I = 0; I != NumBases; ++I)
5979 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5980 return Bases;
5981}
5982
5983serialization::DeclID
5984ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5985 if (LocalID < NUM_PREDEF_DECL_IDS)
5986 return LocalID;
5987
5988 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5989 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5990 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5991
5992 return LocalID + I->second;
5993}
5994
5995bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5996 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00005997 // Predefined decls aren't from any module.
5998 if (ID < NUM_PREDEF_DECL_IDS)
5999 return false;
6000
Richard Smithbcda1a92015-07-12 23:51:20 +00006001 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6002 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006003}
6004
Douglas Gregor9f782892013-01-21 15:25:38 +00006005ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006006 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006007 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006008 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6009 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6010 return I->second;
6011}
6012
6013SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6014 if (ID < NUM_PREDEF_DECL_IDS)
6015 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006016
Guy Benyei11169dd2012-12-18 14:30:41 +00006017 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6018
6019 if (Index > DeclsLoaded.size()) {
6020 Error("declaration ID out-of-range for AST file");
6021 return SourceLocation();
6022 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006023
Guy Benyei11169dd2012-12-18 14:30:41 +00006024 if (Decl *D = DeclsLoaded[Index])
6025 return D->getLocation();
6026
6027 unsigned RawLocation = 0;
6028 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6029 return ReadSourceLocation(*Rec.F, RawLocation);
6030}
6031
Richard Smithfe620d22015-03-05 23:24:12 +00006032static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6033 switch (ID) {
6034 case PREDEF_DECL_NULL_ID:
6035 return nullptr;
6036
6037 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6038 return Context.getTranslationUnitDecl();
6039
6040 case PREDEF_DECL_OBJC_ID_ID:
6041 return Context.getObjCIdDecl();
6042
6043 case PREDEF_DECL_OBJC_SEL_ID:
6044 return Context.getObjCSelDecl();
6045
6046 case PREDEF_DECL_OBJC_CLASS_ID:
6047 return Context.getObjCClassDecl();
6048
6049 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6050 return Context.getObjCProtocolDecl();
6051
6052 case PREDEF_DECL_INT_128_ID:
6053 return Context.getInt128Decl();
6054
6055 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6056 return Context.getUInt128Decl();
6057
6058 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6059 return Context.getObjCInstanceTypeDecl();
6060
6061 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6062 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006063
6064 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6065 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006066 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006067 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006068}
6069
Richard Smithcd45dbc2014-04-19 03:48:30 +00006070Decl *ASTReader::GetExistingDecl(DeclID ID) {
6071 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006072 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6073 if (D) {
6074 // Track that we have merged the declaration with ID \p ID into the
6075 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006076 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006077 if (Merged.empty())
6078 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006079 }
Richard Smithfe620d22015-03-05 23:24:12 +00006080 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006081 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006082
Guy Benyei11169dd2012-12-18 14:30:41 +00006083 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6084
6085 if (Index >= DeclsLoaded.size()) {
6086 assert(0 && "declaration ID out-of-range for AST file");
6087 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006088 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006089 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006090
6091 return DeclsLoaded[Index];
6092}
6093
6094Decl *ASTReader::GetDecl(DeclID ID) {
6095 if (ID < NUM_PREDEF_DECL_IDS)
6096 return GetExistingDecl(ID);
6097
6098 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6099
6100 if (Index >= DeclsLoaded.size()) {
6101 assert(0 && "declaration ID out-of-range for AST file");
6102 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006103 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006104 }
6105
Guy Benyei11169dd2012-12-18 14:30:41 +00006106 if (!DeclsLoaded[Index]) {
6107 ReadDeclRecord(ID);
6108 if (DeserializationListener)
6109 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6110 }
6111
6112 return DeclsLoaded[Index];
6113}
6114
6115DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6116 DeclID GlobalID) {
6117 if (GlobalID < NUM_PREDEF_DECL_IDS)
6118 return GlobalID;
6119
6120 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6121 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6122 ModuleFile *Owner = I->second;
6123
6124 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6125 = M.GlobalToLocalDeclIDs.find(Owner);
6126 if (Pos == M.GlobalToLocalDeclIDs.end())
6127 return 0;
6128
6129 return GlobalID - Owner->BaseDeclID + Pos->second;
6130}
6131
6132serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6133 const RecordData &Record,
6134 unsigned &Idx) {
6135 if (Idx >= Record.size()) {
6136 Error("Corrupted AST file");
6137 return 0;
6138 }
6139
6140 return getGlobalDeclID(F, Record[Idx++]);
6141}
6142
6143/// \brief Resolve the offset of a statement into a statement.
6144///
6145/// This operation will read a new statement from the external
6146/// source each time it is called, and is meant to be used via a
6147/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6148Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6149 // Switch case IDs are per Decl.
6150 ClearSwitchCaseIDs();
6151
6152 // Offset here is a global offset across the entire chain.
6153 RecordLocation Loc = getLocalBitOffset(Offset);
6154 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6155 return ReadStmtFromStream(*Loc.F);
6156}
6157
6158namespace {
6159 class FindExternalLexicalDeclsVisitor {
6160 ASTReader &Reader;
6161 const DeclContext *DC;
6162 bool (*isKindWeWant)(Decl::Kind);
6163
6164 SmallVectorImpl<Decl*> &Decls;
6165 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6166
6167 public:
6168 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6169 bool (*isKindWeWant)(Decl::Kind),
6170 SmallVectorImpl<Decl*> &Decls)
6171 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6172 {
6173 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6174 PredefsVisited[I] = false;
6175 }
6176
Manuel Klimek9eff8b12015-05-20 10:29:23 +00006177 static bool visitPostorder(ModuleFile &M, void *UserData) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006178 FindExternalLexicalDeclsVisitor *This
6179 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6180
6181 ModuleFile::DeclContextInfosMap::iterator Info
6182 = M.DeclContextInfos.find(This->DC);
6183 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6184 return false;
6185
6186 // Load all of the declaration IDs
6187 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6188 *IDE = ID + Info->second.NumLexicalDecls;
6189 ID != IDE; ++ID) {
6190 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6191 continue;
6192
6193 // Don't add predefined declarations to the lexical context more
6194 // than once.
6195 if (ID->second < NUM_PREDEF_DECL_IDS) {
6196 if (This->PredefsVisited[ID->second])
6197 continue;
6198
6199 This->PredefsVisited[ID->second] = true;
6200 }
6201
6202 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6203 if (!This->DC->isDeclInLexicalTraversal(D))
6204 This->Decls.push_back(D);
6205 }
6206 }
6207
6208 return false;
6209 }
6210 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006211}
Guy Benyei11169dd2012-12-18 14:30:41 +00006212
6213ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6214 bool (*isKindWeWant)(Decl::Kind),
6215 SmallVectorImpl<Decl*> &Decls) {
6216 // There might be lexical decls in multiple modules, for the TU at
6217 // least. Walk all of the modules in the order they were loaded.
6218 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
Manuel Klimek9eff8b12015-05-20 10:29:23 +00006219 ModuleMgr.visitDepthFirst(
6220 nullptr, &FindExternalLexicalDeclsVisitor::visitPostorder, &Visitor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006221 ++NumLexicalDeclContextsRead;
6222 return ELR_Success;
6223}
6224
6225namespace {
6226
6227class DeclIDComp {
6228 ASTReader &Reader;
6229 ModuleFile &Mod;
6230
6231public:
6232 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6233
6234 bool operator()(LocalDeclID L, LocalDeclID R) const {
6235 SourceLocation LHS = getLocation(L);
6236 SourceLocation RHS = getLocation(R);
6237 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6238 }
6239
6240 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6241 SourceLocation RHS = getLocation(R);
6242 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6243 }
6244
6245 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6246 SourceLocation LHS = getLocation(L);
6247 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6248 }
6249
6250 SourceLocation getLocation(LocalDeclID ID) const {
6251 return Reader.getSourceManager().getFileLoc(
6252 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6253 }
6254};
6255
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006256}
Guy Benyei11169dd2012-12-18 14:30:41 +00006257
6258void ASTReader::FindFileRegionDecls(FileID File,
6259 unsigned Offset, unsigned Length,
6260 SmallVectorImpl<Decl *> &Decls) {
6261 SourceManager &SM = getSourceManager();
6262
6263 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6264 if (I == FileDeclIDs.end())
6265 return;
6266
6267 FileDeclsInfo &DInfo = I->second;
6268 if (DInfo.Decls.empty())
6269 return;
6270
6271 SourceLocation
6272 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6273 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6274
6275 DeclIDComp DIDComp(*this, *DInfo.Mod);
6276 ArrayRef<serialization::LocalDeclID>::iterator
6277 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6278 BeginLoc, DIDComp);
6279 if (BeginIt != DInfo.Decls.begin())
6280 --BeginIt;
6281
6282 // If we are pointing at a top-level decl inside an objc container, we need
6283 // to backtrack until we find it otherwise we will fail to report that the
6284 // region overlaps with an objc container.
6285 while (BeginIt != DInfo.Decls.begin() &&
6286 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6287 ->isTopLevelDeclInObjCContainer())
6288 --BeginIt;
6289
6290 ArrayRef<serialization::LocalDeclID>::iterator
6291 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6292 EndLoc, DIDComp);
6293 if (EndIt != DInfo.Decls.end())
6294 ++EndIt;
6295
6296 for (ArrayRef<serialization::LocalDeclID>::iterator
6297 DIt = BeginIt; DIt != EndIt; ++DIt)
6298 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6299}
6300
Richard Smith3b637412015-07-14 18:42:41 +00006301/// \brief Retrieve the "definitive" module file for the definition of the
6302/// given declaration context, if there is one.
6303///
6304/// The "definitive" module file is the only place where we need to look to
6305/// find information about the declarations within the given declaration
6306/// context. For example, C++ and Objective-C classes, C structs/unions, and
6307/// Objective-C protocols, categories, and extensions are all defined in a
6308/// single place in the source code, so they have definitive module files
6309/// associated with them. C++ namespaces, on the other hand, can have
6310/// definitions in multiple different module files.
6311///
6312/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6313/// NDEBUG checking.
6314static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6315 ASTReader &Reader) {
6316 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6317 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
6318
6319 return nullptr;
6320}
6321
Guy Benyei11169dd2012-12-18 14:30:41 +00006322namespace {
6323 /// \brief ModuleFile visitor used to perform name lookup into a
6324 /// declaration context.
6325 class DeclContextNameLookupVisitor {
6326 ASTReader &Reader;
Richard Smith8c913ec2014-08-14 02:21:01 +00006327 ArrayRef<const DeclContext *> Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006328 DeclarationName Name;
Richard Smith3b637412015-07-14 18:42:41 +00006329 ASTDeclContextNameLookupTrait::DeclNameKey NameKey;
6330 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00006331 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006332 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006333
6334 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006335 DeclContextNameLookupVisitor(ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00006336 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006337 SmallVectorImpl<NamedDecl *> &Decls,
6338 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
Richard Smith3b637412015-07-14 18:42:41 +00006339 : Reader(Reader), Name(Name),
6340 NameKey(ASTDeclContextNameLookupTrait::GetInternalKey(Name)),
6341 NameHash(ASTDeclContextNameLookupTrait::ComputeHash(NameKey)),
6342 Decls(Decls), DeclSet(DeclSet) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006343
Richard Smith3b637412015-07-14 18:42:41 +00006344 void visitContexts(ArrayRef<const DeclContext*> Contexts) {
6345 if (Contexts.empty())
6346 return;
6347 this->Contexts = Contexts;
6348
6349 // If we can definitively determine which module file to look into,
6350 // only look there. Otherwise, look in all module files.
6351 ModuleFile *Definitive;
6352 if (Contexts.size() == 1 &&
6353 (Definitive = getDefinitiveModuleFileFor(Contexts[0], Reader))) {
6354 visit(*Definitive, this);
6355 } else {
6356 Reader.getModuleManager().visit(&visit, this);
6357 }
6358 }
6359
6360 private:
Guy Benyei11169dd2012-12-18 14:30:41 +00006361 static bool visit(ModuleFile &M, void *UserData) {
6362 DeclContextNameLookupVisitor *This
6363 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6364
6365 // Check whether we have any visible declaration information for
6366 // this context in this module.
6367 ModuleFile::DeclContextInfosMap::iterator Info;
6368 bool FoundInfo = false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006369 for (auto *DC : This->Contexts) {
6370 Info = M.DeclContextInfos.find(DC);
6371 if (Info != M.DeclContextInfos.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006372 Info->second.NameLookupTableData) {
6373 FoundInfo = true;
6374 break;
6375 }
6376 }
6377
6378 if (!FoundInfo)
6379 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006380
Guy Benyei11169dd2012-12-18 14:30:41 +00006381 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006382 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006383 Info->second.NameLookupTableData;
6384 ASTDeclContextNameLookupTable::iterator Pos
Richard Smith3b637412015-07-14 18:42:41 +00006385 = LookupTable->find_hashed(This->NameKey, This->NameHash);
Guy Benyei11169dd2012-12-18 14:30:41 +00006386 if (Pos == LookupTable->end())
6387 return false;
6388
6389 bool FoundAnything = false;
6390 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6391 for (; Data.first != Data.second; ++Data.first) {
6392 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6393 if (!ND)
6394 continue;
6395
6396 if (ND->getDeclName() != This->Name) {
6397 // A name might be null because the decl's redeclarable part is
6398 // currently read before reading its name. The lookup is triggered by
6399 // building that decl (likely indirectly), and so it is later in the
6400 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006401 // FIXME: This should not happen; deserializing declarations should
6402 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006403 continue;
6404 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006405
Guy Benyei11169dd2012-12-18 14:30:41 +00006406 // Record this declaration.
6407 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006408 if (This->DeclSet.insert(ND).second)
6409 This->Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006410 }
6411
6412 return FoundAnything;
6413 }
6414 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006415}
Guy Benyei11169dd2012-12-18 14:30:41 +00006416
Richard Smith9ce12e32013-02-07 03:30:24 +00006417bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006418ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6419 DeclarationName Name) {
6420 assert(DC->hasExternalVisibleStorage() &&
6421 "DeclContext has no visible decls in storage");
6422 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006423 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006424
Richard Smith8c913ec2014-08-14 02:21:01 +00006425 Deserializing LookupResults(this);
6426
Guy Benyei11169dd2012-12-18 14:30:41 +00006427 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006428 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006429
Guy Benyei11169dd2012-12-18 14:30:41 +00006430 // Compute the declaration contexts we need to look into. Multiple such
6431 // declaration contexts occur when two declaration contexts from disjoint
6432 // modules get merged, e.g., when two namespaces with the same name are
6433 // independently defined in separate modules.
6434 SmallVector<const DeclContext *, 2> Contexts;
6435 Contexts.push_back(DC);
Richard Smith8c913ec2014-08-14 02:21:01 +00006436
Guy Benyei11169dd2012-12-18 14:30:41 +00006437 if (DC->isNamespace()) {
Richard Smith5fc18a92015-07-12 23:43:21 +00006438 auto Key = KeyDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6439 if (Key != KeyDecls.end()) {
6440 for (unsigned I = 0, N = Key->second.size(); I != N; ++I)
6441 Contexts.push_back(cast<DeclContext>(GetDecl(Key->second[I])));
Guy Benyei11169dd2012-12-18 14:30:41 +00006442 }
6443 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006444
Richard Smith3b637412015-07-14 18:42:41 +00006445 DeclContextNameLookupVisitor Visitor(*this, Name, Decls, DeclSet);
6446 Visitor.visitContexts(Contexts);
Richard Smith8c913ec2014-08-14 02:21:01 +00006447
6448 // If this might be an implicit special member function, then also search
6449 // all merged definitions of the surrounding class. We need to search them
6450 // individually, because finding an entity in one of them doesn't imply that
6451 // we can't find a different entity in another one.
Richard Smithcd45dbc2014-04-19 03:48:30 +00006452 if (isa<CXXRecordDecl>(DC)) {
Richard Smith02793752015-03-27 21:16:39 +00006453 auto Merged = MergedLookups.find(DC);
6454 if (Merged != MergedLookups.end()) {
6455 for (unsigned I = 0; I != Merged->second.size(); ++I) {
6456 const DeclContext *Context = Merged->second[I];
Richard Smith3b637412015-07-14 18:42:41 +00006457 Visitor.visitContexts(Context);
Richard Smith02793752015-03-27 21:16:39 +00006458 // We might have just added some more merged lookups. If so, our
6459 // iterator is now invalid, so grab a fresh one before continuing.
6460 Merged = MergedLookups.find(DC);
Richard Smithe0612472014-11-21 05:16:13 +00006461 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006462 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006463 }
6464
Guy Benyei11169dd2012-12-18 14:30:41 +00006465 ++NumVisibleDeclContextsRead;
6466 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006467 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006468}
6469
6470namespace {
6471 /// \brief ModuleFile visitor used to retrieve all visible names in a
6472 /// declaration context.
6473 class DeclContextAllNamesVisitor {
6474 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006475 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006476 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006477 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006478 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006479
6480 public:
6481 DeclContextAllNamesVisitor(ASTReader &Reader,
6482 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006483 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006484 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006485
6486 static bool visit(ModuleFile &M, void *UserData) {
6487 DeclContextAllNamesVisitor *This
6488 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6489
6490 // Check whether we have any visible declaration information for
6491 // this context in this module.
6492 ModuleFile::DeclContextInfosMap::iterator Info;
6493 bool FoundInfo = false;
6494 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6495 Info = M.DeclContextInfos.find(This->Contexts[I]);
6496 if (Info != M.DeclContextInfos.end() &&
6497 Info->second.NameLookupTableData) {
6498 FoundInfo = true;
6499 break;
6500 }
6501 }
6502
6503 if (!FoundInfo)
6504 return false;
6505
Richard Smith52e3fba2014-03-11 07:17:35 +00006506 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006507 Info->second.NameLookupTableData;
6508 bool FoundAnything = false;
6509 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006510 I = LookupTable->data_begin(), E = LookupTable->data_end();
6511 I != E;
6512 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006513 ASTDeclContextNameLookupTrait::data_type Data = *I;
6514 for (; Data.first != Data.second; ++Data.first) {
6515 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6516 *Data.first);
6517 if (!ND)
6518 continue;
6519
6520 // Record this declaration.
6521 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006522 if (This->DeclSet.insert(ND).second)
6523 This->Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006524 }
6525 }
6526
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006527 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006528 }
6529 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006530}
Guy Benyei11169dd2012-12-18 14:30:41 +00006531
6532void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6533 if (!DC->hasExternalVisibleStorage())
6534 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006535 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006536
6537 // Compute the declaration contexts we need to look into. Multiple such
6538 // declaration contexts occur when two declaration contexts from disjoint
6539 // modules get merged, e.g., when two namespaces with the same name are
6540 // independently defined in separate modules.
6541 SmallVector<const DeclContext *, 2> Contexts;
6542 Contexts.push_back(DC);
6543
6544 if (DC->isNamespace()) {
Richard Smith5fc18a92015-07-12 23:43:21 +00006545 KeyDeclsMap::iterator Key =
6546 KeyDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6547 if (Key != KeyDecls.end()) {
6548 for (unsigned I = 0, N = Key->second.size(); I != N; ++I)
6549 Contexts.push_back(cast<DeclContext>(GetDecl(Key->second[I])));
Guy Benyei11169dd2012-12-18 14:30:41 +00006550 }
6551 }
6552
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006553 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6554 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006555 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6556 ++NumVisibleDeclContextsRead;
6557
Craig Topper79be4cd2013-07-05 04:33:53 +00006558 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006559 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6560 }
6561 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6562}
6563
6564/// \brief Under non-PCH compilation the consumer receives the objc methods
6565/// before receiving the implementation, and codegen depends on this.
6566/// We simulate this by deserializing and passing to consumer the methods of the
6567/// implementation before passing the deserialized implementation decl.
6568static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6569 ASTConsumer *Consumer) {
6570 assert(ImplD && Consumer);
6571
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006572 for (auto *I : ImplD->methods())
6573 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006574
6575 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6576}
6577
6578void ASTReader::PassInterestingDeclsToConsumer() {
6579 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006580
6581 if (PassingDeclsToConsumer)
6582 return;
6583
6584 // Guard variable to avoid recursively redoing the process of passing
6585 // decls to consumer.
6586 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6587 true);
6588
Richard Smith9e2341d2015-03-23 03:25:59 +00006589 // Ensure that we've loaded all potentially-interesting declarations
6590 // that need to be eagerly loaded.
6591 for (auto ID : EagerlyDeserializedDecls)
6592 GetDecl(ID);
6593 EagerlyDeserializedDecls.clear();
6594
Guy Benyei11169dd2012-12-18 14:30:41 +00006595 while (!InterestingDecls.empty()) {
6596 Decl *D = InterestingDecls.front();
6597 InterestingDecls.pop_front();
6598
6599 PassInterestingDeclToConsumer(D);
6600 }
6601}
6602
6603void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6604 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6605 PassObjCImplDeclToConsumer(ImplD, Consumer);
6606 else
6607 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6608}
6609
6610void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6611 this->Consumer = Consumer;
6612
Richard Smith9e2341d2015-03-23 03:25:59 +00006613 if (Consumer)
6614 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006615
6616 if (DeserializationListener)
6617 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006618}
6619
6620void ASTReader::PrintStats() {
6621 std::fprintf(stderr, "*** AST File Statistics:\n");
6622
6623 unsigned NumTypesLoaded
6624 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6625 QualType());
6626 unsigned NumDeclsLoaded
6627 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006628 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006629 unsigned NumIdentifiersLoaded
6630 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6631 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006632 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006633 unsigned NumMacrosLoaded
6634 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6635 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006636 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006637 unsigned NumSelectorsLoaded
6638 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6639 SelectorsLoaded.end(),
6640 Selector());
6641
6642 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6643 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6644 NumSLocEntriesRead, TotalNumSLocEntries,
6645 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6646 if (!TypesLoaded.empty())
6647 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6648 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6649 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6650 if (!DeclsLoaded.empty())
6651 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6652 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6653 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6654 if (!IdentifiersLoaded.empty())
6655 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6656 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6657 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6658 if (!MacrosLoaded.empty())
6659 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6660 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6661 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6662 if (!SelectorsLoaded.empty())
6663 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6664 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6665 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6666 if (TotalNumStatements)
6667 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6668 NumStatementsRead, TotalNumStatements,
6669 ((float)NumStatementsRead/TotalNumStatements * 100));
6670 if (TotalNumMacros)
6671 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6672 NumMacrosRead, TotalNumMacros,
6673 ((float)NumMacrosRead/TotalNumMacros * 100));
6674 if (TotalLexicalDeclContexts)
6675 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6676 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6677 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6678 * 100));
6679 if (TotalVisibleDeclContexts)
6680 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6681 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6682 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6683 * 100));
6684 if (TotalNumMethodPoolEntries) {
6685 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6686 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6687 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6688 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006689 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006690 if (NumMethodPoolLookups) {
6691 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6692 NumMethodPoolHits, NumMethodPoolLookups,
6693 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6694 }
6695 if (NumMethodPoolTableLookups) {
6696 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6697 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6698 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6699 * 100.0));
6700 }
6701
Douglas Gregor00a50f72013-01-25 00:38:33 +00006702 if (NumIdentifierLookupHits) {
6703 std::fprintf(stderr,
6704 " %u / %u identifier table lookups succeeded (%f%%)\n",
6705 NumIdentifierLookupHits, NumIdentifierLookups,
6706 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6707 }
6708
Douglas Gregore060e572013-01-25 01:03:03 +00006709 if (GlobalIndex) {
6710 std::fprintf(stderr, "\n");
6711 GlobalIndex->printStats();
6712 }
6713
Guy Benyei11169dd2012-12-18 14:30:41 +00006714 std::fprintf(stderr, "\n");
6715 dump();
6716 std::fprintf(stderr, "\n");
6717}
6718
6719template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6720static void
6721dumpModuleIDMap(StringRef Name,
6722 const ContinuousRangeMap<Key, ModuleFile *,
6723 InitialCapacity> &Map) {
6724 if (Map.begin() == Map.end())
6725 return;
6726
6727 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6728 llvm::errs() << Name << ":\n";
6729 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6730 I != IEnd; ++I) {
6731 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6732 << "\n";
6733 }
6734}
6735
6736void ASTReader::dump() {
6737 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6738 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6739 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6740 dumpModuleIDMap("Global type map", GlobalTypeMap);
6741 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6742 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6743 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6744 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6745 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6746 dumpModuleIDMap("Global preprocessed entity map",
6747 GlobalPreprocessedEntityMap);
6748
6749 llvm::errs() << "\n*** PCH/Modules Loaded:";
6750 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6751 MEnd = ModuleMgr.end();
6752 M != MEnd; ++M)
6753 (*M)->dump();
6754}
6755
6756/// Return the amount of memory used by memory buffers, breaking down
6757/// by heap-backed versus mmap'ed memory.
6758void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6759 for (ModuleConstIterator I = ModuleMgr.begin(),
6760 E = ModuleMgr.end(); I != E; ++I) {
6761 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6762 size_t bytes = buf->getBufferSize();
6763 switch (buf->getBufferKind()) {
6764 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6765 sizes.malloc_bytes += bytes;
6766 break;
6767 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6768 sizes.mmap_bytes += bytes;
6769 break;
6770 }
6771 }
6772 }
6773}
6774
6775void ASTReader::InitializeSema(Sema &S) {
6776 SemaObj = &S;
6777 S.addExternalSource(this);
6778
6779 // Makes sure any declarations that were deserialized "too early"
6780 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006781 for (uint64_t ID : PreloadedDeclIDs) {
6782 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6783 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006784 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006785 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006786
Richard Smith3d8e97e2013-10-18 06:54:39 +00006787 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006788 if (!FPPragmaOptions.empty()) {
6789 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6790 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6791 }
6792
Richard Smith3d8e97e2013-10-18 06:54:39 +00006793 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006794 if (!OpenCLExtensions.empty()) {
6795 unsigned I = 0;
6796#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6797#include "clang/Basic/OpenCLExtensions.def"
6798
6799 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6800 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006801
6802 UpdateSema();
6803}
6804
6805void ASTReader::UpdateSema() {
6806 assert(SemaObj && "no Sema to update");
6807
6808 // Load the offsets of the declarations that Sema references.
6809 // They will be lazily deserialized when needed.
6810 if (!SemaDeclRefs.empty()) {
6811 assert(SemaDeclRefs.size() % 2 == 0);
6812 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6813 if (!SemaObj->StdNamespace)
6814 SemaObj->StdNamespace = SemaDeclRefs[I];
6815 if (!SemaObj->StdBadAlloc)
6816 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6817 }
6818 SemaDeclRefs.clear();
6819 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006820
6821 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6822 // encountered the pragma in the source.
6823 if(OptimizeOffPragmaLocation.isValid())
6824 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006825}
6826
6827IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6828 // Note that we are loading an identifier.
6829 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006830 StringRef Name(NameStart, NameEnd - NameStart);
6831
6832 // If there is a global index, look there first to determine which modules
6833 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006834 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00006835 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00006836 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006837 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6838 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006839 }
6840 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006841 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006842 NumIdentifierLookups,
6843 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006844 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006845 IdentifierInfo *II = Visitor.getIdentifierInfo();
6846 markIdentifierUpToDate(II);
6847 return II;
6848}
6849
6850namespace clang {
6851 /// \brief An identifier-lookup iterator that enumerates all of the
6852 /// identifiers stored within a set of AST files.
6853 class ASTIdentifierIterator : public IdentifierIterator {
6854 /// \brief The AST reader whose identifiers are being enumerated.
6855 const ASTReader &Reader;
6856
6857 /// \brief The current index into the chain of AST files stored in
6858 /// the AST reader.
6859 unsigned Index;
6860
6861 /// \brief The current position within the identifier lookup table
6862 /// of the current AST file.
6863 ASTIdentifierLookupTable::key_iterator Current;
6864
6865 /// \brief The end position within the identifier lookup table of
6866 /// the current AST file.
6867 ASTIdentifierLookupTable::key_iterator End;
6868
6869 public:
6870 explicit ASTIdentifierIterator(const ASTReader &Reader);
6871
Craig Topper3e89dfe2014-03-13 02:13:41 +00006872 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006873 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006874}
Guy Benyei11169dd2012-12-18 14:30:41 +00006875
6876ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6877 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6878 ASTIdentifierLookupTable *IdTable
6879 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6880 Current = IdTable->key_begin();
6881 End = IdTable->key_end();
6882}
6883
6884StringRef ASTIdentifierIterator::Next() {
6885 while (Current == End) {
6886 // If we have exhausted all of our AST files, we're done.
6887 if (Index == 0)
6888 return StringRef();
6889
6890 --Index;
6891 ASTIdentifierLookupTable *IdTable
6892 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6893 IdentifierLookupTable;
6894 Current = IdTable->key_begin();
6895 End = IdTable->key_end();
6896 }
6897
6898 // We have any identifiers remaining in the current AST file; return
6899 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006900 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006901 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006902 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006903}
6904
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006905IdentifierIterator *ASTReader::getIdentifiers() {
6906 if (!loadGlobalIndex())
6907 return GlobalIndex->createIdentifierIterator();
6908
Guy Benyei11169dd2012-12-18 14:30:41 +00006909 return new ASTIdentifierIterator(*this);
6910}
6911
6912namespace clang { namespace serialization {
6913 class ReadMethodPoolVisitor {
6914 ASTReader &Reader;
6915 Selector Sel;
6916 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006917 unsigned InstanceBits;
6918 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006919 bool InstanceHasMoreThanOneDecl;
6920 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006921 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6922 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006923
6924 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00006925 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00006926 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00006927 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00006928 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
6929 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00006930
Guy Benyei11169dd2012-12-18 14:30:41 +00006931 static bool visit(ModuleFile &M, void *UserData) {
6932 ReadMethodPoolVisitor *This
6933 = static_cast<ReadMethodPoolVisitor *>(UserData);
6934
6935 if (!M.SelectorLookupTable)
6936 return false;
6937
6938 // If we've already searched this module file, skip it now.
6939 if (M.Generation <= This->PriorGeneration)
6940 return true;
6941
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006942 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006943 ASTSelectorLookupTable *PoolTable
6944 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6945 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6946 if (Pos == PoolTable->end())
6947 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006948
6949 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006950 ++This->Reader.NumSelectorsRead;
6951 // FIXME: Not quite happy with the statistics here. We probably should
6952 // disable this tracking when called via LoadSelector.
6953 // Also, should entries without methods count as misses?
6954 ++This->Reader.NumMethodPoolEntriesRead;
6955 ASTSelectorLookupTrait::data_type Data = *Pos;
6956 if (This->Reader.DeserializationListener)
6957 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6958 This->Sel);
6959
6960 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6961 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006962 This->InstanceBits = Data.InstanceBits;
6963 This->FactoryBits = Data.FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006964 This->InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
6965 This->FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00006966 return true;
6967 }
6968
6969 /// \brief Retrieve the instance methods found by this visitor.
6970 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6971 return InstanceMethods;
6972 }
6973
6974 /// \brief Retrieve the instance methods found by this visitor.
6975 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6976 return FactoryMethods;
6977 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006978
6979 unsigned getInstanceBits() const { return InstanceBits; }
6980 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00006981 bool instanceHasMoreThanOneDecl() const {
6982 return InstanceHasMoreThanOneDecl;
6983 }
6984 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006985 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006986} } // end namespace clang::serialization
Guy Benyei11169dd2012-12-18 14:30:41 +00006987
6988/// \brief Add the given set of methods to the method list.
6989static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6990 ObjCMethodList &List) {
6991 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6992 S.addMethodToGlobalList(&List, Methods[I]);
6993 }
6994}
6995
6996void ASTReader::ReadMethodPool(Selector Sel) {
6997 // Get the selector generation and update it to the current generation.
6998 unsigned &Generation = SelectorGeneration[Sel];
6999 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007000 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007001
7002 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007003 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007004 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7005 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
7006
7007 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007008 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007009 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007010
7011 ++NumMethodPoolHits;
7012
Guy Benyei11169dd2012-12-18 14:30:41 +00007013 if (!getSema())
7014 return;
7015
7016 Sema &S = *getSema();
7017 Sema::GlobalMethodPool::iterator Pos
7018 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007019
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007020 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007021 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007022 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007023 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007024
7025 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7026 // when building a module we keep every method individually and may need to
7027 // update hasMoreThanOneDecl as we add the methods.
7028 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7029 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007030}
7031
7032void ASTReader::ReadKnownNamespaces(
7033 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7034 Namespaces.clear();
7035
7036 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7037 if (NamespaceDecl *Namespace
7038 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7039 Namespaces.push_back(Namespace);
7040 }
7041}
7042
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007043void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007044 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007045 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7046 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007047 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007048 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007049 Undefined.insert(std::make_pair(D, Loc));
7050 }
7051}
Nick Lewycky8334af82013-01-26 00:35:08 +00007052
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007053void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7054 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7055 Exprs) {
7056 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7057 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7058 uint64_t Count = DelayedDeleteExprs[Idx++];
7059 for (uint64_t C = 0; C < Count; ++C) {
7060 SourceLocation DeleteLoc =
7061 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7062 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7063 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7064 }
7065 }
7066}
7067
Guy Benyei11169dd2012-12-18 14:30:41 +00007068void ASTReader::ReadTentativeDefinitions(
7069 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7070 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7071 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7072 if (Var)
7073 TentativeDefs.push_back(Var);
7074 }
7075 TentativeDefinitions.clear();
7076}
7077
7078void ASTReader::ReadUnusedFileScopedDecls(
7079 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7080 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7081 DeclaratorDecl *D
7082 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7083 if (D)
7084 Decls.push_back(D);
7085 }
7086 UnusedFileScopedDecls.clear();
7087}
7088
7089void ASTReader::ReadDelegatingConstructors(
7090 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7091 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7092 CXXConstructorDecl *D
7093 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7094 if (D)
7095 Decls.push_back(D);
7096 }
7097 DelegatingCtorDecls.clear();
7098}
7099
7100void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7101 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7102 TypedefNameDecl *D
7103 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7104 if (D)
7105 Decls.push_back(D);
7106 }
7107 ExtVectorDecls.clear();
7108}
7109
Nico Weber72889432014-09-06 01:25:55 +00007110void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7111 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7112 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7113 ++I) {
7114 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7115 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7116 if (D)
7117 Decls.insert(D);
7118 }
7119 UnusedLocalTypedefNameCandidates.clear();
7120}
7121
Guy Benyei11169dd2012-12-18 14:30:41 +00007122void ASTReader::ReadReferencedSelectors(
7123 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7124 if (ReferencedSelectorsData.empty())
7125 return;
7126
7127 // If there are @selector references added them to its pool. This is for
7128 // implementation of -Wselector.
7129 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7130 unsigned I = 0;
7131 while (I < DataSize) {
7132 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7133 SourceLocation SelLoc
7134 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7135 Sels.push_back(std::make_pair(Sel, SelLoc));
7136 }
7137 ReferencedSelectorsData.clear();
7138}
7139
7140void ASTReader::ReadWeakUndeclaredIdentifiers(
7141 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7142 if (WeakUndeclaredIdentifiers.empty())
7143 return;
7144
7145 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7146 IdentifierInfo *WeakId
7147 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7148 IdentifierInfo *AliasId
7149 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7150 SourceLocation Loc
7151 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7152 bool Used = WeakUndeclaredIdentifiers[I++];
7153 WeakInfo WI(AliasId, Loc);
7154 WI.setUsed(Used);
7155 WeakIDs.push_back(std::make_pair(WeakId, WI));
7156 }
7157 WeakUndeclaredIdentifiers.clear();
7158}
7159
7160void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7161 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7162 ExternalVTableUse VT;
7163 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7164 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7165 VT.DefinitionRequired = VTableUses[Idx++];
7166 VTables.push_back(VT);
7167 }
7168
7169 VTableUses.clear();
7170}
7171
7172void ASTReader::ReadPendingInstantiations(
7173 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7174 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7175 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7176 SourceLocation Loc
7177 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7178
7179 Pending.push_back(std::make_pair(D, Loc));
7180 }
7181 PendingInstantiations.clear();
7182}
7183
Richard Smithe40f2ba2013-08-07 21:41:30 +00007184void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007185 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007186 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7187 /* In loop */) {
7188 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7189
7190 LateParsedTemplate *LT = new LateParsedTemplate;
7191 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7192
7193 ModuleFile *F = getOwningModuleFile(LT->D);
7194 assert(F && "No module");
7195
7196 unsigned TokN = LateParsedTemplates[Idx++];
7197 LT->Toks.reserve(TokN);
7198 for (unsigned T = 0; T < TokN; ++T)
7199 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7200
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007201 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007202 }
7203
7204 LateParsedTemplates.clear();
7205}
7206
Guy Benyei11169dd2012-12-18 14:30:41 +00007207void ASTReader::LoadSelector(Selector Sel) {
7208 // It would be complicated to avoid reading the methods anyway. So don't.
7209 ReadMethodPool(Sel);
7210}
7211
7212void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7213 assert(ID && "Non-zero identifier ID required");
7214 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7215 IdentifiersLoaded[ID - 1] = II;
7216 if (DeserializationListener)
7217 DeserializationListener->IdentifierRead(ID, II);
7218}
7219
7220/// \brief Set the globally-visible declarations associated with the given
7221/// identifier.
7222///
7223/// If the AST reader is currently in a state where the given declaration IDs
7224/// cannot safely be resolved, they are queued until it is safe to resolve
7225/// them.
7226///
7227/// \param II an IdentifierInfo that refers to one or more globally-visible
7228/// declarations.
7229///
7230/// \param DeclIDs the set of declaration IDs with the name @p II that are
7231/// visible at global scope.
7232///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007233/// \param Decls if non-null, this vector will be populated with the set of
7234/// deserialized declarations. These declarations will not be pushed into
7235/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007236void
7237ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7238 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007239 SmallVectorImpl<Decl *> *Decls) {
7240 if (NumCurrentElementsDeserializing && !Decls) {
7241 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007242 return;
7243 }
7244
7245 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007246 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007247 // Queue this declaration so that it will be added to the
7248 // translation unit scope and identifier's declaration chain
7249 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007250 PreloadedDeclIDs.push_back(DeclIDs[I]);
7251 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007252 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007253
7254 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7255
7256 // If we're simply supposed to record the declarations, do so now.
7257 if (Decls) {
7258 Decls->push_back(D);
7259 continue;
7260 }
7261
7262 // Introduce this declaration into the translation-unit scope
7263 // and add it to the declaration chain for this identifier, so
7264 // that (unqualified) name lookup will find it.
7265 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007266 }
7267}
7268
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007269IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007270 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007271 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007272
7273 if (IdentifiersLoaded.empty()) {
7274 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007275 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007276 }
7277
7278 ID -= 1;
7279 if (!IdentifiersLoaded[ID]) {
7280 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7281 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7282 ModuleFile *M = I->second;
7283 unsigned Index = ID - M->BaseIdentifierID;
7284 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7285
7286 // All of the strings in the AST file are preceded by a 16-bit length.
7287 // Extract that 16-bit length to avoid having to execute strlen().
7288 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7289 // unsigned integers. This is important to avoid integer overflow when
7290 // we cast them to 'unsigned'.
7291 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7292 unsigned StrLen = (((unsigned) StrLenPtr[0])
7293 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007294 IdentifiersLoaded[ID]
7295 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007296 if (DeserializationListener)
7297 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7298 }
7299
7300 return IdentifiersLoaded[ID];
7301}
7302
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007303IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7304 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007305}
7306
7307IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7308 if (LocalID < NUM_PREDEF_IDENT_IDS)
7309 return LocalID;
7310
7311 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7312 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7313 assert(I != M.IdentifierRemap.end()
7314 && "Invalid index into identifier index remap");
7315
7316 return LocalID + I->second;
7317}
7318
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007319MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007320 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007321 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007322
7323 if (MacrosLoaded.empty()) {
7324 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007325 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007326 }
7327
7328 ID -= NUM_PREDEF_MACRO_IDS;
7329 if (!MacrosLoaded[ID]) {
7330 GlobalMacroMapType::iterator I
7331 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7332 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7333 ModuleFile *M = I->second;
7334 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007335 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7336
7337 if (DeserializationListener)
7338 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7339 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007340 }
7341
7342 return MacrosLoaded[ID];
7343}
7344
7345MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7346 if (LocalID < NUM_PREDEF_MACRO_IDS)
7347 return LocalID;
7348
7349 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7350 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7351 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7352
7353 return LocalID + I->second;
7354}
7355
7356serialization::SubmoduleID
7357ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7358 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7359 return LocalID;
7360
7361 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7362 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7363 assert(I != M.SubmoduleRemap.end()
7364 && "Invalid index into submodule index remap");
7365
7366 return LocalID + I->second;
7367}
7368
7369Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7370 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7371 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007372 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007373 }
7374
7375 if (GlobalID > SubmodulesLoaded.size()) {
7376 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007377 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007378 }
7379
7380 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7381}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007382
7383Module *ASTReader::getModule(unsigned ID) {
7384 return getSubmodule(ID);
7385}
7386
Adrian Prantl15bcf702015-06-30 17:39:43 +00007387ExternalASTSource::ASTSourceDescriptor
7388ASTReader::getSourceDescriptor(const Module &M) {
7389 StringRef Dir, Filename;
7390 if (M.Directory)
7391 Dir = M.Directory->getName();
7392 if (auto *File = M.getASTFile())
7393 Filename = File->getName();
7394 return ASTReader::ASTSourceDescriptor{
7395 M.getFullModuleName(), Dir, Filename,
7396 M.Signature
7397 };
7398}
7399
7400llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7401ASTReader::getSourceDescriptor(unsigned ID) {
7402 if (const Module *M = getSubmodule(ID))
7403 return getSourceDescriptor(*M);
7404
7405 // If there is only a single PCH, return it instead.
7406 // Chained PCH are not suported.
7407 if (ModuleMgr.size() == 1) {
7408 ModuleFile &MF = ModuleMgr.getPrimaryModule();
7409 return ASTReader::ASTSourceDescriptor{
7410 MF.OriginalSourceFileName, MF.OriginalDir,
7411 MF.FileName,
7412 MF.Signature
7413 };
7414 }
7415 return None;
7416}
7417
Guy Benyei11169dd2012-12-18 14:30:41 +00007418Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7419 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7420}
7421
7422Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7423 if (ID == 0)
7424 return Selector();
7425
7426 if (ID > SelectorsLoaded.size()) {
7427 Error("selector ID out of range in AST file");
7428 return Selector();
7429 }
7430
Craig Toppera13603a2014-05-22 05:54:18 +00007431 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007432 // Load this selector from the selector table.
7433 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7434 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7435 ModuleFile &M = *I->second;
7436 ASTSelectorLookupTrait Trait(*this, M);
7437 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7438 SelectorsLoaded[ID - 1] =
7439 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7440 if (DeserializationListener)
7441 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7442 }
7443
7444 return SelectorsLoaded[ID - 1];
7445}
7446
7447Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7448 return DecodeSelector(ID);
7449}
7450
7451uint32_t ASTReader::GetNumExternalSelectors() {
7452 // ID 0 (the null selector) is considered an external selector.
7453 return getTotalNumSelectors() + 1;
7454}
7455
7456serialization::SelectorID
7457ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7458 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7459 return LocalID;
7460
7461 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7462 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7463 assert(I != M.SelectorRemap.end()
7464 && "Invalid index into selector index remap");
7465
7466 return LocalID + I->second;
7467}
7468
7469DeclarationName
7470ASTReader::ReadDeclarationName(ModuleFile &F,
7471 const RecordData &Record, unsigned &Idx) {
7472 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7473 switch (Kind) {
7474 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007475 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007476
7477 case DeclarationName::ObjCZeroArgSelector:
7478 case DeclarationName::ObjCOneArgSelector:
7479 case DeclarationName::ObjCMultiArgSelector:
7480 return DeclarationName(ReadSelector(F, Record, Idx));
7481
7482 case DeclarationName::CXXConstructorName:
7483 return Context.DeclarationNames.getCXXConstructorName(
7484 Context.getCanonicalType(readType(F, Record, Idx)));
7485
7486 case DeclarationName::CXXDestructorName:
7487 return Context.DeclarationNames.getCXXDestructorName(
7488 Context.getCanonicalType(readType(F, Record, Idx)));
7489
7490 case DeclarationName::CXXConversionFunctionName:
7491 return Context.DeclarationNames.getCXXConversionFunctionName(
7492 Context.getCanonicalType(readType(F, Record, Idx)));
7493
7494 case DeclarationName::CXXOperatorName:
7495 return Context.DeclarationNames.getCXXOperatorName(
7496 (OverloadedOperatorKind)Record[Idx++]);
7497
7498 case DeclarationName::CXXLiteralOperatorName:
7499 return Context.DeclarationNames.getCXXLiteralOperatorName(
7500 GetIdentifierInfo(F, Record, Idx));
7501
7502 case DeclarationName::CXXUsingDirective:
7503 return DeclarationName::getUsingDirectiveName();
7504 }
7505
7506 llvm_unreachable("Invalid NameKind!");
7507}
7508
7509void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7510 DeclarationNameLoc &DNLoc,
7511 DeclarationName Name,
7512 const RecordData &Record, unsigned &Idx) {
7513 switch (Name.getNameKind()) {
7514 case DeclarationName::CXXConstructorName:
7515 case DeclarationName::CXXDestructorName:
7516 case DeclarationName::CXXConversionFunctionName:
7517 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7518 break;
7519
7520 case DeclarationName::CXXOperatorName:
7521 DNLoc.CXXOperatorName.BeginOpNameLoc
7522 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7523 DNLoc.CXXOperatorName.EndOpNameLoc
7524 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7525 break;
7526
7527 case DeclarationName::CXXLiteralOperatorName:
7528 DNLoc.CXXLiteralOperatorName.OpNameLoc
7529 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7530 break;
7531
7532 case DeclarationName::Identifier:
7533 case DeclarationName::ObjCZeroArgSelector:
7534 case DeclarationName::ObjCOneArgSelector:
7535 case DeclarationName::ObjCMultiArgSelector:
7536 case DeclarationName::CXXUsingDirective:
7537 break;
7538 }
7539}
7540
7541void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7542 DeclarationNameInfo &NameInfo,
7543 const RecordData &Record, unsigned &Idx) {
7544 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7545 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7546 DeclarationNameLoc DNLoc;
7547 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7548 NameInfo.setInfo(DNLoc);
7549}
7550
7551void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7552 const RecordData &Record, unsigned &Idx) {
7553 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7554 unsigned NumTPLists = Record[Idx++];
7555 Info.NumTemplParamLists = NumTPLists;
7556 if (NumTPLists) {
7557 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7558 for (unsigned i=0; i != NumTPLists; ++i)
7559 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7560 }
7561}
7562
7563TemplateName
7564ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7565 unsigned &Idx) {
7566 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7567 switch (Kind) {
7568 case TemplateName::Template:
7569 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7570
7571 case TemplateName::OverloadedTemplate: {
7572 unsigned size = Record[Idx++];
7573 UnresolvedSet<8> Decls;
7574 while (size--)
7575 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7576
7577 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7578 }
7579
7580 case TemplateName::QualifiedTemplate: {
7581 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7582 bool hasTemplKeyword = Record[Idx++];
7583 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7584 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7585 }
7586
7587 case TemplateName::DependentTemplate: {
7588 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7589 if (Record[Idx++]) // isIdentifier
7590 return Context.getDependentTemplateName(NNS,
7591 GetIdentifierInfo(F, Record,
7592 Idx));
7593 return Context.getDependentTemplateName(NNS,
7594 (OverloadedOperatorKind)Record[Idx++]);
7595 }
7596
7597 case TemplateName::SubstTemplateTemplateParm: {
7598 TemplateTemplateParmDecl *param
7599 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7600 if (!param) return TemplateName();
7601 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7602 return Context.getSubstTemplateTemplateParm(param, replacement);
7603 }
7604
7605 case TemplateName::SubstTemplateTemplateParmPack: {
7606 TemplateTemplateParmDecl *Param
7607 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7608 if (!Param)
7609 return TemplateName();
7610
7611 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7612 if (ArgPack.getKind() != TemplateArgument::Pack)
7613 return TemplateName();
7614
7615 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7616 }
7617 }
7618
7619 llvm_unreachable("Unhandled template name kind!");
7620}
7621
7622TemplateArgument
7623ASTReader::ReadTemplateArgument(ModuleFile &F,
7624 const RecordData &Record, unsigned &Idx) {
7625 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7626 switch (Kind) {
7627 case TemplateArgument::Null:
7628 return TemplateArgument();
7629 case TemplateArgument::Type:
7630 return TemplateArgument(readType(F, Record, Idx));
7631 case TemplateArgument::Declaration: {
7632 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007633 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007634 }
7635 case TemplateArgument::NullPtr:
7636 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7637 case TemplateArgument::Integral: {
7638 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7639 QualType T = readType(F, Record, Idx);
7640 return TemplateArgument(Context, Value, T);
7641 }
7642 case TemplateArgument::Template:
7643 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7644 case TemplateArgument::TemplateExpansion: {
7645 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007646 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007647 if (unsigned NumExpansions = Record[Idx++])
7648 NumTemplateExpansions = NumExpansions - 1;
7649 return TemplateArgument(Name, NumTemplateExpansions);
7650 }
7651 case TemplateArgument::Expression:
7652 return TemplateArgument(ReadExpr(F));
7653 case TemplateArgument::Pack: {
7654 unsigned NumArgs = Record[Idx++];
7655 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7656 for (unsigned I = 0; I != NumArgs; ++I)
7657 Args[I] = ReadTemplateArgument(F, Record, Idx);
7658 return TemplateArgument(Args, NumArgs);
7659 }
7660 }
7661
7662 llvm_unreachable("Unhandled template argument kind!");
7663}
7664
7665TemplateParameterList *
7666ASTReader::ReadTemplateParameterList(ModuleFile &F,
7667 const RecordData &Record, unsigned &Idx) {
7668 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7669 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7670 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7671
7672 unsigned NumParams = Record[Idx++];
7673 SmallVector<NamedDecl *, 16> Params;
7674 Params.reserve(NumParams);
7675 while (NumParams--)
7676 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7677
7678 TemplateParameterList* TemplateParams =
7679 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7680 Params.data(), Params.size(), RAngleLoc);
7681 return TemplateParams;
7682}
7683
7684void
7685ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007686ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007687 ModuleFile &F, const RecordData &Record,
7688 unsigned &Idx) {
7689 unsigned NumTemplateArgs = Record[Idx++];
7690 TemplArgs.reserve(NumTemplateArgs);
7691 while (NumTemplateArgs--)
7692 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7693}
7694
7695/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007696void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007697 const RecordData &Record, unsigned &Idx) {
7698 unsigned NumDecls = Record[Idx++];
7699 Set.reserve(Context, NumDecls);
7700 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007701 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007702 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007703 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007704 }
7705}
7706
7707CXXBaseSpecifier
7708ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7709 const RecordData &Record, unsigned &Idx) {
7710 bool isVirtual = static_cast<bool>(Record[Idx++]);
7711 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7712 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7713 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7714 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7715 SourceRange Range = ReadSourceRange(F, Record, Idx);
7716 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7717 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7718 EllipsisLoc);
7719 Result.setInheritConstructors(inheritConstructors);
7720 return Result;
7721}
7722
Richard Smithc2bb8182015-03-24 06:36:48 +00007723CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007724ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7725 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007726 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007727 assert(NumInitializers && "wrote ctor initializers but have no inits");
7728 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7729 for (unsigned i = 0; i != NumInitializers; ++i) {
7730 TypeSourceInfo *TInfo = nullptr;
7731 bool IsBaseVirtual = false;
7732 FieldDecl *Member = nullptr;
7733 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007734
Richard Smithc2bb8182015-03-24 06:36:48 +00007735 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7736 switch (Type) {
7737 case CTOR_INITIALIZER_BASE:
7738 TInfo = GetTypeSourceInfo(F, Record, Idx);
7739 IsBaseVirtual = Record[Idx++];
7740 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007741
Richard Smithc2bb8182015-03-24 06:36:48 +00007742 case CTOR_INITIALIZER_DELEGATING:
7743 TInfo = GetTypeSourceInfo(F, Record, Idx);
7744 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007745
Richard Smithc2bb8182015-03-24 06:36:48 +00007746 case CTOR_INITIALIZER_MEMBER:
7747 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7748 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007749
Richard Smithc2bb8182015-03-24 06:36:48 +00007750 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7751 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7752 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007753 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007754
7755 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7756 Expr *Init = ReadExpr(F);
7757 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7758 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7759 bool IsWritten = Record[Idx++];
7760 unsigned SourceOrderOrNumArrayIndices;
7761 SmallVector<VarDecl *, 8> Indices;
7762 if (IsWritten) {
7763 SourceOrderOrNumArrayIndices = Record[Idx++];
7764 } else {
7765 SourceOrderOrNumArrayIndices = Record[Idx++];
7766 Indices.reserve(SourceOrderOrNumArrayIndices);
7767 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7768 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7769 }
7770
7771 CXXCtorInitializer *BOMInit;
7772 if (Type == CTOR_INITIALIZER_BASE) {
7773 BOMInit = new (Context)
7774 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7775 RParenLoc, MemberOrEllipsisLoc);
7776 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7777 BOMInit = new (Context)
7778 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7779 } else if (IsWritten) {
7780 if (Member)
7781 BOMInit = new (Context) CXXCtorInitializer(
7782 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7783 else
7784 BOMInit = new (Context)
7785 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7786 LParenLoc, Init, RParenLoc);
7787 } else {
7788 if (IndirectMember) {
7789 assert(Indices.empty() && "Indirect field improperly initialized");
7790 BOMInit = new (Context)
7791 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7792 LParenLoc, Init, RParenLoc);
7793 } else {
7794 BOMInit = CXXCtorInitializer::Create(
7795 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7796 Indices.data(), Indices.size());
7797 }
7798 }
7799
7800 if (IsWritten)
7801 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7802 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007803 }
7804
Richard Smithc2bb8182015-03-24 06:36:48 +00007805 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007806}
7807
7808NestedNameSpecifier *
7809ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7810 const RecordData &Record, unsigned &Idx) {
7811 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007812 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007813 for (unsigned I = 0; I != N; ++I) {
7814 NestedNameSpecifier::SpecifierKind Kind
7815 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7816 switch (Kind) {
7817 case NestedNameSpecifier::Identifier: {
7818 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7819 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7820 break;
7821 }
7822
7823 case NestedNameSpecifier::Namespace: {
7824 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7825 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7826 break;
7827 }
7828
7829 case NestedNameSpecifier::NamespaceAlias: {
7830 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7831 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7832 break;
7833 }
7834
7835 case NestedNameSpecifier::TypeSpec:
7836 case NestedNameSpecifier::TypeSpecWithTemplate: {
7837 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7838 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007839 return nullptr;
7840
Guy Benyei11169dd2012-12-18 14:30:41 +00007841 bool Template = Record[Idx++];
7842 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7843 break;
7844 }
7845
7846 case NestedNameSpecifier::Global: {
7847 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7848 // No associated value, and there can't be a prefix.
7849 break;
7850 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007851
7852 case NestedNameSpecifier::Super: {
7853 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7854 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7855 break;
7856 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007857 }
7858 Prev = NNS;
7859 }
7860 return NNS;
7861}
7862
7863NestedNameSpecifierLoc
7864ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7865 unsigned &Idx) {
7866 unsigned N = Record[Idx++];
7867 NestedNameSpecifierLocBuilder Builder;
7868 for (unsigned I = 0; I != N; ++I) {
7869 NestedNameSpecifier::SpecifierKind Kind
7870 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7871 switch (Kind) {
7872 case NestedNameSpecifier::Identifier: {
7873 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7874 SourceRange Range = ReadSourceRange(F, Record, Idx);
7875 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7876 break;
7877 }
7878
7879 case NestedNameSpecifier::Namespace: {
7880 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7881 SourceRange Range = ReadSourceRange(F, Record, Idx);
7882 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7883 break;
7884 }
7885
7886 case NestedNameSpecifier::NamespaceAlias: {
7887 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7888 SourceRange Range = ReadSourceRange(F, Record, Idx);
7889 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7890 break;
7891 }
7892
7893 case NestedNameSpecifier::TypeSpec:
7894 case NestedNameSpecifier::TypeSpecWithTemplate: {
7895 bool Template = Record[Idx++];
7896 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7897 if (!T)
7898 return NestedNameSpecifierLoc();
7899 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7900
7901 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7902 Builder.Extend(Context,
7903 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7904 T->getTypeLoc(), ColonColonLoc);
7905 break;
7906 }
7907
7908 case NestedNameSpecifier::Global: {
7909 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7910 Builder.MakeGlobal(Context, ColonColonLoc);
7911 break;
7912 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007913
7914 case NestedNameSpecifier::Super: {
7915 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7916 SourceRange Range = ReadSourceRange(F, Record, Idx);
7917 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
7918 break;
7919 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007920 }
7921 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007922
Guy Benyei11169dd2012-12-18 14:30:41 +00007923 return Builder.getWithLocInContext(Context);
7924}
7925
7926SourceRange
7927ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7928 unsigned &Idx) {
7929 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7930 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7931 return SourceRange(beg, end);
7932}
7933
7934/// \brief Read an integral value
7935llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7936 unsigned BitWidth = Record[Idx++];
7937 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7938 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7939 Idx += NumWords;
7940 return Result;
7941}
7942
7943/// \brief Read a signed integral value
7944llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7945 bool isUnsigned = Record[Idx++];
7946 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7947}
7948
7949/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007950llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7951 const llvm::fltSemantics &Sem,
7952 unsigned &Idx) {
7953 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007954}
7955
7956// \brief Read a string
7957std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7958 unsigned Len = Record[Idx++];
7959 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7960 Idx += Len;
7961 return Result;
7962}
7963
Richard Smith7ed1bc92014-12-05 22:42:13 +00007964std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
7965 unsigned &Idx) {
7966 std::string Filename = ReadString(Record, Idx);
7967 ResolveImportedPath(F, Filename);
7968 return Filename;
7969}
7970
Guy Benyei11169dd2012-12-18 14:30:41 +00007971VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7972 unsigned &Idx) {
7973 unsigned Major = Record[Idx++];
7974 unsigned Minor = Record[Idx++];
7975 unsigned Subminor = Record[Idx++];
7976 if (Minor == 0)
7977 return VersionTuple(Major);
7978 if (Subminor == 0)
7979 return VersionTuple(Major, Minor - 1);
7980 return VersionTuple(Major, Minor - 1, Subminor - 1);
7981}
7982
7983CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7984 const RecordData &Record,
7985 unsigned &Idx) {
7986 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7987 return CXXTemporary::Create(Context, Decl);
7988}
7989
7990DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007991 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007992}
7993
7994DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7995 return Diags.Report(Loc, DiagID);
7996}
7997
7998/// \brief Retrieve the identifier table associated with the
7999/// preprocessor.
8000IdentifierTable &ASTReader::getIdentifierTable() {
8001 return PP.getIdentifierTable();
8002}
8003
8004/// \brief Record that the given ID maps to the given switch-case
8005/// statement.
8006void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008007 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008008 "Already have a SwitchCase with this ID");
8009 (*CurrSwitchCaseStmts)[ID] = SC;
8010}
8011
8012/// \brief Retrieve the switch-case statement with the given ID.
8013SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008014 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008015 return (*CurrSwitchCaseStmts)[ID];
8016}
8017
8018void ASTReader::ClearSwitchCaseIDs() {
8019 CurrSwitchCaseStmts->clear();
8020}
8021
8022void ASTReader::ReadComments() {
8023 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008024 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008025 serialization::ModuleFile *> >::iterator
8026 I = CommentsCursors.begin(),
8027 E = CommentsCursors.end();
8028 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008029 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008030 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008031 serialization::ModuleFile &F = *I->second;
8032 SavedStreamPosition SavedPosition(Cursor);
8033
8034 RecordData Record;
8035 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008036 llvm::BitstreamEntry Entry =
8037 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008038
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008039 switch (Entry.Kind) {
8040 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8041 case llvm::BitstreamEntry::Error:
8042 Error("malformed block record in AST file");
8043 return;
8044 case llvm::BitstreamEntry::EndBlock:
8045 goto NextCursor;
8046 case llvm::BitstreamEntry::Record:
8047 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008048 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008049 }
8050
8051 // Read a record.
8052 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008053 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008054 case COMMENTS_RAW_COMMENT: {
8055 unsigned Idx = 0;
8056 SourceRange SR = ReadSourceRange(F, Record, Idx);
8057 RawComment::CommentKind Kind =
8058 (RawComment::CommentKind) Record[Idx++];
8059 bool IsTrailingComment = Record[Idx++];
8060 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008061 Comments.push_back(new (Context) RawComment(
8062 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8063 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008064 break;
8065 }
8066 }
8067 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008068 NextCursor:
8069 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008070 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008071}
8072
Argyrios Kyrtzidis1bde1172014-11-18 05:24:18 +00008073void ASTReader::getInputFiles(ModuleFile &F,
8074 SmallVectorImpl<serialization::InputFile> &Files) {
8075 for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
8076 unsigned ID = I+1;
8077 Files.push_back(getInputFile(F, ID));
8078 }
8079}
8080
Richard Smithcd45dbc2014-04-19 03:48:30 +00008081std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8082 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008083 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008084 return M->getFullModuleName();
8085
8086 // Otherwise, use the name of the top-level module the decl is within.
8087 if (ModuleFile *M = getOwningModuleFile(D))
8088 return M->ModuleName;
8089
8090 // Not from a module.
8091 return "";
8092}
8093
Guy Benyei11169dd2012-12-18 14:30:41 +00008094void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008095 while (!PendingIdentifierInfos.empty() ||
8096 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008097 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008098 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008099 // If any identifiers with corresponding top-level declarations have
8100 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008101 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8102 TopLevelDeclsMap;
8103 TopLevelDeclsMap TopLevelDecls;
8104
Guy Benyei11169dd2012-12-18 14:30:41 +00008105 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008106 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008107 SmallVector<uint32_t, 4> DeclIDs =
8108 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008109 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008110
8111 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008112 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008113
Richard Smith851072e2014-05-19 20:59:20 +00008114 // For each decl chain that we wanted to complete while deserializing, mark
8115 // it as "still needs to be completed".
8116 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8117 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8118 }
8119 PendingIncompleteDeclChains.clear();
8120
Guy Benyei11169dd2012-12-18 14:30:41 +00008121 // Load pending declaration chains.
Richard Smithfe620d22015-03-05 23:24:12 +00008122 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
Richard Smithfe620d22015-03-05 23:24:12 +00008123 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
Richard Smithe687bf82015-03-16 20:54:07 +00008124 loadPendingDeclChain(PendingDeclChains[I]);
Richard Smithfe620d22015-03-05 23:24:12 +00008125 }
8126 assert(PendingDeclChainsKnown.empty());
Guy Benyei11169dd2012-12-18 14:30:41 +00008127 PendingDeclChains.clear();
8128
Douglas Gregor6168bd22013-02-18 15:53:43 +00008129 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008130 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8131 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008132 IdentifierInfo *II = TLD->first;
8133 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008134 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008135 }
8136 }
8137
Guy Benyei11169dd2012-12-18 14:30:41 +00008138 // Load any pending macro definitions.
8139 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008140 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8141 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8142 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8143 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008144 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008145 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008146 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008147 if (Info.M->Kind != MK_ImplicitModule &&
8148 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008149 resolvePendingMacro(II, Info);
8150 }
8151 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008152 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008153 ++IDIdx) {
8154 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008155 if (Info.M->Kind == MK_ImplicitModule ||
8156 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008157 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008158 }
8159 }
8160 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008161
8162 // Wire up the DeclContexts for Decls that we delayed setting until
8163 // recursive loading is completed.
8164 while (!PendingDeclContextInfos.empty()) {
8165 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8166 PendingDeclContextInfos.pop_front();
8167 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8168 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8169 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8170 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008171
Richard Smithd1c46742014-04-30 02:24:17 +00008172 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008173 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008174 auto Update = PendingUpdateRecords.pop_back_val();
8175 ReadingKindTracker ReadingKind(Read_Decl, *this);
8176 loadDeclUpdateRecords(Update.first, Update.second);
8177 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008178 }
Richard Smith8a639892015-01-24 01:07:20 +00008179
8180 // At this point, all update records for loaded decls are in place, so any
8181 // fake class definitions should have become real.
8182 assert(PendingFakeDefinitionData.empty() &&
8183 "faked up a class definition but never saw the real one");
8184
Guy Benyei11169dd2012-12-18 14:30:41 +00008185 // If we deserialized any C++ or Objective-C class definitions, any
8186 // Objective-C protocol definitions, or any redeclarable templates, make sure
8187 // that all redeclarations point to the definitions. Note that this can only
8188 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008189 for (Decl *D : PendingDefinitions) {
8190 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008191 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008192 // Make sure that the TagType points at the definition.
8193 const_cast<TagType*>(TagT)->decl = TD;
8194 }
Richard Smith8ce51082015-03-11 01:44:51 +00008195
Craig Topperc6914d02014-08-25 04:15:02 +00008196 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008197 for (auto *R = getMostRecentExistingDecl(RD); R;
8198 R = R->getPreviousDecl()) {
8199 assert((R == D) ==
8200 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008201 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008202 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008203 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008204 }
8205
8206 continue;
8207 }
Richard Smith8ce51082015-03-11 01:44:51 +00008208
Craig Topperc6914d02014-08-25 04:15:02 +00008209 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008210 // Make sure that the ObjCInterfaceType points at the definition.
8211 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8212 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008213
8214 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8215 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8216
Guy Benyei11169dd2012-12-18 14:30:41 +00008217 continue;
8218 }
Richard Smith8ce51082015-03-11 01:44:51 +00008219
Craig Topperc6914d02014-08-25 04:15:02 +00008220 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008221 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8222 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8223
Guy Benyei11169dd2012-12-18 14:30:41 +00008224 continue;
8225 }
Richard Smith8ce51082015-03-11 01:44:51 +00008226
Craig Topperc6914d02014-08-25 04:15:02 +00008227 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008228 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8229 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008230 }
8231 PendingDefinitions.clear();
8232
8233 // Load the bodies of any functions or methods we've encountered. We do
8234 // this now (delayed) so that we can be sure that the declaration chains
8235 // have been fully wired up.
Richard Smith8ce51082015-03-11 01:44:51 +00008236 // FIXME: There seems to be no point in delaying this, it does not depend
8237 // on the redecl chains having been wired up.
Guy Benyei11169dd2012-12-18 14:30:41 +00008238 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8239 PBEnd = PendingBodies.end();
8240 PB != PBEnd; ++PB) {
8241 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8242 // FIXME: Check for =delete/=default?
8243 // FIXME: Complain about ODR violations here?
8244 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8245 FD->setLazyBody(PB->second);
8246 continue;
8247 }
8248
8249 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8250 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8251 MD->setLazyBody(PB->second);
8252 }
8253 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008254
8255 // Do some cleanup.
8256 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8257 getContext().deduplicateMergedDefinitonsFor(ND);
8258 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008259}
8260
8261void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008262 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8263 return;
8264
Richard Smitha0ce9c42014-07-29 23:23:27 +00008265 // Trigger the import of the full definition of each class that had any
8266 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008267 // These updates may in turn find and diagnose some ODR failures, so take
8268 // ownership of the set first.
8269 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8270 PendingOdrMergeFailures.clear();
8271 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008272 Merge.first->buildLookup();
8273 Merge.first->decls_begin();
8274 Merge.first->bases_begin();
8275 Merge.first->vbases_begin();
8276 for (auto *RD : Merge.second) {
8277 RD->decls_begin();
8278 RD->bases_begin();
8279 RD->vbases_begin();
8280 }
8281 }
8282
8283 // For each declaration from a merged context, check that the canonical
8284 // definition of that context also contains a declaration of the same
8285 // entity.
8286 //
8287 // Caution: this loop does things that might invalidate iterators into
8288 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8289 while (!PendingOdrMergeChecks.empty()) {
8290 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8291
8292 // FIXME: Skip over implicit declarations for now. This matters for things
8293 // like implicitly-declared special member functions. This isn't entirely
8294 // correct; we can end up with multiple unmerged declarations of the same
8295 // implicit entity.
8296 if (D->isImplicit())
8297 continue;
8298
8299 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008300
8301 bool Found = false;
8302 const Decl *DCanon = D->getCanonicalDecl();
8303
Richard Smith01bdb7a2014-08-28 05:44:07 +00008304 for (auto RI : D->redecls()) {
8305 if (RI->getLexicalDeclContext() == CanonDef) {
8306 Found = true;
8307 break;
8308 }
8309 }
8310 if (Found)
8311 continue;
8312
Richard Smitha0ce9c42014-07-29 23:23:27 +00008313 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith01bdb7a2014-08-28 05:44:07 +00008314 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
Richard Smitha0ce9c42014-07-29 23:23:27 +00008315 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8316 !Found && I != E; ++I) {
8317 for (auto RI : (*I)->redecls()) {
8318 if (RI->getLexicalDeclContext() == CanonDef) {
8319 // This declaration is present in the canonical definition. If it's
8320 // in the same redecl chain, it's the one we're looking for.
8321 if (RI->getCanonicalDecl() == DCanon)
8322 Found = true;
8323 else
8324 Candidates.push_back(cast<NamedDecl>(RI));
8325 break;
8326 }
8327 }
8328 }
8329
8330 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008331 // The AST doesn't like TagDecls becoming invalid after they've been
8332 // completed. We only really need to mark FieldDecls as invalid here.
8333 if (!isa<TagDecl>(D))
8334 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008335
8336 // Ensure we don't accidentally recursively enter deserialization while
8337 // we're producing our diagnostic.
8338 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008339
8340 std::string CanonDefModule =
8341 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8342 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8343 << D << getOwningModuleNameForDiagnostic(D)
8344 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8345
8346 if (Candidates.empty())
8347 Diag(cast<Decl>(CanonDef)->getLocation(),
8348 diag::note_module_odr_violation_no_possible_decls) << D;
8349 else {
8350 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8351 Diag(Candidates[I]->getLocation(),
8352 diag::note_module_odr_violation_possible_decl)
8353 << Candidates[I];
8354 }
8355
8356 DiagnosedOdrMergeFailures.insert(CanonDef);
8357 }
8358 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008359
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008360 if (OdrMergeFailures.empty())
8361 return;
8362
8363 // Ensure we don't accidentally recursively enter deserialization while
8364 // we're producing our diagnostics.
8365 Deserializing RecursionGuard(this);
8366
Richard Smithcd45dbc2014-04-19 03:48:30 +00008367 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008368 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008369 // If we've already pointed out a specific problem with this class, don't
8370 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008371 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008372 continue;
8373
8374 bool Diagnosed = false;
8375 for (auto *RD : Merge.second) {
8376 // Multiple different declarations got merged together; tell the user
8377 // where they came from.
8378 if (Merge.first != RD) {
8379 // FIXME: Walk the definition, figure out what's different,
8380 // and diagnose that.
8381 if (!Diagnosed) {
8382 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8383 Diag(Merge.first->getLocation(),
8384 diag::err_module_odr_violation_different_definitions)
8385 << Merge.first << Module.empty() << Module;
8386 Diagnosed = true;
8387 }
8388
8389 Diag(RD->getLocation(),
8390 diag::note_module_odr_violation_different_definitions)
8391 << getOwningModuleNameForDiagnostic(RD);
8392 }
8393 }
8394
8395 if (!Diagnosed) {
8396 // All definitions are updates to the same declaration. This happens if a
8397 // module instantiates the declaration of a class template specialization
8398 // and two or more other modules instantiate its definition.
8399 //
8400 // FIXME: Indicate which modules had instantiations of this definition.
8401 // FIXME: How can this even happen?
8402 Diag(Merge.first->getLocation(),
8403 diag::err_module_odr_violation_different_instantiations)
8404 << Merge.first;
8405 }
8406 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008407}
8408
Richard Smithce18a182015-07-14 00:26:00 +00008409void ASTReader::StartedDeserializing() {
8410 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8411 ReadTimer->startTimer();
8412}
8413
Guy Benyei11169dd2012-12-18 14:30:41 +00008414void ASTReader::FinishedDeserializing() {
8415 assert(NumCurrentElementsDeserializing &&
8416 "FinishedDeserializing not paired with StartedDeserializing");
8417 if (NumCurrentElementsDeserializing == 1) {
8418 // We decrease NumCurrentElementsDeserializing only after pending actions
8419 // are finished, to avoid recursively re-calling finishPendingActions().
8420 finishPendingActions();
8421 }
8422 --NumCurrentElementsDeserializing;
8423
Richard Smitha0ce9c42014-07-29 23:23:27 +00008424 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008425 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008426 while (!PendingExceptionSpecUpdates.empty()) {
8427 auto Updates = std::move(PendingExceptionSpecUpdates);
8428 PendingExceptionSpecUpdates.clear();
8429 for (auto Update : Updates) {
8430 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8431 SemaObj->UpdateExceptionSpec(Update.second,
8432 FPT->getExtProtoInfo().ExceptionSpec);
8433 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008434 }
8435
Richard Smitha0ce9c42014-07-29 23:23:27 +00008436 diagnoseOdrViolations();
8437
Richard Smithce18a182015-07-14 00:26:00 +00008438 if (ReadTimer)
8439 ReadTimer->stopTimer();
8440
Richard Smith04d05b52014-03-23 00:27:18 +00008441 // We are not in recursive loading, so it's safe to pass the "interesting"
8442 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008443 if (Consumer)
8444 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008445 }
8446}
8447
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008448void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008449 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8450 // Remove any fake results before adding any real ones.
8451 auto It = PendingFakeLookupResults.find(II);
8452 if (It != PendingFakeLookupResults.end()) {
8453 for (auto *ND : PendingFakeLookupResults[II])
8454 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008455 // FIXME: this works around module+PCH performance issue.
8456 // Rather than erase the result from the map, which is O(n), just clear
8457 // the vector of NamedDecls.
8458 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008459 }
8460 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008461
8462 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8463 SemaObj->TUScope->AddDecl(D);
8464 } else if (SemaObj->TUScope) {
8465 // Adding the decl to IdResolver may have failed because it was already in
8466 // (even though it was not added in scope). If it is already in, make sure
8467 // it gets in the scope as well.
8468 if (std::find(SemaObj->IdResolver.begin(Name),
8469 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8470 SemaObj->TUScope->AddDecl(D);
8471 }
8472}
8473
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008474ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
8475 const PCHContainerOperations &PCHContainerOps,
8476 StringRef isysroot, bool DisableValidation,
8477 bool AllowASTWithCompilerErrors,
Nico Weber824285e2014-05-08 04:26:47 +00008478 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Richard Smithce18a182015-07-14 00:26:00 +00008479 bool UseGlobalIndex,
8480 std::unique_ptr<llvm::Timer> ReadTimer)
Craig Toppera13603a2014-05-22 05:54:18 +00008481 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008482 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008483 FileMgr(PP.getFileManager()), PCHContainerOps(PCHContainerOps),
8484 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
8485 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerOps),
Richard Smithce18a182015-07-14 00:26:00 +00008486 ReadTimer(std::move(ReadTimer)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008487 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008488 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8489 AllowConfigurationMismatch(AllowConfigurationMismatch),
8490 ValidateSystemInputs(ValidateSystemInputs),
8491 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008492 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8493 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8494 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8495 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008496 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8497 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8498 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8499 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8500 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8501 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008502 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008503 SourceMgr.setExternalSLocEntrySource(this);
8504}
8505
8506ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008507 if (OwnsDeserializationListener)
8508 delete DeserializationListener;
8509
Guy Benyei11169dd2012-12-18 14:30:41 +00008510 for (DeclContextVisibleUpdatesPending::iterator
8511 I = PendingVisibleUpdates.begin(),
8512 E = PendingVisibleUpdates.end();
8513 I != E; ++I) {
8514 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8515 F = I->second.end();
8516 J != F; ++J)
8517 delete J->first;
8518 }
8519}