blob: af6f92a5115700abb5f2379582cb42afcdde79df [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
212 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
213 if (Diags)
214 Diags->Report(diag::err_pch_langopt_value_mismatch)
215 << "target Objective-C runtime";
216 return true;
217 }
218
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000219 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
220 LangOpts.CommentOpts.BlockCommandNames) {
221 if (Diags)
222 Diags->Report(diag::err_pch_langopt_value_mismatch)
223 << "block command names";
224 return true;
225 }
226
Guy Benyei11169dd2012-12-18 14:30:41 +0000227 return false;
228}
229
230/// \brief Compare the given set of target options against an existing set of
231/// target options.
232///
233/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
234///
235/// \returns true if the target options mis-match, false otherwise.
236static bool checkTargetOptions(const TargetOptions &TargetOpts,
237 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000238 DiagnosticsEngine *Diags,
239 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000240#define CHECK_TARGET_OPT(Field, Name) \
241 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
242 if (Diags) \
243 Diags->Report(diag::err_pch_targetopt_mismatch) \
244 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
245 return true; \
246 }
247
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000248 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000249 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000250 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000251
252 // We can tolerate different CPUs in many cases, notably when one CPU
253 // supports a strict superset of another. When allowing compatible
254 // differences skip this check.
255 if (!AllowCompatibleDifferences)
256 CHECK_TARGET_OPT(CPU, "target CPU");
257
Guy Benyei11169dd2012-12-18 14:30:41 +0000258#undef CHECK_TARGET_OPT
259
260 // Compare feature sets.
261 SmallVector<StringRef, 4> ExistingFeatures(
262 ExistingTargetOpts.FeaturesAsWritten.begin(),
263 ExistingTargetOpts.FeaturesAsWritten.end());
264 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
265 TargetOpts.FeaturesAsWritten.end());
266 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
267 std::sort(ReadFeatures.begin(), ReadFeatures.end());
268
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000269 // We compute the set difference in both directions explicitly so that we can
270 // diagnose the differences differently.
271 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
272 std::set_difference(
273 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
274 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
275 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
276 ExistingFeatures.begin(), ExistingFeatures.end(),
277 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000278
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000279 // If we are allowing compatible differences and the read feature set is
280 // a strict subset of the existing feature set, there is nothing to diagnose.
281 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
282 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000283
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000284 if (Diags) {
285 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000286 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000287 << /* is-existing-feature */ false << Feature;
288 for (StringRef Feature : UnmatchedExistingFeatures)
289 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
290 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000291 }
292
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000293 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000294}
295
296bool
297PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000298 bool Complain,
299 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000300 const LangOptions &ExistingLangOpts = PP.getLangOpts();
301 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000302 Complain ? &Reader.Diags : nullptr,
303 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000304}
305
306bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000307 bool Complain,
308 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000309 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
310 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000311 Complain ? &Reader.Diags : nullptr,
312 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000313}
314
315namespace {
316 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
317 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000318 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
319 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000320}
321
Ben Langmuirb92de022014-04-29 16:25:26 +0000322static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
323 DiagnosticsEngine &Diags,
324 bool Complain) {
325 typedef DiagnosticsEngine::Level Level;
326
327 // Check current mappings for new -Werror mappings, and the stored mappings
328 // for cases that were explicitly mapped to *not* be errors that are now
329 // errors because of options like -Werror.
330 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
331
332 for (DiagnosticsEngine *MappingSource : MappingSources) {
333 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
334 diag::kind DiagID = DiagIDMappingPair.first;
335 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
336 if (CurLevel < DiagnosticsEngine::Error)
337 continue; // not significant
338 Level StoredLevel =
339 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
340 if (StoredLevel < DiagnosticsEngine::Error) {
341 if (Complain)
342 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
343 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
344 return true;
345 }
346 }
347 }
348
349 return false;
350}
351
Alp Tokerac4e8e52014-06-22 21:58:33 +0000352static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
353 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
354 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
355 return true;
356 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000357}
358
359static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
360 DiagnosticsEngine &Diags,
361 bool IsSystem, bool Complain) {
362 // Top-level options
363 if (IsSystem) {
364 if (Diags.getSuppressSystemWarnings())
365 return false;
366 // If -Wsystem-headers was not enabled before, be conservative
367 if (StoredDiags.getSuppressSystemWarnings()) {
368 if (Complain)
369 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
370 return true;
371 }
372 }
373
374 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
375 if (Complain)
376 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
377 return true;
378 }
379
380 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
381 !StoredDiags.getEnableAllWarnings()) {
382 if (Complain)
383 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
384 return true;
385 }
386
387 if (isExtHandlingFromDiagsError(Diags) &&
388 !isExtHandlingFromDiagsError(StoredDiags)) {
389 if (Complain)
390 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
391 return true;
392 }
393
394 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
395}
396
397bool PCHValidator::ReadDiagnosticOptions(
398 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
399 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
400 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
401 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000402 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000403 // This should never fail, because we would have processed these options
404 // before writing them to an ASTFile.
405 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
406
407 ModuleManager &ModuleMgr = Reader.getModuleManager();
408 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
409
410 // If the original import came from a file explicitly generated by the user,
411 // don't check the diagnostic mappings.
412 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000413 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000414 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
415 // the transitive closure of its imports, since unrelated modules cannot be
416 // imported until after this module finishes validation.
417 ModuleFile *TopImport = *ModuleMgr.rbegin();
418 while (!TopImport->ImportedBy.empty())
419 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000420 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000421 return false;
422
423 StringRef ModuleName = TopImport->ModuleName;
424 assert(!ModuleName.empty() && "diagnostic options read before module name");
425
426 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
427 assert(M && "missing module");
428
429 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
430 // contains the union of their flags.
431 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
432}
433
Guy Benyei11169dd2012-12-18 14:30:41 +0000434/// \brief Collect the macro definitions provided by the given preprocessor
435/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000436static void
437collectMacroDefinitions(const PreprocessorOptions &PPOpts,
438 MacroDefinitionsMap &Macros,
439 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000440 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
441 StringRef Macro = PPOpts.Macros[I].first;
442 bool IsUndef = PPOpts.Macros[I].second;
443
444 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
445 StringRef MacroName = MacroPair.first;
446 StringRef MacroBody = MacroPair.second;
447
448 // For an #undef'd macro, we only care about the name.
449 if (IsUndef) {
450 if (MacroNames && !Macros.count(MacroName))
451 MacroNames->push_back(MacroName);
452
453 Macros[MacroName] = std::make_pair("", true);
454 continue;
455 }
456
457 // For a #define'd macro, figure out the actual definition.
458 if (MacroName.size() == Macro.size())
459 MacroBody = "1";
460 else {
461 // Note: GCC drops anything following an end-of-line character.
462 StringRef::size_type End = MacroBody.find_first_of("\n\r");
463 MacroBody = MacroBody.substr(0, End);
464 }
465
466 if (MacroNames && !Macros.count(MacroName))
467 MacroNames->push_back(MacroName);
468 Macros[MacroName] = std::make_pair(MacroBody, false);
469 }
470}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000471
Guy Benyei11169dd2012-12-18 14:30:41 +0000472/// \brief Check the preprocessor options deserialized from the control block
473/// against the preprocessor options in an existing preprocessor.
474///
475/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
476static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
477 const PreprocessorOptions &ExistingPPOpts,
478 DiagnosticsEngine *Diags,
479 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000480 std::string &SuggestedPredefines,
481 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000482 // Check macro definitions.
483 MacroDefinitionsMap ASTFileMacros;
484 collectMacroDefinitions(PPOpts, ASTFileMacros);
485 MacroDefinitionsMap ExistingMacros;
486 SmallVector<StringRef, 4> ExistingMacroNames;
487 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
488
489 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
490 // Dig out the macro definition in the existing preprocessor options.
491 StringRef MacroName = ExistingMacroNames[I];
492 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
493
494 // Check whether we know anything about this macro name or not.
495 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
496 = ASTFileMacros.find(MacroName);
497 if (Known == ASTFileMacros.end()) {
498 // FIXME: Check whether this identifier was referenced anywhere in the
499 // AST file. If so, we should reject the AST file. Unfortunately, this
500 // information isn't in the control block. What shall we do about it?
501
502 if (Existing.second) {
503 SuggestedPredefines += "#undef ";
504 SuggestedPredefines += MacroName.str();
505 SuggestedPredefines += '\n';
506 } else {
507 SuggestedPredefines += "#define ";
508 SuggestedPredefines += MacroName.str();
509 SuggestedPredefines += ' ';
510 SuggestedPredefines += Existing.first.str();
511 SuggestedPredefines += '\n';
512 }
513 continue;
514 }
515
516 // If the macro was defined in one but undef'd in the other, we have a
517 // conflict.
518 if (Existing.second != Known->second.second) {
519 if (Diags) {
520 Diags->Report(diag::err_pch_macro_def_undef)
521 << MacroName << Known->second.second;
522 }
523 return true;
524 }
525
526 // If the macro was #undef'd in both, or if the macro bodies are identical,
527 // it's fine.
528 if (Existing.second || Existing.first == Known->second.first)
529 continue;
530
531 // The macro bodies differ; complain.
532 if (Diags) {
533 Diags->Report(diag::err_pch_macro_def_conflict)
534 << MacroName << Known->second.first << Existing.first;
535 }
536 return true;
537 }
538
539 // Check whether we're using predefines.
540 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
541 if (Diags) {
542 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
543 }
544 return true;
545 }
546
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000547 // Detailed record is important since it is used for the module cache hash.
548 if (LangOpts.Modules &&
549 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
550 if (Diags) {
551 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
552 }
553 return true;
554 }
555
Guy Benyei11169dd2012-12-18 14:30:41 +0000556 // Compute the #include and #include_macros lines we need.
557 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
558 StringRef File = ExistingPPOpts.Includes[I];
559 if (File == ExistingPPOpts.ImplicitPCHInclude)
560 continue;
561
562 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
563 != PPOpts.Includes.end())
564 continue;
565
566 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000567 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000568 SuggestedPredefines += "\"\n";
569 }
570
571 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
572 StringRef File = ExistingPPOpts.MacroIncludes[I];
573 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
574 File)
575 != PPOpts.MacroIncludes.end())
576 continue;
577
578 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000579 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000580 SuggestedPredefines += "\"\n##\n";
581 }
582
583 return false;
584}
585
586bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
587 bool Complain,
588 std::string &SuggestedPredefines) {
589 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
590
591 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000592 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000593 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000594 SuggestedPredefines,
595 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000596}
597
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000598/// Check the header search options deserialized from the control block
599/// against the header search options in an existing preprocessor.
600///
601/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
602static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
603 StringRef SpecificModuleCachePath,
604 StringRef ExistingModuleCachePath,
605 DiagnosticsEngine *Diags,
606 const LangOptions &LangOpts) {
607 if (LangOpts.Modules) {
608 if (SpecificModuleCachePath != ExistingModuleCachePath) {
609 if (Diags)
610 Diags->Report(diag::err_pch_modulecache_mismatch)
611 << SpecificModuleCachePath << ExistingModuleCachePath;
612 return true;
613 }
614 }
615
616 return false;
617}
618
619bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
620 StringRef SpecificModuleCachePath,
621 bool Complain) {
622 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
623 PP.getHeaderSearchInfo().getModuleCachePath(),
624 Complain ? &Reader.Diags : nullptr,
625 PP.getLangOpts());
626}
627
Guy Benyei11169dd2012-12-18 14:30:41 +0000628void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
629 PP.setCounterValue(Value);
630}
631
632//===----------------------------------------------------------------------===//
633// AST reader implementation
634//===----------------------------------------------------------------------===//
635
Nico Weber824285e2014-05-08 04:26:47 +0000636void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
637 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000638 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000639 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000640}
641
642
643
644unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
645 return serialization::ComputeHash(Sel);
646}
647
648
649std::pair<unsigned, unsigned>
650ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000651 using namespace llvm::support;
652 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
653 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000654 return std::make_pair(KeyLen, DataLen);
655}
656
657ASTSelectorLookupTrait::internal_key_type
658ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000659 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000660 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000661 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
662 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
663 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000664 if (N == 0)
665 return SelTable.getNullarySelector(FirstII);
666 else if (N == 1)
667 return SelTable.getUnarySelector(FirstII);
668
669 SmallVector<IdentifierInfo *, 16> Args;
670 Args.push_back(FirstII);
671 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000672 Args.push_back(Reader.getLocalIdentifier(
673 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000674
675 return SelTable.getSelector(N, Args.data());
676}
677
678ASTSelectorLookupTrait::data_type
679ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
680 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000681 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000682
683 data_type Result;
684
Justin Bogner57ba0b22014-03-28 22:03:24 +0000685 Result.ID = Reader.getGlobalSelectorID(
686 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000687 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
688 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
689 Result.InstanceBits = FullInstanceBits & 0x3;
690 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
691 Result.FactoryBits = FullFactoryBits & 0x3;
692 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
693 unsigned NumInstanceMethods = FullInstanceBits >> 3;
694 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000695
696 // Load instance methods
697 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000698 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
699 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000700 Result.Instance.push_back(Method);
701 }
702
703 // Load factory methods
704 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000705 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
706 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000707 Result.Factory.push_back(Method);
708 }
709
710 return Result;
711}
712
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000713unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
714 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000715}
716
717std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000718ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000719 using namespace llvm::support;
720 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
721 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000722 return std::make_pair(KeyLen, DataLen);
723}
724
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000725ASTIdentifierLookupTraitBase::internal_key_type
726ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000727 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000728 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000729}
730
Douglas Gregordcf25082013-02-11 18:16:18 +0000731/// \brief Whether the given identifier is "interesting".
732static bool isInterestingIdentifier(IdentifierInfo &II) {
733 return II.isPoisoned() ||
734 II.isExtensionToken() ||
735 II.getObjCOrBuiltinID() ||
736 II.hasRevertedTokenIDToIdentifier() ||
737 II.hadMacroDefinition() ||
738 II.getFETokenInfo<void>();
739}
740
Guy Benyei11169dd2012-12-18 14:30:41 +0000741IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
742 const unsigned char* d,
743 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000744 using namespace llvm::support;
745 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000746 bool IsInteresting = RawID & 0x01;
747
748 // Wipe out the "is interesting" bit.
749 RawID = RawID >> 1;
750
751 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
752 if (!IsInteresting) {
753 // For uninteresting identifiers, just build the IdentifierInfo
754 // and associate it with the persistent ID.
755 IdentifierInfo *II = KnownII;
756 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000757 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000758 KnownII = II;
759 }
760 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000761 if (!II->isFromAST()) {
762 bool WasInteresting = isInterestingIdentifier(*II);
763 II->setIsFromAST();
764 if (WasInteresting)
765 II->setChangedSinceDeserialization();
766 }
767 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000768 return II;
769 }
770
Justin Bogner57ba0b22014-03-28 22:03:24 +0000771 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
772 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000773 bool CPlusPlusOperatorKeyword = Bits & 0x01;
774 Bits >>= 1;
775 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
776 Bits >>= 1;
777 bool Poisoned = Bits & 0x01;
778 Bits >>= 1;
779 bool ExtensionToken = Bits & 0x01;
780 Bits >>= 1;
781 bool hadMacroDefinition = Bits & 0x01;
782 Bits >>= 1;
783
784 assert(Bits == 0 && "Extra bits in the identifier?");
785 DataLen -= 8;
786
787 // Build the IdentifierInfo itself and link the identifier ID with
788 // the new IdentifierInfo.
789 IdentifierInfo *II = KnownII;
790 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000791 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000792 KnownII = II;
793 }
794 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000795 if (!II->isFromAST()) {
796 bool WasInteresting = isInterestingIdentifier(*II);
797 II->setIsFromAST();
798 if (WasInteresting)
799 II->setChangedSinceDeserialization();
800 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000801
802 // Set or check the various bits in the IdentifierInfo structure.
803 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000804 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000805 II->RevertTokenIDToIdentifier();
806 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
807 assert(II->isExtensionToken() == ExtensionToken &&
808 "Incorrect extension token flag");
809 (void)ExtensionToken;
810 if (Poisoned)
811 II->setIsPoisoned(true);
812 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
813 "Incorrect C++ operator keyword flag");
814 (void)CPlusPlusOperatorKeyword;
815
816 // If this identifier is a macro, deserialize the macro
817 // definition.
818 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000819 uint32_t MacroDirectivesOffset =
820 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000821 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000822
Richard Smithd7329392015-04-21 21:46:32 +0000823 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000824 }
825
826 Reader.SetIdentifierInfo(ID, II);
827
828 // Read all of the declarations visible at global scope with this
829 // name.
830 if (DataLen > 0) {
831 SmallVector<uint32_t, 4> DeclIDs;
832 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000833 DeclIDs.push_back(Reader.getGlobalDeclID(
834 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000835 Reader.SetGloballyVisibleDecls(II, DeclIDs);
836 }
837
838 return II;
839}
840
841unsigned
842ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
843 llvm::FoldingSetNodeID ID;
844 ID.AddInteger(Key.Kind);
845
846 switch (Key.Kind) {
847 case DeclarationName::Identifier:
848 case DeclarationName::CXXLiteralOperatorName:
849 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
850 break;
851 case DeclarationName::ObjCZeroArgSelector:
852 case DeclarationName::ObjCOneArgSelector:
853 case DeclarationName::ObjCMultiArgSelector:
854 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
855 break;
856 case DeclarationName::CXXOperatorName:
857 ID.AddInteger((OverloadedOperatorKind)Key.Data);
858 break;
859 case DeclarationName::CXXConstructorName:
860 case DeclarationName::CXXDestructorName:
861 case DeclarationName::CXXConversionFunctionName:
862 case DeclarationName::CXXUsingDirective:
863 break;
864 }
865
866 return ID.ComputeHash();
867}
868
869ASTDeclContextNameLookupTrait::internal_key_type
870ASTDeclContextNameLookupTrait::GetInternalKey(
871 const external_key_type& Name) const {
872 DeclNameKey Key;
873 Key.Kind = Name.getNameKind();
874 switch (Name.getNameKind()) {
875 case DeclarationName::Identifier:
876 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
877 break;
878 case DeclarationName::ObjCZeroArgSelector:
879 case DeclarationName::ObjCOneArgSelector:
880 case DeclarationName::ObjCMultiArgSelector:
881 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
882 break;
883 case DeclarationName::CXXOperatorName:
884 Key.Data = Name.getCXXOverloadedOperator();
885 break;
886 case DeclarationName::CXXLiteralOperatorName:
887 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
888 break;
889 case DeclarationName::CXXConstructorName:
890 case DeclarationName::CXXDestructorName:
891 case DeclarationName::CXXConversionFunctionName:
892 case DeclarationName::CXXUsingDirective:
893 Key.Data = 0;
894 break;
895 }
896
897 return Key;
898}
899
900std::pair<unsigned, unsigned>
901ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000902 using namespace llvm::support;
903 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
904 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000905 return std::make_pair(KeyLen, DataLen);
906}
907
908ASTDeclContextNameLookupTrait::internal_key_type
909ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000910 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000911
912 DeclNameKey Key;
913 Key.Kind = (DeclarationName::NameKind)*d++;
914 switch (Key.Kind) {
915 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000916 Key.Data = (uint64_t)Reader.getLocalIdentifier(
917 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000918 break;
919 case DeclarationName::ObjCZeroArgSelector:
920 case DeclarationName::ObjCOneArgSelector:
921 case DeclarationName::ObjCMultiArgSelector:
922 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000923 (uint64_t)Reader.getLocalSelector(
924 F, endian::readNext<uint32_t, little, unaligned>(
925 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000926 break;
927 case DeclarationName::CXXOperatorName:
928 Key.Data = *d++; // OverloadedOperatorKind
929 break;
930 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000931 Key.Data = (uint64_t)Reader.getLocalIdentifier(
932 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000933 break;
934 case DeclarationName::CXXConstructorName:
935 case DeclarationName::CXXDestructorName:
936 case DeclarationName::CXXConversionFunctionName:
937 case DeclarationName::CXXUsingDirective:
938 Key.Data = 0;
939 break;
940 }
941
942 return Key;
943}
944
945ASTDeclContextNameLookupTrait::data_type
946ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
947 const unsigned char* d,
948 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000949 using namespace llvm::support;
950 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000951 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
952 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000953 return std::make_pair(Start, Start + NumDecls);
954}
955
956bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000957 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000958 const std::pair<uint64_t, uint64_t> &Offsets,
959 DeclContextInfo &Info) {
960 SavedStreamPosition SavedPosition(Cursor);
961 // First the lexical decls.
962 if (Offsets.first != 0) {
963 Cursor.JumpToBit(Offsets.first);
964
965 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000966 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000967 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000968 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000969 if (RecCode != DECL_CONTEXT_LEXICAL) {
970 Error("Expected lexical block");
971 return true;
972 }
973
Chris Lattner0e6c9402013-01-20 02:38:54 +0000974 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
975 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000976 }
977
978 // Now the lookup table.
979 if (Offsets.second != 0) {
980 Cursor.JumpToBit(Offsets.second);
981
982 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000983 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000984 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000985 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000986 if (RecCode != DECL_CONTEXT_VISIBLE) {
987 Error("Expected visible lookup table block");
988 return true;
989 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000990 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
991 (const unsigned char *)Blob.data() + Record[0],
992 (const unsigned char *)Blob.data() + sizeof(uint32_t),
993 (const unsigned char *)Blob.data(),
994 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +0000995 }
996
997 return false;
998}
999
1000void ASTReader::Error(StringRef Msg) {
1001 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +00001002 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
1003 Diag(diag::note_module_cache_path)
1004 << PP.getHeaderSearchInfo().getModuleCachePath();
1005 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001006}
1007
1008void ASTReader::Error(unsigned DiagID,
1009 StringRef Arg1, StringRef Arg2) {
1010 if (Diags.isDiagnosticInFlight())
1011 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1012 else
1013 Diag(DiagID) << Arg1 << Arg2;
1014}
1015
1016//===----------------------------------------------------------------------===//
1017// Source Manager Deserialization
1018//===----------------------------------------------------------------------===//
1019
1020/// \brief Read the line table in the source manager block.
1021/// \returns true if there was an error.
1022bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001023 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001024 unsigned Idx = 0;
1025 LineTableInfo &LineTable = SourceMgr.getLineTable();
1026
1027 // Parse the file names
1028 std::map<int, int> FileIDs;
1029 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1030 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001031 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001032 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1033 }
1034
1035 // Parse the line entries
1036 std::vector<LineEntry> Entries;
1037 while (Idx < Record.size()) {
1038 int FID = Record[Idx++];
1039 assert(FID >= 0 && "Serialized line entries for non-local file.");
1040 // Remap FileID from 1-based old view.
1041 FID += F.SLocEntryBaseID - 1;
1042
1043 // Extract the line entries
1044 unsigned NumEntries = Record[Idx++];
1045 assert(NumEntries && "Numentries is 00000");
1046 Entries.clear();
1047 Entries.reserve(NumEntries);
1048 for (unsigned I = 0; I != NumEntries; ++I) {
1049 unsigned FileOffset = Record[Idx++];
1050 unsigned LineNo = Record[Idx++];
1051 int FilenameID = FileIDs[Record[Idx++]];
1052 SrcMgr::CharacteristicKind FileKind
1053 = (SrcMgr::CharacteristicKind)Record[Idx++];
1054 unsigned IncludeOffset = Record[Idx++];
1055 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1056 FileKind, IncludeOffset));
1057 }
1058 LineTable.AddEntry(FileID::get(FID), Entries);
1059 }
1060
1061 return false;
1062}
1063
1064/// \brief Read a source manager block
1065bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1066 using namespace SrcMgr;
1067
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001068 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001069
1070 // Set the source-location entry cursor to the current position in
1071 // the stream. This cursor will be used to read the contents of the
1072 // source manager block initially, and then lazily read
1073 // source-location entries as needed.
1074 SLocEntryCursor = F.Stream;
1075
1076 // The stream itself is going to skip over the source manager block.
1077 if (F.Stream.SkipBlock()) {
1078 Error("malformed block record in AST file");
1079 return true;
1080 }
1081
1082 // Enter the source manager block.
1083 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1084 Error("malformed source manager block record in AST file");
1085 return true;
1086 }
1087
1088 RecordData Record;
1089 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001090 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1091
1092 switch (E.Kind) {
1093 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1094 case llvm::BitstreamEntry::Error:
1095 Error("malformed block record in AST file");
1096 return true;
1097 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001098 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001099 case llvm::BitstreamEntry::Record:
1100 // The interesting case.
1101 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001102 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001103
Guy Benyei11169dd2012-12-18 14:30:41 +00001104 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001105 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001106 StringRef Blob;
1107 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001108 default: // Default behavior: ignore.
1109 break;
1110
1111 case SM_SLOC_FILE_ENTRY:
1112 case SM_SLOC_BUFFER_ENTRY:
1113 case SM_SLOC_EXPANSION_ENTRY:
1114 // Once we hit one of the source location entries, we're done.
1115 return false;
1116 }
1117 }
1118}
1119
1120/// \brief If a header file is not found at the path that we expect it to be
1121/// and the PCH file was moved from its original location, try to resolve the
1122/// file by assuming that header+PCH were moved together and the header is in
1123/// the same place relative to the PCH.
1124static std::string
1125resolveFileRelativeToOriginalDir(const std::string &Filename,
1126 const std::string &OriginalDir,
1127 const std::string &CurrDir) {
1128 assert(OriginalDir != CurrDir &&
1129 "No point trying to resolve the file if the PCH dir didn't change");
1130 using namespace llvm::sys;
1131 SmallString<128> filePath(Filename);
1132 fs::make_absolute(filePath);
1133 assert(path::is_absolute(OriginalDir));
1134 SmallString<128> currPCHPath(CurrDir);
1135
1136 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1137 fileDirE = path::end(path::parent_path(filePath));
1138 path::const_iterator origDirI = path::begin(OriginalDir),
1139 origDirE = path::end(OriginalDir);
1140 // Skip the common path components from filePath and OriginalDir.
1141 while (fileDirI != fileDirE && origDirI != origDirE &&
1142 *fileDirI == *origDirI) {
1143 ++fileDirI;
1144 ++origDirI;
1145 }
1146 for (; origDirI != origDirE; ++origDirI)
1147 path::append(currPCHPath, "..");
1148 path::append(currPCHPath, fileDirI, fileDirE);
1149 path::append(currPCHPath, path::filename(Filename));
1150 return currPCHPath.str();
1151}
1152
1153bool ASTReader::ReadSLocEntry(int ID) {
1154 if (ID == 0)
1155 return false;
1156
1157 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1158 Error("source location entry ID out-of-range for AST file");
1159 return true;
1160 }
1161
1162 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1163 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001164 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001165 unsigned BaseOffset = F->SLocEntryBaseOffset;
1166
1167 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001168 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1169 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001170 Error("incorrectly-formatted source location entry in AST file");
1171 return true;
1172 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001173
Guy Benyei11169dd2012-12-18 14:30:41 +00001174 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001175 StringRef Blob;
1176 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001177 default:
1178 Error("incorrectly-formatted source location entry in AST file");
1179 return true;
1180
1181 case SM_SLOC_FILE_ENTRY: {
1182 // We will detect whether a file changed and return 'Failure' for it, but
1183 // we will also try to fail gracefully by setting up the SLocEntry.
1184 unsigned InputID = Record[4];
1185 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001186 const FileEntry *File = IF.getFile();
1187 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001188
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001189 // Note that we only check if a File was returned. If it was out-of-date
1190 // we have complained but we will continue creating a FileID to recover
1191 // gracefully.
1192 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001193 return true;
1194
1195 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1196 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1197 // This is the module's main file.
1198 IncludeLoc = getImportLocation(F);
1199 }
1200 SrcMgr::CharacteristicKind
1201 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1202 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1203 ID, BaseOffset + Record[0]);
1204 SrcMgr::FileInfo &FileInfo =
1205 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1206 FileInfo.NumCreatedFIDs = Record[5];
1207 if (Record[3])
1208 FileInfo.setHasLineDirectives();
1209
1210 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1211 unsigned NumFileDecls = Record[7];
1212 if (NumFileDecls) {
1213 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1214 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1215 NumFileDecls));
1216 }
1217
1218 const SrcMgr::ContentCache *ContentCache
1219 = SourceMgr.getOrCreateContentCache(File,
1220 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1221 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1222 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1223 unsigned Code = SLocEntryCursor.ReadCode();
1224 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001225 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001226
1227 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1228 Error("AST record has invalid code");
1229 return true;
1230 }
1231
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001232 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001233 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001234 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001235 }
1236
1237 break;
1238 }
1239
1240 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001241 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001242 unsigned Offset = Record[0];
1243 SrcMgr::CharacteristicKind
1244 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1245 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001246 if (IncludeLoc.isInvalid() &&
1247 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001248 IncludeLoc = getImportLocation(F);
1249 }
1250 unsigned Code = SLocEntryCursor.ReadCode();
1251 Record.clear();
1252 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001253 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001254
1255 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1256 Error("AST record has invalid code");
1257 return true;
1258 }
1259
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001260 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1261 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001262 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001263 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001264 break;
1265 }
1266
1267 case SM_SLOC_EXPANSION_ENTRY: {
1268 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1269 SourceMgr.createExpansionLoc(SpellingLoc,
1270 ReadSourceLocation(*F, Record[2]),
1271 ReadSourceLocation(*F, Record[3]),
1272 Record[4],
1273 ID,
1274 BaseOffset + Record[0]);
1275 break;
1276 }
1277 }
1278
1279 return false;
1280}
1281
1282std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1283 if (ID == 0)
1284 return std::make_pair(SourceLocation(), "");
1285
1286 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1287 Error("source location entry ID out-of-range for AST file");
1288 return std::make_pair(SourceLocation(), "");
1289 }
1290
1291 // Find which module file this entry lands in.
1292 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001293 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001294 return std::make_pair(SourceLocation(), "");
1295
1296 // FIXME: Can we map this down to a particular submodule? That would be
1297 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001298 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001299}
1300
1301/// \brief Find the location where the module F is imported.
1302SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1303 if (F->ImportLoc.isValid())
1304 return F->ImportLoc;
1305
1306 // Otherwise we have a PCH. It's considered to be "imported" at the first
1307 // location of its includer.
1308 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001309 // Main file is the importer.
1310 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1311 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001312 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001313 return F->ImportedBy[0]->FirstLoc;
1314}
1315
1316/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1317/// specified cursor. Read the abbreviations that are at the top of the block
1318/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001319bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001320 if (Cursor.EnterSubBlock(BlockID)) {
1321 Error("malformed block record in AST file");
1322 return Failure;
1323 }
1324
1325 while (true) {
1326 uint64_t Offset = Cursor.GetCurrentBitNo();
1327 unsigned Code = Cursor.ReadCode();
1328
1329 // We expect all abbrevs to be at the start of the block.
1330 if (Code != llvm::bitc::DEFINE_ABBREV) {
1331 Cursor.JumpToBit(Offset);
1332 return false;
1333 }
1334 Cursor.ReadAbbrevRecord();
1335 }
1336}
1337
Richard Smithe40f2ba2013-08-07 21:41:30 +00001338Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001339 unsigned &Idx) {
1340 Token Tok;
1341 Tok.startToken();
1342 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1343 Tok.setLength(Record[Idx++]);
1344 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1345 Tok.setIdentifierInfo(II);
1346 Tok.setKind((tok::TokenKind)Record[Idx++]);
1347 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1348 return Tok;
1349}
1350
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001351MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001352 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001353
1354 // Keep track of where we are in the stream, then jump back there
1355 // after reading this macro.
1356 SavedStreamPosition SavedPosition(Stream);
1357
1358 Stream.JumpToBit(Offset);
1359 RecordData Record;
1360 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001361 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001362
Guy Benyei11169dd2012-12-18 14:30:41 +00001363 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001364 // Advance to the next record, but if we get to the end of the block, don't
1365 // pop it (removing all the abbreviations from the cursor) since we want to
1366 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001367 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001368 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1369
1370 switch (Entry.Kind) {
1371 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1372 case llvm::BitstreamEntry::Error:
1373 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001374 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001375 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001376 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001377 case llvm::BitstreamEntry::Record:
1378 // The interesting case.
1379 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001380 }
1381
1382 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001383 Record.clear();
1384 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001385 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001386 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001387 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001388 case PP_MACRO_DIRECTIVE_HISTORY:
1389 return Macro;
1390
Guy Benyei11169dd2012-12-18 14:30:41 +00001391 case PP_MACRO_OBJECT_LIKE:
1392 case PP_MACRO_FUNCTION_LIKE: {
1393 // If we already have a macro, that means that we've hit the end
1394 // of the definition of the macro we were looking for. We're
1395 // done.
1396 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001397 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001398
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001399 unsigned NextIndex = 1; // Skip identifier ID.
1400 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001401 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001402 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001403 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001404 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001405 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001406
Guy Benyei11169dd2012-12-18 14:30:41 +00001407 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1408 // Decode function-like macro info.
1409 bool isC99VarArgs = Record[NextIndex++];
1410 bool isGNUVarArgs = Record[NextIndex++];
1411 bool hasCommaPasting = Record[NextIndex++];
1412 MacroArgs.clear();
1413 unsigned NumArgs = Record[NextIndex++];
1414 for (unsigned i = 0; i != NumArgs; ++i)
1415 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1416
1417 // Install function-like macro info.
1418 MI->setIsFunctionLike();
1419 if (isC99VarArgs) MI->setIsC99Varargs();
1420 if (isGNUVarArgs) MI->setIsGNUVarargs();
1421 if (hasCommaPasting) MI->setHasCommaPasting();
1422 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1423 PP.getPreprocessorAllocator());
1424 }
1425
Guy Benyei11169dd2012-12-18 14:30:41 +00001426 // Remember that we saw this macro last so that we add the tokens that
1427 // form its body to it.
1428 Macro = MI;
1429
1430 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1431 Record[NextIndex]) {
1432 // We have a macro definition. Register the association
1433 PreprocessedEntityID
1434 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1435 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001436 PreprocessingRecord::PPEntityID PPID =
1437 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1438 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1439 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001440 if (PPDef)
1441 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001442 }
1443
1444 ++NumMacrosRead;
1445 break;
1446 }
1447
1448 case PP_TOKEN: {
1449 // If we see a TOKEN before a PP_MACRO_*, then the file is
1450 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001451 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001452
John McCallf413f5e2013-05-03 00:10:13 +00001453 unsigned Idx = 0;
1454 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001455 Macro->AddTokenToBody(Tok);
1456 break;
1457 }
1458 }
1459 }
1460}
1461
1462PreprocessedEntityID
1463ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1464 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1465 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1466 assert(I != M.PreprocessedEntityRemap.end()
1467 && "Invalid index into preprocessed entity index remap");
1468
1469 return LocalID + I->second;
1470}
1471
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001472unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1473 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001474}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001475
Guy Benyei11169dd2012-12-18 14:30:41 +00001476HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001477HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1478 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
Richard Smith7ed1bc92014-12-05 22:42:13 +00001479 FE->getName(), /*Imported*/false };
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001480 return ikey;
1481}
Guy Benyei11169dd2012-12-18 14:30:41 +00001482
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001483bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1484 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001485 return false;
1486
Richard Smith7ed1bc92014-12-05 22:42:13 +00001487 if (llvm::sys::path::is_absolute(a.Filename) &&
1488 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001489 return true;
1490
Guy Benyei11169dd2012-12-18 14:30:41 +00001491 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001492 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001493 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1494 if (!Key.Imported)
1495 return FileMgr.getFile(Key.Filename);
1496
1497 std::string Resolved = Key.Filename;
1498 Reader.ResolveImportedPath(M, Resolved);
1499 return FileMgr.getFile(Resolved);
1500 };
1501
1502 const FileEntry *FEA = GetFile(a);
1503 const FileEntry *FEB = GetFile(b);
1504 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001505}
1506
1507std::pair<unsigned, unsigned>
1508HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001509 using namespace llvm::support;
1510 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001511 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001512 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001513}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001514
1515HeaderFileInfoTrait::internal_key_type
1516HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001517 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001518 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001519 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1520 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001521 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001522 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001523 return ikey;
1524}
1525
Guy Benyei11169dd2012-12-18 14:30:41 +00001526HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001527HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001528 unsigned DataLen) {
1529 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001530 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001531 HeaderFileInfo HFI;
1532 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001533 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1534 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001535 HFI.isImport = (Flags >> 5) & 0x01;
1536 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1537 HFI.DirInfo = (Flags >> 2) & 0x03;
1538 HFI.Resolved = (Flags >> 1) & 0x01;
1539 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001540 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1541 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1542 M, endian::readNext<uint32_t, little, unaligned>(d));
1543 if (unsigned FrameworkOffset =
1544 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001545 // The framework offset is 1 greater than the actual offset,
1546 // since 0 is used as an indicator for "no framework name".
1547 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1548 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1549 }
1550
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001551 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001552 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001553 if (LocalSMID) {
1554 // This header is part of a module. Associate it with the module to enable
1555 // implicit module import.
1556 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1557 Module *Mod = Reader.getSubmodule(GlobalSMID);
1558 HFI.isModuleHeader = true;
1559 FileManager &FileMgr = Reader.getFileManager();
1560 ModuleMap &ModMap =
1561 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001562 // FIXME: This information should be propagated through the
1563 // SUBMODULE_HEADER etc records rather than from here.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001564 // FIXME: We don't ever mark excluded headers.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001565 std::string Filename = key.Filename;
1566 if (key.Imported)
1567 Reader.ResolveImportedPath(M, Filename);
1568 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Hans Wennborg0101b542014-12-02 02:13:09 +00001569 ModMap.addHeader(Mod, H, HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001570 }
1571 }
1572
Guy Benyei11169dd2012-12-18 14:30:41 +00001573 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1574 (void)End;
1575
1576 // This HeaderFileInfo was externally loaded.
1577 HFI.External = true;
1578 return HFI;
1579}
1580
Richard Smithd7329392015-04-21 21:46:32 +00001581void ASTReader::addPendingMacro(IdentifierInfo *II,
1582 ModuleFile *M,
1583 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001584 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1585 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001586}
1587
1588void ASTReader::ReadDefinedMacros() {
1589 // Note that we are loading defined macros.
1590 Deserializing Macros(this);
1591
1592 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1593 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001594 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001595
1596 // If there was no preprocessor block, skip this file.
1597 if (!MacroCursor.getBitStreamReader())
1598 continue;
1599
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001600 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001601 Cursor.JumpToBit((*I)->MacroStartOffset);
1602
1603 RecordData Record;
1604 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001605 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1606
1607 switch (E.Kind) {
1608 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1609 case llvm::BitstreamEntry::Error:
1610 Error("malformed block record in AST file");
1611 return;
1612 case llvm::BitstreamEntry::EndBlock:
1613 goto NextCursor;
1614
1615 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001616 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001617 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001618 default: // Default behavior: ignore.
1619 break;
1620
1621 case PP_MACRO_OBJECT_LIKE:
1622 case PP_MACRO_FUNCTION_LIKE:
1623 getLocalIdentifier(**I, Record[0]);
1624 break;
1625
1626 case PP_TOKEN:
1627 // Ignore tokens.
1628 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001629 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001630 break;
1631 }
1632 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001633 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001634 }
1635}
1636
1637namespace {
1638 /// \brief Visitor class used to look up identifirs in an AST file.
1639 class IdentifierLookupVisitor {
1640 StringRef Name;
1641 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001642 unsigned &NumIdentifierLookups;
1643 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001644 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001645
Guy Benyei11169dd2012-12-18 14:30:41 +00001646 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001647 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1648 unsigned &NumIdentifierLookups,
1649 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001650 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001651 NumIdentifierLookups(NumIdentifierLookups),
1652 NumIdentifierLookupHits(NumIdentifierLookupHits),
1653 Found()
1654 {
1655 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001656
1657 static bool visit(ModuleFile &M, void *UserData) {
1658 IdentifierLookupVisitor *This
1659 = static_cast<IdentifierLookupVisitor *>(UserData);
1660
1661 // If we've already searched this module file, skip it now.
1662 if (M.Generation <= This->PriorGeneration)
1663 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001664
Guy Benyei11169dd2012-12-18 14:30:41 +00001665 ASTIdentifierLookupTable *IdTable
1666 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1667 if (!IdTable)
1668 return false;
1669
1670 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1671 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001672 ++This->NumIdentifierLookups;
1673 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001674 if (Pos == IdTable->end())
1675 return false;
1676
1677 // Dereferencing the iterator has the effect of building the
1678 // IdentifierInfo node and populating it with the various
1679 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001680 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001681 This->Found = *Pos;
1682 return true;
1683 }
1684
1685 // \brief Retrieve the identifier info found within the module
1686 // files.
1687 IdentifierInfo *getIdentifierInfo() const { return Found; }
1688 };
1689}
1690
1691void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1692 // Note that we are loading an identifier.
1693 Deserializing AnIdentifier(this);
1694
1695 unsigned PriorGeneration = 0;
1696 if (getContext().getLangOpts().Modules)
1697 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001698
1699 // If there is a global index, look there first to determine which modules
1700 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001701 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001702 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001703 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001704 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1705 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001706 }
1707 }
1708
Douglas Gregor7211ac12013-01-25 23:32:03 +00001709 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001710 NumIdentifierLookups,
1711 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001712 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001713 markIdentifierUpToDate(&II);
1714}
1715
1716void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1717 if (!II)
1718 return;
1719
1720 II->setOutOfDate(false);
1721
1722 // Update the generation for this identifier.
1723 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001724 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001725}
1726
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001727void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1728 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001729 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001730
1731 BitstreamCursor &Cursor = M.MacroCursor;
1732 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001733 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001734
Richard Smith713369b2015-04-23 20:40:50 +00001735 struct ModuleMacroRecord {
1736 SubmoduleID SubModID;
1737 MacroInfo *MI;
1738 SmallVector<SubmoduleID, 8> Overrides;
1739 };
1740 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001741
Richard Smithd7329392015-04-21 21:46:32 +00001742 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1743 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1744 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001745 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001746 while (true) {
1747 llvm::BitstreamEntry Entry =
1748 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1749 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1750 Error("malformed block record in AST file");
1751 return;
1752 }
1753
1754 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001755 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001756 case PP_MACRO_DIRECTIVE_HISTORY:
1757 break;
1758
1759 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001760 ModuleMacros.push_back(ModuleMacroRecord());
1761 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001762 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1763 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001764 for (int I = 2, N = Record.size(); I != N; ++I)
1765 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001766 continue;
1767 }
1768
1769 default:
1770 Error("malformed block record in AST file");
1771 return;
1772 }
1773
1774 // We found the macro directive history; that's the last record
1775 // for this macro.
1776 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001777 }
1778
Richard Smithd7329392015-04-21 21:46:32 +00001779 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001780 {
1781 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001782 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001783 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001784 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001785 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001786 Module *Mod = getSubmodule(ModID);
1787 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001788 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001789 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001790 }
1791
1792 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001793 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001794 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001795 }
1796 }
1797
1798 // Don't read the directive history for a module; we don't have anywhere
1799 // to put it.
1800 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1801 return;
1802
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001803 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001804 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001805 unsigned Idx = 0, N = Record.size();
1806 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001807 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001808 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001809 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1810 switch (K) {
1811 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001812 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001813 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001814 break;
1815 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001816 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001817 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001818 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001819 }
1820 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001821 bool isPublic = Record[Idx++];
1822 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1823 break;
1824 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001825
1826 if (!Latest)
1827 Latest = MD;
1828 if (Earliest)
1829 Earliest->setPrevious(MD);
1830 Earliest = MD;
1831 }
1832
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001833 if (Latest)
1834 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001835}
1836
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001837ASTReader::InputFileInfo
1838ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001839 // Go find this input file.
1840 BitstreamCursor &Cursor = F.InputFilesCursor;
1841 SavedStreamPosition SavedPosition(Cursor);
1842 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1843
1844 unsigned Code = Cursor.ReadCode();
1845 RecordData Record;
1846 StringRef Blob;
1847
1848 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1849 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1850 "invalid record type for input file");
1851 (void)Result;
1852
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001853 std::string Filename;
1854 off_t StoredSize;
1855 time_t StoredTime;
1856 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001857
Ben Langmuir198c1682014-03-07 07:27:49 +00001858 assert(Record[0] == ID && "Bogus stored ID or offset");
1859 StoredSize = static_cast<off_t>(Record[1]);
1860 StoredTime = static_cast<time_t>(Record[2]);
1861 Overridden = static_cast<bool>(Record[3]);
1862 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001863 ResolveImportedPath(F, Filename);
1864
Hans Wennborg73945142014-03-14 17:45:06 +00001865 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1866 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001867}
1868
1869std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001870 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00001871}
1872
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001873InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001874 // If this ID is bogus, just return an empty input file.
1875 if (ID == 0 || ID > F.InputFilesLoaded.size())
1876 return InputFile();
1877
1878 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001879 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001880 return F.InputFilesLoaded[ID-1];
1881
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001882 if (F.InputFilesLoaded[ID-1].isNotFound())
1883 return InputFile();
1884
Guy Benyei11169dd2012-12-18 14:30:41 +00001885 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001886 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001887 SavedStreamPosition SavedPosition(Cursor);
1888 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1889
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001890 InputFileInfo FI = readInputFileInfo(F, ID);
1891 off_t StoredSize = FI.StoredSize;
1892 time_t StoredTime = FI.StoredTime;
1893 bool Overridden = FI.Overridden;
1894 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001895
Ben Langmuir198c1682014-03-07 07:27:49 +00001896 const FileEntry *File
1897 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1898 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1899
1900 // If we didn't find the file, resolve it relative to the
1901 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00001902 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00001903 F.OriginalDir != CurrentDir) {
1904 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1905 F.OriginalDir,
1906 CurrentDir);
1907 if (!Resolved.empty())
1908 File = FileMgr.getFile(Resolved);
1909 }
1910
1911 // For an overridden file, create a virtual file with the stored
1912 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00001913 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001914 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1915 }
1916
Craig Toppera13603a2014-05-22 05:54:18 +00001917 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001918 if (Complain) {
1919 std::string ErrorStr = "could not find file '";
1920 ErrorStr += Filename;
1921 ErrorStr += "' referenced by AST file";
1922 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001923 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001924 // Record that we didn't find the file.
1925 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1926 return InputFile();
1927 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001928
Ben Langmuir198c1682014-03-07 07:27:49 +00001929 // Check if there was a request to override the contents of the file
1930 // that was part of the precompiled header. Overridding such a file
1931 // can lead to problems when lexing using the source locations from the
1932 // PCH.
1933 SourceManager &SM = getSourceManager();
1934 if (!Overridden && SM.isFileOverridden(File)) {
1935 if (Complain)
1936 Error(diag::err_fe_pch_file_overridden, Filename);
1937 // After emitting the diagnostic, recover by disabling the override so
1938 // that the original file will be used.
1939 SM.disableFileContentsOverride(File);
1940 // The FileEntry is a virtual file entry with the size of the contents
1941 // that would override the original contents. Set it to the original's
1942 // size/time.
1943 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1944 StoredSize, StoredTime);
1945 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001946
Ben Langmuir198c1682014-03-07 07:27:49 +00001947 bool IsOutOfDate = false;
1948
1949 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00001950 if (!Overridden && //
1951 (StoredSize != File->getSize() ||
1952#if defined(LLVM_ON_WIN32)
1953 false
1954#else
Ben Langmuir198c1682014-03-07 07:27:49 +00001955 // In our regression testing, the Windows file system seems to
1956 // have inconsistent modification times that sometimes
1957 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00001958 //
1959 // This also happens in networked file systems, so disable this
1960 // check if validation is disabled or if we have an explicitly
1961 // built PCM file.
1962 //
1963 // FIXME: Should we also do this for PCH files? They could also
1964 // reasonably get shared across a network during a distributed build.
1965 (StoredTime != File->getModificationTime() && !DisableValidation &&
1966 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001967#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00001968 )) {
1969 if (Complain) {
1970 // Build a list of the PCH imports that got us here (in reverse).
1971 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1972 while (ImportStack.back()->ImportedBy.size() > 0)
1973 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00001974
Ben Langmuir198c1682014-03-07 07:27:49 +00001975 // The top-level PCH is stale.
1976 StringRef TopLevelPCHName(ImportStack.back()->FileName);
1977 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00001978
Ben Langmuir198c1682014-03-07 07:27:49 +00001979 // Print the import stack.
1980 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
1981 Diag(diag::note_pch_required_by)
1982 << Filename << ImportStack[0]->FileName;
1983 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00001984 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00001985 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00001986 }
1987
Ben Langmuir198c1682014-03-07 07:27:49 +00001988 if (!Diags.isDiagnosticInFlight())
1989 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00001990 }
1991
Ben Langmuir198c1682014-03-07 07:27:49 +00001992 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001993 }
1994
Ben Langmuir198c1682014-03-07 07:27:49 +00001995 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
1996
1997 // Note that we've loaded this input file.
1998 F.InputFilesLoaded[ID-1] = IF;
1999 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002000}
2001
Richard Smith7ed1bc92014-12-05 22:42:13 +00002002/// \brief If we are loading a relocatable PCH or module file, and the filename
2003/// is not an absolute path, add the system or module root to the beginning of
2004/// the file name.
2005void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2006 // Resolve relative to the base directory, if we have one.
2007 if (!M.BaseDirectory.empty())
2008 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002009}
2010
Richard Smith7ed1bc92014-12-05 22:42:13 +00002011void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002012 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2013 return;
2014
Richard Smith7ed1bc92014-12-05 22:42:13 +00002015 SmallString<128> Buffer;
2016 llvm::sys::path::append(Buffer, Prefix, Filename);
2017 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002018}
2019
2020ASTReader::ASTReadResult
2021ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002022 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002023 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002024 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002025 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002026
2027 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2028 Error("malformed block record in AST file");
2029 return Failure;
2030 }
2031
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002032 // Should we allow the configuration of the module file to differ from the
2033 // configuration of the current translation unit in a compatible way?
2034 //
2035 // FIXME: Allow this for files explicitly specified with -include-pch too.
2036 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2037
Guy Benyei11169dd2012-12-18 14:30:41 +00002038 // Read all of the records and blocks in the control block.
2039 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002040 unsigned NumInputs = 0;
2041 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002042 while (1) {
2043 llvm::BitstreamEntry Entry = Stream.advance();
2044
2045 switch (Entry.Kind) {
2046 case llvm::BitstreamEntry::Error:
2047 Error("malformed block record in AST file");
2048 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002049 case llvm::BitstreamEntry::EndBlock: {
2050 // Validate input files.
2051 const HeaderSearchOptions &HSOpts =
2052 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002053
Richard Smitha1825302014-10-23 22:18:29 +00002054 // All user input files reside at the index range [0, NumUserInputs), and
2055 // system input files reside at [NumUserInputs, NumInputs).
Ben Langmuiracb803e2014-11-10 22:13:10 +00002056 if (!DisableValidation) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002057 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002058
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002059 // If we are reading a module, we will create a verification timestamp,
2060 // so we verify all input files. Otherwise, verify only user input
2061 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002062
2063 unsigned N = NumUserInputs;
2064 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002065 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002066 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002067 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002068 N = NumInputs;
2069
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002070 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002071 InputFile IF = getInputFile(F, I+1, Complain);
2072 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002073 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002074 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002075 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002076
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002077 if (Listener)
2078 Listener->visitModuleFile(F.FileName);
2079
Ben Langmuircb69b572014-03-07 06:40:32 +00002080 if (Listener && Listener->needsInputFileVisitation()) {
2081 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2082 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002083 for (unsigned I = 0; I < N; ++I) {
2084 bool IsSystem = I >= NumUserInputs;
2085 InputFileInfo FI = readInputFileInfo(F, I+1);
2086 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2087 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002088 }
2089
Guy Benyei11169dd2012-12-18 14:30:41 +00002090 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002091 }
2092
Chris Lattnere7b154b2013-01-19 21:39:22 +00002093 case llvm::BitstreamEntry::SubBlock:
2094 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002095 case INPUT_FILES_BLOCK_ID:
2096 F.InputFilesCursor = Stream;
2097 if (Stream.SkipBlock() || // Skip with the main cursor
2098 // Read the abbreviations
2099 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2100 Error("malformed block record in AST file");
2101 return Failure;
2102 }
2103 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002104
Guy Benyei11169dd2012-12-18 14:30:41 +00002105 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002106 if (Stream.SkipBlock()) {
2107 Error("malformed block record in AST file");
2108 return Failure;
2109 }
2110 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002111 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002112
2113 case llvm::BitstreamEntry::Record:
2114 // The interesting case.
2115 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002116 }
2117
2118 // Read and process a record.
2119 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002120 StringRef Blob;
2121 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002122 case METADATA: {
2123 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2124 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002125 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2126 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002127 return VersionMismatch;
2128 }
2129
2130 bool hasErrors = Record[5];
2131 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2132 Diag(diag::err_pch_with_compiler_errors);
2133 return HadErrors;
2134 }
2135
2136 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002137 // Relative paths in a relocatable PCH are relative to our sysroot.
2138 if (F.RelocatablePCH)
2139 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002140
2141 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002142 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002143 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2144 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002145 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002146 return VersionMismatch;
2147 }
2148 break;
2149 }
2150
Ben Langmuir487ea142014-10-23 18:05:36 +00002151 case SIGNATURE:
2152 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2153 F.Signature = Record[0];
2154 break;
2155
Guy Benyei11169dd2012-12-18 14:30:41 +00002156 case IMPORTS: {
2157 // Load each of the imported PCH files.
2158 unsigned Idx = 0, N = Record.size();
2159 while (Idx < N) {
2160 // Read information about the AST file.
2161 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2162 // The import location will be the local one for now; we will adjust
2163 // all import locations of module imports after the global source
2164 // location info are setup.
2165 SourceLocation ImportLoc =
2166 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002167 off_t StoredSize = (off_t)Record[Idx++];
2168 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002169 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002170 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002171
2172 // Load the AST file.
2173 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00002174 StoredSize, StoredModTime, StoredSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00002175 ClientLoadCapabilities)) {
2176 case Failure: return Failure;
2177 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002178 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002179 case OutOfDate: return OutOfDate;
2180 case VersionMismatch: return VersionMismatch;
2181 case ConfigurationMismatch: return ConfigurationMismatch;
2182 case HadErrors: return HadErrors;
2183 case Success: break;
2184 }
2185 }
2186 break;
2187 }
2188
Richard Smith7f330cd2015-03-18 01:42:29 +00002189 case KNOWN_MODULE_FILES:
2190 break;
2191
Guy Benyei11169dd2012-12-18 14:30:41 +00002192 case LANGUAGE_OPTIONS: {
2193 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002194 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002195 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002196 ParseLanguageOptions(Record, Complain, *Listener,
2197 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002198 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002199 return ConfigurationMismatch;
2200 break;
2201 }
2202
2203 case TARGET_OPTIONS: {
2204 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2205 if (Listener && &F == *ModuleMgr.begin() &&
Chandler Carruth0d745bc2015-03-14 04:47:43 +00002206 ParseTargetOptions(Record, Complain, *Listener,
2207 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002208 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002209 return ConfigurationMismatch;
2210 break;
2211 }
2212
2213 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002214 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002215 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002216 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002217 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002218 !DisableValidation)
2219 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002220 break;
2221 }
2222
2223 case FILE_SYSTEM_OPTIONS: {
2224 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2225 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002226 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002227 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002228 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002229 return ConfigurationMismatch;
2230 break;
2231 }
2232
2233 case HEADER_SEARCH_OPTIONS: {
2234 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2235 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002236 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002237 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002238 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002239 return ConfigurationMismatch;
2240 break;
2241 }
2242
2243 case PREPROCESSOR_OPTIONS: {
2244 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2245 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002246 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002247 ParsePreprocessorOptions(Record, Complain, *Listener,
2248 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002249 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002250 return ConfigurationMismatch;
2251 break;
2252 }
2253
2254 case ORIGINAL_FILE:
2255 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002256 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002257 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002258 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002259 break;
2260
2261 case ORIGINAL_FILE_ID:
2262 F.OriginalSourceFileID = FileID::get(Record[0]);
2263 break;
2264
2265 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002266 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002267 break;
2268
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002269 case MODULE_NAME:
2270 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002271 if (Listener)
2272 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002273 break;
2274
Richard Smith223d3f22014-12-06 03:21:08 +00002275 case MODULE_DIRECTORY: {
2276 assert(!F.ModuleName.empty() &&
2277 "MODULE_DIRECTORY found before MODULE_NAME");
2278 // If we've already loaded a module map file covering this module, we may
2279 // have a better path for it (relative to the current build).
2280 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2281 if (M && M->Directory) {
2282 // If we're implicitly loading a module, the base directory can't
2283 // change between the build and use.
2284 if (F.Kind != MK_ExplicitModule) {
2285 const DirectoryEntry *BuildDir =
2286 PP.getFileManager().getDirectory(Blob);
2287 if (!BuildDir || BuildDir != M->Directory) {
2288 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2289 Diag(diag::err_imported_module_relocated)
2290 << F.ModuleName << Blob << M->Directory->getName();
2291 return OutOfDate;
2292 }
2293 }
2294 F.BaseDirectory = M->Directory->getName();
2295 } else {
2296 F.BaseDirectory = Blob;
2297 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002298 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002299 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002300
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002301 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002302 if (ASTReadResult Result =
2303 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2304 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002305 break;
2306
Justin Bogner2172c3a2015-06-20 22:31:04 +00002307 case INPUT_FILE_OFFSETS: {
Richard Smitha1825302014-10-23 22:18:29 +00002308 NumInputs = Record[0];
2309 NumUserInputs = Record[1];
Justin Bogner2172c3a2015-06-20 22:31:04 +00002310 F.InputFileOffsets.clear();
2311 F.InputFileOffsets.reserve(NumInputs);
2312 using namespace llvm::support;
2313 const char *Buf = Blob.data();
2314 for (unsigned int I = 0; I < NumInputs; ++I)
2315 F.InputFileOffsets.push_back(
2316 endian::readNext<uint64_t, native, unaligned>(Buf));
2317
Richard Smitha1825302014-10-23 22:18:29 +00002318 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002319 break;
2320 }
Justin Bogner2172c3a2015-06-20 22:31:04 +00002321 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002322 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002323}
2324
Ben Langmuir2c9af442014-04-10 17:57:43 +00002325ASTReader::ASTReadResult
2326ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002327 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002328
2329 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2330 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002331 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002332 }
2333
2334 // Read all of the records and blocks for the AST file.
2335 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002336 while (1) {
2337 llvm::BitstreamEntry Entry = Stream.advance();
2338
2339 switch (Entry.Kind) {
2340 case llvm::BitstreamEntry::Error:
2341 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002342 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002343 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002344 // Outside of C++, we do not store a lookup map for the translation unit.
2345 // Instead, mark it as needing a lookup map to be built if this module
2346 // contains any declarations lexically within it (which it always does!).
2347 // This usually has no cost, since we very rarely need the lookup map for
2348 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002349 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002350 if (DC->hasExternalLexicalStorage() &&
2351 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002352 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002353
Ben Langmuir2c9af442014-04-10 17:57:43 +00002354 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002355 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002356 case llvm::BitstreamEntry::SubBlock:
2357 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002358 case DECLTYPES_BLOCK_ID:
2359 // We lazily load the decls block, but we want to set up the
2360 // DeclsCursor cursor to point into it. Clone our current bitcode
2361 // cursor to it, enter the block and read the abbrevs in that block.
2362 // With the main cursor, we just skip over it.
2363 F.DeclsCursor = Stream;
2364 if (Stream.SkipBlock() || // Skip with the main cursor.
2365 // Read the abbrevs.
2366 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2367 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002368 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002369 }
2370 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002371
Guy Benyei11169dd2012-12-18 14:30:41 +00002372 case PREPROCESSOR_BLOCK_ID:
2373 F.MacroCursor = Stream;
2374 if (!PP.getExternalSource())
2375 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002376
Guy Benyei11169dd2012-12-18 14:30:41 +00002377 if (Stream.SkipBlock() ||
2378 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2379 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002380 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002381 }
2382 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2383 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002384
Guy Benyei11169dd2012-12-18 14:30:41 +00002385 case PREPROCESSOR_DETAIL_BLOCK_ID:
2386 F.PreprocessorDetailCursor = Stream;
2387 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002388 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002389 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002390 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002391 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002392 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002393 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002394 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2395
Guy Benyei11169dd2012-12-18 14:30:41 +00002396 if (!PP.getPreprocessingRecord())
2397 PP.createPreprocessingRecord();
2398 if (!PP.getPreprocessingRecord()->getExternalSource())
2399 PP.getPreprocessingRecord()->SetExternalSource(*this);
2400 break;
2401
2402 case SOURCE_MANAGER_BLOCK_ID:
2403 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002404 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002405 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002406
Guy Benyei11169dd2012-12-18 14:30:41 +00002407 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002408 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2409 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002410 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002411
Guy Benyei11169dd2012-12-18 14:30:41 +00002412 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002413 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002414 if (Stream.SkipBlock() ||
2415 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2416 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002417 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002418 }
2419 CommentsCursors.push_back(std::make_pair(C, &F));
2420 break;
2421 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002422
Guy Benyei11169dd2012-12-18 14:30:41 +00002423 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002424 if (Stream.SkipBlock()) {
2425 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002426 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002427 }
2428 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002429 }
2430 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002431
2432 case llvm::BitstreamEntry::Record:
2433 // The interesting case.
2434 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002435 }
2436
2437 // Read and process a record.
2438 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002439 StringRef Blob;
2440 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002441 default: // Default behavior: ignore.
2442 break;
2443
2444 case TYPE_OFFSET: {
2445 if (F.LocalNumTypes != 0) {
2446 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002447 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002448 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002449 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002450 F.LocalNumTypes = Record[0];
2451 unsigned LocalBaseTypeIndex = Record[1];
2452 F.BaseTypeIndex = getTotalNumTypes();
2453
2454 if (F.LocalNumTypes > 0) {
2455 // Introduce the global -> local mapping for types within this module.
2456 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2457
2458 // Introduce the local -> global mapping for types within this module.
2459 F.TypeRemap.insertOrReplace(
2460 std::make_pair(LocalBaseTypeIndex,
2461 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002462
2463 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002464 }
2465 break;
2466 }
2467
2468 case DECL_OFFSET: {
2469 if (F.LocalNumDecls != 0) {
2470 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002471 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002472 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002473 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002474 F.LocalNumDecls = Record[0];
2475 unsigned LocalBaseDeclID = Record[1];
2476 F.BaseDeclID = getTotalNumDecls();
2477
2478 if (F.LocalNumDecls > 0) {
2479 // Introduce the global -> local mapping for declarations within this
2480 // module.
2481 GlobalDeclMap.insert(
2482 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2483
2484 // Introduce the local -> global mapping for declarations within this
2485 // module.
2486 F.DeclRemap.insertOrReplace(
2487 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2488
2489 // Introduce the global -> local mapping for declarations within this
2490 // module.
2491 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002492
Ben Langmuir52ca6782014-10-20 16:27:32 +00002493 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2494 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002495 break;
2496 }
2497
2498 case TU_UPDATE_LEXICAL: {
2499 DeclContext *TU = Context.getTranslationUnitDecl();
2500 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002501 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002502 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002503 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002504 TU->setHasExternalLexicalStorage(true);
2505 break;
2506 }
2507
2508 case UPDATE_VISIBLE: {
2509 unsigned Idx = 0;
2510 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2511 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002512 ASTDeclContextNameLookupTable::Create(
2513 (const unsigned char *)Blob.data() + Record[Idx++],
2514 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2515 (const unsigned char *)Blob.data(),
2516 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002517 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002518 auto *DC = cast<DeclContext>(D);
2519 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002520 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2521 delete LookupTable;
2522 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002523 } else
2524 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2525 break;
2526 }
2527
2528 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002529 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002530 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002531 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2532 (const unsigned char *)F.IdentifierTableData + Record[0],
2533 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2534 (const unsigned char *)F.IdentifierTableData,
2535 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002536
2537 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2538 }
2539 break;
2540
2541 case IDENTIFIER_OFFSET: {
2542 if (F.LocalNumIdentifiers != 0) {
2543 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002544 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002545 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002546 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002547 F.LocalNumIdentifiers = Record[0];
2548 unsigned LocalBaseIdentifierID = Record[1];
2549 F.BaseIdentifierID = getTotalNumIdentifiers();
2550
2551 if (F.LocalNumIdentifiers > 0) {
2552 // Introduce the global -> local mapping for identifiers within this
2553 // module.
2554 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2555 &F));
2556
2557 // Introduce the local -> global mapping for identifiers within this
2558 // module.
2559 F.IdentifierRemap.insertOrReplace(
2560 std::make_pair(LocalBaseIdentifierID,
2561 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002562
Ben Langmuir52ca6782014-10-20 16:27:32 +00002563 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2564 + F.LocalNumIdentifiers);
2565 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002566 break;
2567 }
2568
Ben Langmuir332aafe2014-01-31 01:06:56 +00002569 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002570 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2571 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002573 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002574 break;
2575
2576 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002577 if (SpecialTypes.empty()) {
2578 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2579 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2580 break;
2581 }
2582
2583 if (SpecialTypes.size() != Record.size()) {
2584 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002585 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002586 }
2587
2588 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2589 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2590 if (!SpecialTypes[I])
2591 SpecialTypes[I] = ID;
2592 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2593 // merge step?
2594 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 break;
2596
2597 case STATISTICS:
2598 TotalNumStatements += Record[0];
2599 TotalNumMacros += Record[1];
2600 TotalLexicalDeclContexts += Record[2];
2601 TotalVisibleDeclContexts += Record[3];
2602 break;
2603
2604 case UNUSED_FILESCOPED_DECLS:
2605 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2606 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2607 break;
2608
2609 case DELEGATING_CTORS:
2610 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2611 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2612 break;
2613
2614 case WEAK_UNDECLARED_IDENTIFIERS:
2615 if (Record.size() % 4 != 0) {
2616 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002617 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002618 }
2619
2620 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2621 // files. This isn't the way to do it :)
2622 WeakUndeclaredIdentifiers.clear();
2623
2624 // Translate the weak, undeclared identifiers into global IDs.
2625 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2626 WeakUndeclaredIdentifiers.push_back(
2627 getGlobalIdentifierID(F, Record[I++]));
2628 WeakUndeclaredIdentifiers.push_back(
2629 getGlobalIdentifierID(F, Record[I++]));
2630 WeakUndeclaredIdentifiers.push_back(
2631 ReadSourceLocation(F, Record, I).getRawEncoding());
2632 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2633 }
2634 break;
2635
Guy Benyei11169dd2012-12-18 14:30:41 +00002636 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002637 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002638 F.LocalNumSelectors = Record[0];
2639 unsigned LocalBaseSelectorID = Record[1];
2640 F.BaseSelectorID = getTotalNumSelectors();
2641
2642 if (F.LocalNumSelectors > 0) {
2643 // Introduce the global -> local mapping for selectors within this
2644 // module.
2645 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2646
2647 // Introduce the local -> global mapping for selectors within this
2648 // module.
2649 F.SelectorRemap.insertOrReplace(
2650 std::make_pair(LocalBaseSelectorID,
2651 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002652
2653 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002654 }
2655 break;
2656 }
2657
2658 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002659 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002660 if (Record[0])
2661 F.SelectorLookupTable
2662 = ASTSelectorLookupTable::Create(
2663 F.SelectorLookupTableData + Record[0],
2664 F.SelectorLookupTableData,
2665 ASTSelectorLookupTrait(*this, F));
2666 TotalNumMethodPoolEntries += Record[1];
2667 break;
2668
2669 case REFERENCED_SELECTOR_POOL:
2670 if (!Record.empty()) {
2671 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2672 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2673 Record[Idx++]));
2674 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2675 getRawEncoding());
2676 }
2677 }
2678 break;
2679
2680 case PP_COUNTER_VALUE:
2681 if (!Record.empty() && Listener)
2682 Listener->ReadCounter(F, Record[0]);
2683 break;
2684
2685 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002686 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002687 F.NumFileSortedDecls = Record[0];
2688 break;
2689
2690 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002691 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002692 F.LocalNumSLocEntries = Record[0];
2693 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002694 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002695 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002696 SLocSpaceSize);
2697 // Make our entry in the range map. BaseID is negative and growing, so
2698 // we invert it. Because we invert it, though, we need the other end of
2699 // the range.
2700 unsigned RangeStart =
2701 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2702 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2703 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2704
2705 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2706 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2707 GlobalSLocOffsetMap.insert(
2708 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2709 - SLocSpaceSize,&F));
2710
2711 // Initialize the remapping table.
2712 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002713 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002714 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002715 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002716 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2717
2718 TotalNumSLocEntries += F.LocalNumSLocEntries;
2719 break;
2720 }
2721
2722 case MODULE_OFFSET_MAP: {
2723 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002724 const unsigned char *Data = (const unsigned char*)Blob.data();
2725 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002726
2727 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2728 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2729 F.SLocRemap.insert(std::make_pair(0U, 0));
2730 F.SLocRemap.insert(std::make_pair(2U, 1));
2731 }
2732
Guy Benyei11169dd2012-12-18 14:30:41 +00002733 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002734 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2735 RemapBuilder;
2736 RemapBuilder SLocRemap(F.SLocRemap);
2737 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2738 RemapBuilder MacroRemap(F.MacroRemap);
2739 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2740 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2741 RemapBuilder SelectorRemap(F.SelectorRemap);
2742 RemapBuilder DeclRemap(F.DeclRemap);
2743 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002744
2745 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002746 using namespace llvm::support;
2747 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002748 StringRef Name = StringRef((const char*)Data, Len);
2749 Data += Len;
2750 ModuleFile *OM = ModuleMgr.lookup(Name);
2751 if (!OM) {
2752 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002753 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002754 }
2755
Justin Bogner57ba0b22014-03-28 22:03:24 +00002756 uint32_t SLocOffset =
2757 endian::readNext<uint32_t, little, unaligned>(Data);
2758 uint32_t IdentifierIDOffset =
2759 endian::readNext<uint32_t, little, unaligned>(Data);
2760 uint32_t MacroIDOffset =
2761 endian::readNext<uint32_t, little, unaligned>(Data);
2762 uint32_t PreprocessedEntityIDOffset =
2763 endian::readNext<uint32_t, little, unaligned>(Data);
2764 uint32_t SubmoduleIDOffset =
2765 endian::readNext<uint32_t, little, unaligned>(Data);
2766 uint32_t SelectorIDOffset =
2767 endian::readNext<uint32_t, little, unaligned>(Data);
2768 uint32_t DeclIDOffset =
2769 endian::readNext<uint32_t, little, unaligned>(Data);
2770 uint32_t TypeIndexOffset =
2771 endian::readNext<uint32_t, little, unaligned>(Data);
2772
Ben Langmuir785180e2014-10-20 16:27:30 +00002773 uint32_t None = std::numeric_limits<uint32_t>::max();
2774
2775 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2776 RemapBuilder &Remap) {
2777 if (Offset != None)
2778 Remap.insert(std::make_pair(Offset,
2779 static_cast<int>(BaseOffset - Offset)));
2780 };
2781 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2782 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2783 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2784 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2785 PreprocessedEntityRemap);
2786 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2787 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2788 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2789 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002790
2791 // Global -> local mappings.
2792 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2793 }
2794 break;
2795 }
2796
2797 case SOURCE_MANAGER_LINE_TABLE:
2798 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002799 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002800 break;
2801
2802 case SOURCE_LOCATION_PRELOADS: {
2803 // Need to transform from the local view (1-based IDs) to the global view,
2804 // which is based off F.SLocEntryBaseID.
2805 if (!F.PreloadSLocEntries.empty()) {
2806 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002807 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002808 }
2809
2810 F.PreloadSLocEntries.swap(Record);
2811 break;
2812 }
2813
2814 case EXT_VECTOR_DECLS:
2815 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2816 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2817 break;
2818
2819 case VTABLE_USES:
2820 if (Record.size() % 3 != 0) {
2821 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002822 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002823 }
2824
2825 // Later tables overwrite earlier ones.
2826 // FIXME: Modules will have some trouble with this. This is clearly not
2827 // the right way to do this.
2828 VTableUses.clear();
2829
2830 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2831 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2832 VTableUses.push_back(
2833 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2834 VTableUses.push_back(Record[Idx++]);
2835 }
2836 break;
2837
Guy Benyei11169dd2012-12-18 14:30:41 +00002838 case PENDING_IMPLICIT_INSTANTIATIONS:
2839 if (PendingInstantiations.size() % 2 != 0) {
2840 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002841 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002842 }
2843
2844 if (Record.size() % 2 != 0) {
2845 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002846 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002847 }
2848
2849 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2850 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2851 PendingInstantiations.push_back(
2852 ReadSourceLocation(F, Record, I).getRawEncoding());
2853 }
2854 break;
2855
2856 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002857 if (Record.size() != 2) {
2858 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002859 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002860 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002861 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2862 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2863 break;
2864
2865 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002866 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2867 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2868 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002869
2870 unsigned LocalBasePreprocessedEntityID = Record[0];
2871
2872 unsigned StartingID;
2873 if (!PP.getPreprocessingRecord())
2874 PP.createPreprocessingRecord();
2875 if (!PP.getPreprocessingRecord()->getExternalSource())
2876 PP.getPreprocessingRecord()->SetExternalSource(*this);
2877 StartingID
2878 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00002879 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00002880 F.BasePreprocessedEntityID = StartingID;
2881
2882 if (F.NumPreprocessedEntities > 0) {
2883 // Introduce the global -> local mapping for preprocessed entities in
2884 // this module.
2885 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2886
2887 // Introduce the local -> global mapping for preprocessed entities in
2888 // this module.
2889 F.PreprocessedEntityRemap.insertOrReplace(
2890 std::make_pair(LocalBasePreprocessedEntityID,
2891 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2892 }
2893
2894 break;
2895 }
2896
2897 case DECL_UPDATE_OFFSETS: {
2898 if (Record.size() % 2 != 0) {
2899 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002900 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002901 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00002902 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
2903 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
2904 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
2905
2906 // If we've already loaded the decl, perform the updates when we finish
2907 // loading this block.
2908 if (Decl *D = GetExistingDecl(ID))
2909 PendingUpdateRecords.push_back(std::make_pair(ID, D));
2910 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002911 break;
2912 }
2913
2914 case DECL_REPLACEMENTS: {
2915 if (Record.size() % 3 != 0) {
2916 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002917 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002918 }
2919 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2920 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2921 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2922 break;
2923 }
2924
2925 case OBJC_CATEGORIES_MAP: {
2926 if (F.LocalNumObjCCategoriesInMap != 0) {
2927 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002928 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002929 }
2930
2931 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002932 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002933 break;
2934 }
2935
2936 case OBJC_CATEGORIES:
2937 F.ObjCCategories.swap(Record);
2938 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00002939
Guy Benyei11169dd2012-12-18 14:30:41 +00002940 case CXX_BASE_SPECIFIER_OFFSETS: {
2941 if (F.LocalNumCXXBaseSpecifiers != 0) {
2942 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002943 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002944 }
Richard Smithc2bb8182015-03-24 06:36:48 +00002945
Guy Benyei11169dd2012-12-18 14:30:41 +00002946 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002947 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00002948 break;
2949 }
2950
2951 case CXX_CTOR_INITIALIZERS_OFFSETS: {
2952 if (F.LocalNumCXXCtorInitializers != 0) {
2953 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
2954 return Failure;
2955 }
2956
2957 F.LocalNumCXXCtorInitializers = Record[0];
2958 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002959 break;
2960 }
2961
2962 case DIAG_PRAGMA_MAPPINGS:
2963 if (F.PragmaDiagMappings.empty())
2964 F.PragmaDiagMappings.swap(Record);
2965 else
2966 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2967 Record.begin(), Record.end());
2968 break;
2969
2970 case CUDA_SPECIAL_DECL_REFS:
2971 // Later tables overwrite earlier ones.
2972 // FIXME: Modules will have trouble with this.
2973 CUDASpecialDeclRefs.clear();
2974 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2975 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2976 break;
2977
2978 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002979 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002980 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00002981 if (Record[0]) {
2982 F.HeaderFileInfoTable
2983 = HeaderFileInfoLookupTable::Create(
2984 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2985 (const unsigned char *)F.HeaderFileInfoTableData,
2986 HeaderFileInfoTrait(*this, F,
2987 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00002988 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002989
2990 PP.getHeaderSearchInfo().SetExternalSource(this);
2991 if (!PP.getHeaderSearchInfo().getExternalLookup())
2992 PP.getHeaderSearchInfo().SetExternalLookup(this);
2993 }
2994 break;
2995 }
2996
2997 case FP_PRAGMA_OPTIONS:
2998 // Later tables overwrite earlier ones.
2999 FPPragmaOptions.swap(Record);
3000 break;
3001
3002 case OPENCL_EXTENSIONS:
3003 // Later tables overwrite earlier ones.
3004 OpenCLExtensions.swap(Record);
3005 break;
3006
3007 case TENTATIVE_DEFINITIONS:
3008 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3009 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3010 break;
3011
3012 case KNOWN_NAMESPACES:
3013 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3014 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3015 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003016
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003017 case UNDEFINED_BUT_USED:
3018 if (UndefinedButUsed.size() % 2 != 0) {
3019 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003020 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003021 }
3022
3023 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003024 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003025 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003026 }
3027 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003028 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3029 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003030 ReadSourceLocation(F, Record, I).getRawEncoding());
3031 }
3032 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003033 case DELETE_EXPRS_TO_ANALYZE:
3034 for (unsigned I = 0, N = Record.size(); I != N;) {
3035 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3036 const uint64_t Count = Record[I++];
3037 DelayedDeleteExprs.push_back(Count);
3038 for (uint64_t C = 0; C < Count; ++C) {
3039 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3040 bool IsArrayForm = Record[I++] == 1;
3041 DelayedDeleteExprs.push_back(IsArrayForm);
3042 }
3043 }
3044 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003045
Guy Benyei11169dd2012-12-18 14:30:41 +00003046 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003047 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003048 // If we aren't loading a module (which has its own exports), make
3049 // all of the imported modules visible.
3050 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003051 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3052 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3053 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3054 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003055 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003056 }
3057 }
3058 break;
3059 }
3060
3061 case LOCAL_REDECLARATIONS: {
3062 F.RedeclarationChains.swap(Record);
3063 break;
3064 }
3065
3066 case LOCAL_REDECLARATIONS_MAP: {
3067 if (F.LocalNumRedeclarationsInMap != 0) {
3068 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003069 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003070 }
3071
3072 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003073 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003074 break;
3075 }
3076
Guy Benyei11169dd2012-12-18 14:30:41 +00003077 case MACRO_OFFSET: {
3078 if (F.LocalNumMacros != 0) {
3079 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003080 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003081 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003082 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003083 F.LocalNumMacros = Record[0];
3084 unsigned LocalBaseMacroID = Record[1];
3085 F.BaseMacroID = getTotalNumMacros();
3086
3087 if (F.LocalNumMacros > 0) {
3088 // Introduce the global -> local mapping for macros within this module.
3089 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3090
3091 // Introduce the local -> global mapping for macros within this module.
3092 F.MacroRemap.insertOrReplace(
3093 std::make_pair(LocalBaseMacroID,
3094 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003095
3096 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003097 }
3098 break;
3099 }
3100
Richard Smithe40f2ba2013-08-07 21:41:30 +00003101 case LATE_PARSED_TEMPLATE: {
3102 LateParsedTemplates.append(Record.begin(), Record.end());
3103 break;
3104 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003105
3106 case OPTIMIZE_PRAGMA_OPTIONS:
3107 if (Record.size() != 1) {
3108 Error("invalid pragma optimize record");
3109 return Failure;
3110 }
3111 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3112 break;
Nico Weber72889432014-09-06 01:25:55 +00003113
3114 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3115 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3116 UnusedLocalTypedefNameCandidates.push_back(
3117 getGlobalDeclID(F, Record[I]));
3118 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003119 }
3120 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003121}
3122
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003123ASTReader::ASTReadResult
3124ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3125 const ModuleFile *ImportedBy,
3126 unsigned ClientLoadCapabilities) {
3127 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003128 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003129
Richard Smithe842a472014-10-22 02:05:46 +00003130 if (F.Kind == MK_ExplicitModule) {
3131 // For an explicitly-loaded module, we don't care whether the original
3132 // module map file exists or matches.
3133 return Success;
3134 }
3135
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003136 // Try to resolve ModuleName in the current header search context and
3137 // verify that it is found in the same module map file as we saved. If the
3138 // top-level AST file is a main file, skip this check because there is no
3139 // usable header search context.
3140 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003141 "MODULE_NAME should come before MODULE_MAP_FILE");
3142 if (F.Kind == MK_ImplicitModule &&
3143 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3144 // An implicitly-loaded module file should have its module listed in some
3145 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003146 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003147 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3148 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3149 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003150 assert(ImportedBy && "top-level import should be verified");
3151 if ((ClientLoadCapabilities & ARR_Missing) == 0)
Richard Smithe842a472014-10-22 02:05:46 +00003152 Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3153 << ImportedBy->FileName
3154 << F.ModuleMapPath;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003155 return Missing;
3156 }
3157
Richard Smithe842a472014-10-22 02:05:46 +00003158 assert(M->Name == F.ModuleName && "found module with different name");
3159
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003160 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003161 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003162 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3163 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003164 assert(ImportedBy && "top-level import should be verified");
3165 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3166 Diag(diag::err_imported_module_modmap_changed)
3167 << F.ModuleName << ImportedBy->FileName
3168 << ModMap->getName() << F.ModuleMapPath;
3169 return OutOfDate;
3170 }
3171
3172 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3173 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3174 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003175 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003176 const FileEntry *F =
3177 FileMgr.getFile(Filename, false, false);
3178 if (F == nullptr) {
3179 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3180 Error("could not find file '" + Filename +"' referenced by AST file");
3181 return OutOfDate;
3182 }
3183 AdditionalStoredMaps.insert(F);
3184 }
3185
3186 // Check any additional module map files (e.g. module.private.modulemap)
3187 // that are not in the pcm.
3188 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3189 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3190 // Remove files that match
3191 // Note: SmallPtrSet::erase is really remove
3192 if (!AdditionalStoredMaps.erase(ModMap)) {
3193 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3194 Diag(diag::err_module_different_modmap)
3195 << F.ModuleName << /*new*/0 << ModMap->getName();
3196 return OutOfDate;
3197 }
3198 }
3199 }
3200
3201 // Check any additional module map files that are in the pcm, but not
3202 // found in header search. Cases that match are already removed.
3203 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3204 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3205 Diag(diag::err_module_different_modmap)
3206 << F.ModuleName << /*not new*/1 << ModMap->getName();
3207 return OutOfDate;
3208 }
3209 }
3210
3211 if (Listener)
3212 Listener->ReadModuleMapFile(F.ModuleMapPath);
3213 return Success;
3214}
3215
3216
Douglas Gregorc1489562013-02-12 23:36:21 +00003217/// \brief Move the given method to the back of the global list of methods.
3218static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3219 // Find the entry for this selector in the method pool.
3220 Sema::GlobalMethodPool::iterator Known
3221 = S.MethodPool.find(Method->getSelector());
3222 if (Known == S.MethodPool.end())
3223 return;
3224
3225 // Retrieve the appropriate method list.
3226 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3227 : Known->second.second;
3228 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003229 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003230 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003231 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003232 Found = true;
3233 } else {
3234 // Keep searching.
3235 continue;
3236 }
3237 }
3238
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003239 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003240 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003241 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003242 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003243 }
3244}
3245
Richard Smithde711422015-04-23 21:20:19 +00003246void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003247 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003248 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003249 bool wasHidden = D->Hidden;
3250 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003251
Richard Smith49f906a2014-03-01 00:08:04 +00003252 if (wasHidden && SemaObj) {
3253 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3254 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003255 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003256 }
3257 }
3258}
3259
Richard Smith49f906a2014-03-01 00:08:04 +00003260void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003261 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003262 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003263 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003264 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003265 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003266 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003267 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003268
3269 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003270 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003271 // there is nothing more to do.
3272 continue;
3273 }
Richard Smith49f906a2014-03-01 00:08:04 +00003274
Guy Benyei11169dd2012-12-18 14:30:41 +00003275 if (!Mod->isAvailable()) {
3276 // Modules that aren't available cannot be made visible.
3277 continue;
3278 }
3279
3280 // Update the module's name visibility.
3281 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003282
Guy Benyei11169dd2012-12-18 14:30:41 +00003283 // If we've already deserialized any names from this module,
3284 // mark them as visible.
3285 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3286 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003287 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003288 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003289 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003290 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3291 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003292 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003293
Guy Benyei11169dd2012-12-18 14:30:41 +00003294 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003295 SmallVector<Module *, 16> Exports;
3296 Mod->getExportedModules(Exports);
3297 for (SmallVectorImpl<Module *>::iterator
3298 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3299 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003300 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003301 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003302 }
3303 }
3304}
3305
Douglas Gregore060e572013-01-25 01:03:03 +00003306bool ASTReader::loadGlobalIndex() {
3307 if (GlobalIndex)
3308 return false;
3309
3310 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3311 !Context.getLangOpts().Modules)
3312 return true;
3313
3314 // Try to load the global index.
3315 TriedLoadingGlobalIndex = true;
3316 StringRef ModuleCachePath
3317 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3318 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003319 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003320 if (!Result.first)
3321 return true;
3322
3323 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003324 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003325 return false;
3326}
3327
3328bool ASTReader::isGlobalIndexUnavailable() const {
3329 return Context.getLangOpts().Modules && UseGlobalIndex &&
3330 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3331}
3332
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003333static void updateModuleTimestamp(ModuleFile &MF) {
3334 // Overwrite the timestamp file contents so that file's mtime changes.
3335 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003336 std::error_code EC;
3337 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3338 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003339 return;
3340 OS << "Timestamp file\n";
3341}
3342
Guy Benyei11169dd2012-12-18 14:30:41 +00003343ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3344 ModuleKind Type,
3345 SourceLocation ImportLoc,
3346 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003347 llvm::SaveAndRestore<SourceLocation>
3348 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3349
Richard Smithd1c46742014-04-30 02:24:17 +00003350 // Defer any pending actions until we get to the end of reading the AST file.
3351 Deserializing AnASTFile(this);
3352
Guy Benyei11169dd2012-12-18 14:30:41 +00003353 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003354 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003355
3356 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003357 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003358 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003359 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003360 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003361 ClientLoadCapabilities)) {
3362 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003363 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003364 case OutOfDate:
3365 case VersionMismatch:
3366 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003367 case HadErrors: {
3368 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3369 for (const ImportedModule &IM : Loaded)
3370 LoadedSet.insert(IM.Mod);
3371
Douglas Gregor7029ce12013-03-19 00:28:20 +00003372 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003373 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003374 Context.getLangOpts().Modules
3375 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003376 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003377
3378 // If we find that any modules are unusable, the global index is going
3379 // to be out-of-date. Just remove it.
3380 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003381 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003382 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003383 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003384 case Success:
3385 break;
3386 }
3387
3388 // Here comes stuff that we only do once the entire chain is loaded.
3389
3390 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003391 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3392 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003393 M != MEnd; ++M) {
3394 ModuleFile &F = *M->Mod;
3395
3396 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003397 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3398 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003399
3400 // Once read, set the ModuleFile bit base offset and update the size in
3401 // bits of all files we've seen.
3402 F.GlobalBitOffset = TotalModulesSizeInBits;
3403 TotalModulesSizeInBits += F.SizeInBits;
3404 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3405
3406 // Preload SLocEntries.
3407 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3408 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3409 // Load it through the SourceManager and don't call ReadSLocEntry()
3410 // directly because the entry may have already been loaded in which case
3411 // calling ReadSLocEntry() directly would trigger an assertion in
3412 // SourceManager.
3413 SourceMgr.getLoadedSLocEntryByID(Index);
3414 }
3415 }
3416
Douglas Gregor603cd862013-03-22 18:50:14 +00003417 // Setup the import locations and notify the module manager that we've
3418 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003419 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3420 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003421 M != MEnd; ++M) {
3422 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003423
3424 ModuleMgr.moduleFileAccepted(&F);
3425
3426 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003427 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003428 if (!M->ImportedBy)
3429 F.ImportLoc = M->ImportLoc;
3430 else
3431 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3432 M->ImportLoc.getRawEncoding());
3433 }
3434
3435 // Mark all of the identifiers in the identifier table as being out of date,
3436 // so that various accessors know to check the loaded modules when the
3437 // identifier is used.
3438 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3439 IdEnd = PP.getIdentifierTable().end();
3440 Id != IdEnd; ++Id)
3441 Id->second->setOutOfDate(true);
3442
3443 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003444 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3445 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003446 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3447 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003448
3449 switch (Unresolved.Kind) {
3450 case UnresolvedModuleRef::Conflict:
3451 if (ResolvedMod) {
3452 Module::Conflict Conflict;
3453 Conflict.Other = ResolvedMod;
3454 Conflict.Message = Unresolved.String.str();
3455 Unresolved.Mod->Conflicts.push_back(Conflict);
3456 }
3457 continue;
3458
3459 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003460 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003461 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003462 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003463
Douglas Gregorfb912652013-03-20 21:10:35 +00003464 case UnresolvedModuleRef::Export:
3465 if (ResolvedMod || Unresolved.IsWildcard)
3466 Unresolved.Mod->Exports.push_back(
3467 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3468 continue;
3469 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003470 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003471 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003472
3473 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3474 // Might be unnecessary as use declarations are only used to build the
3475 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003476
3477 InitializeContext();
3478
Richard Smith3d8e97e2013-10-18 06:54:39 +00003479 if (SemaObj)
3480 UpdateSema();
3481
Guy Benyei11169dd2012-12-18 14:30:41 +00003482 if (DeserializationListener)
3483 DeserializationListener->ReaderInitialized(this);
3484
3485 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3486 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3487 PrimaryModule.OriginalSourceFileID
3488 = FileID::get(PrimaryModule.SLocEntryBaseID
3489 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3490
3491 // If this AST file is a precompiled preamble, then set the
3492 // preamble file ID of the source manager to the file source file
3493 // from which the preamble was built.
3494 if (Type == MK_Preamble) {
3495 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3496 } else if (Type == MK_MainFile) {
3497 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3498 }
3499 }
3500
3501 // For any Objective-C class definitions we have already loaded, make sure
3502 // that we load any additional categories.
3503 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3504 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3505 ObjCClassesLoaded[I],
3506 PreviousGeneration);
3507 }
Douglas Gregore060e572013-01-25 01:03:03 +00003508
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003509 if (PP.getHeaderSearchInfo()
3510 .getHeaderSearchOpts()
3511 .ModulesValidateOncePerBuildSession) {
3512 // Now we are certain that the module and all modules it depends on are
3513 // up to date. Create or update timestamp files for modules that are
3514 // located in the module cache (not for PCH files that could be anywhere
3515 // in the filesystem).
3516 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3517 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003518 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003519 updateModuleTimestamp(*M.Mod);
3520 }
3521 }
3522 }
3523
Guy Benyei11169dd2012-12-18 14:30:41 +00003524 return Success;
3525}
3526
Ben Langmuir487ea142014-10-23 18:05:36 +00003527static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3528
Ben Langmuir70a1b812015-03-24 04:43:52 +00003529/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3530static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3531 return Stream.Read(8) == 'C' &&
3532 Stream.Read(8) == 'P' &&
3533 Stream.Read(8) == 'C' &&
3534 Stream.Read(8) == 'H';
3535}
3536
Guy Benyei11169dd2012-12-18 14:30:41 +00003537ASTReader::ASTReadResult
3538ASTReader::ReadASTCore(StringRef FileName,
3539 ModuleKind Type,
3540 SourceLocation ImportLoc,
3541 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003542 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003543 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003544 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003545 unsigned ClientLoadCapabilities) {
3546 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003547 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003548 ModuleManager::AddModuleResult AddResult
3549 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003550 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003551 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003552 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003553
Douglas Gregor7029ce12013-03-19 00:28:20 +00003554 switch (AddResult) {
3555 case ModuleManager::AlreadyLoaded:
3556 return Success;
3557
3558 case ModuleManager::NewlyLoaded:
3559 // Load module file below.
3560 break;
3561
3562 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003563 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003564 // it.
3565 if (ClientLoadCapabilities & ARR_Missing)
3566 return Missing;
3567
3568 // Otherwise, return an error.
3569 {
3570 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3571 + ErrorStr;
3572 Error(Msg);
3573 }
3574 return Failure;
3575
3576 case ModuleManager::OutOfDate:
3577 // We couldn't load the module file because it is out-of-date. If the
3578 // client can handle out-of-date, return it.
3579 if (ClientLoadCapabilities & ARR_OutOfDate)
3580 return OutOfDate;
3581
3582 // Otherwise, return an error.
3583 {
3584 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3585 + ErrorStr;
3586 Error(Msg);
3587 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003588 return Failure;
3589 }
3590
Douglas Gregor7029ce12013-03-19 00:28:20 +00003591 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003592
3593 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3594 // module?
3595 if (FileName != "-") {
3596 CurrentDir = llvm::sys::path::parent_path(FileName);
3597 if (CurrentDir.empty()) CurrentDir = ".";
3598 }
3599
3600 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003601 BitstreamCursor &Stream = F.Stream;
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003602 PCHContainerOps.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003603 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003604 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3605
Guy Benyei11169dd2012-12-18 14:30:41 +00003606 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003607 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003608 Diag(diag::err_not_a_pch_file) << FileName;
3609 return Failure;
3610 }
3611
3612 // This is used for compatibility with older PCH formats.
3613 bool HaveReadControlBlock = false;
3614
Chris Lattnerefa77172013-01-20 00:00:22 +00003615 while (1) {
3616 llvm::BitstreamEntry Entry = Stream.advance();
3617
3618 switch (Entry.Kind) {
3619 case llvm::BitstreamEntry::Error:
3620 case llvm::BitstreamEntry::EndBlock:
3621 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003622 Error("invalid record at top-level of AST file");
3623 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003624
3625 case llvm::BitstreamEntry::SubBlock:
3626 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003627 }
3628
Guy Benyei11169dd2012-12-18 14:30:41 +00003629 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003630 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003631 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3632 if (Stream.ReadBlockInfoBlock()) {
3633 Error("malformed BlockInfoBlock in AST file");
3634 return Failure;
3635 }
3636 break;
3637 case CONTROL_BLOCK_ID:
3638 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003639 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003640 case Success:
3641 break;
3642
3643 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003644 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003645 case OutOfDate: return OutOfDate;
3646 case VersionMismatch: return VersionMismatch;
3647 case ConfigurationMismatch: return ConfigurationMismatch;
3648 case HadErrors: return HadErrors;
3649 }
3650 break;
3651 case AST_BLOCK_ID:
3652 if (!HaveReadControlBlock) {
3653 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003654 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003655 return VersionMismatch;
3656 }
3657
3658 // Record that we've loaded this module.
3659 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3660 return Success;
3661
3662 default:
3663 if (Stream.SkipBlock()) {
3664 Error("malformed block record in AST file");
3665 return Failure;
3666 }
3667 break;
3668 }
3669 }
3670
3671 return Success;
3672}
3673
Richard Smitha7e2cc62015-05-01 01:53:09 +00003674void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003675 // If there's a listener, notify them that we "read" the translation unit.
3676 if (DeserializationListener)
3677 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3678 Context.getTranslationUnitDecl());
3679
Guy Benyei11169dd2012-12-18 14:30:41 +00003680 // FIXME: Find a better way to deal with collisions between these
3681 // built-in types. Right now, we just ignore the problem.
3682
3683 // Load the special types.
3684 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3685 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3686 if (!Context.CFConstantStringTypeDecl)
3687 Context.setCFConstantStringType(GetType(String));
3688 }
3689
3690 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3691 QualType FileType = GetType(File);
3692 if (FileType.isNull()) {
3693 Error("FILE type is NULL");
3694 return;
3695 }
3696
3697 if (!Context.FILEDecl) {
3698 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3699 Context.setFILEDecl(Typedef->getDecl());
3700 else {
3701 const TagType *Tag = FileType->getAs<TagType>();
3702 if (!Tag) {
3703 Error("Invalid FILE type in AST file");
3704 return;
3705 }
3706 Context.setFILEDecl(Tag->getDecl());
3707 }
3708 }
3709 }
3710
3711 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3712 QualType Jmp_bufType = GetType(Jmp_buf);
3713 if (Jmp_bufType.isNull()) {
3714 Error("jmp_buf type is NULL");
3715 return;
3716 }
3717
3718 if (!Context.jmp_bufDecl) {
3719 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3720 Context.setjmp_bufDecl(Typedef->getDecl());
3721 else {
3722 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3723 if (!Tag) {
3724 Error("Invalid jmp_buf type in AST file");
3725 return;
3726 }
3727 Context.setjmp_bufDecl(Tag->getDecl());
3728 }
3729 }
3730 }
3731
3732 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3733 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3734 if (Sigjmp_bufType.isNull()) {
3735 Error("sigjmp_buf type is NULL");
3736 return;
3737 }
3738
3739 if (!Context.sigjmp_bufDecl) {
3740 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3741 Context.setsigjmp_bufDecl(Typedef->getDecl());
3742 else {
3743 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3744 assert(Tag && "Invalid sigjmp_buf type in AST file");
3745 Context.setsigjmp_bufDecl(Tag->getDecl());
3746 }
3747 }
3748 }
3749
3750 if (unsigned ObjCIdRedef
3751 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3752 if (Context.ObjCIdRedefinitionType.isNull())
3753 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3754 }
3755
3756 if (unsigned ObjCClassRedef
3757 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3758 if (Context.ObjCClassRedefinitionType.isNull())
3759 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3760 }
3761
3762 if (unsigned ObjCSelRedef
3763 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3764 if (Context.ObjCSelRedefinitionType.isNull())
3765 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3766 }
3767
3768 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3769 QualType Ucontext_tType = GetType(Ucontext_t);
3770 if (Ucontext_tType.isNull()) {
3771 Error("ucontext_t type is NULL");
3772 return;
3773 }
3774
3775 if (!Context.ucontext_tDecl) {
3776 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3777 Context.setucontext_tDecl(Typedef->getDecl());
3778 else {
3779 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3780 assert(Tag && "Invalid ucontext_t type in AST file");
3781 Context.setucontext_tDecl(Tag->getDecl());
3782 }
3783 }
3784 }
3785 }
3786
3787 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3788
3789 // If there were any CUDA special declarations, deserialize them.
3790 if (!CUDASpecialDeclRefs.empty()) {
3791 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3792 Context.setcudaConfigureCallDecl(
3793 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3794 }
Richard Smith56be7542014-03-21 00:33:59 +00003795
Guy Benyei11169dd2012-12-18 14:30:41 +00003796 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00003797 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00003798 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00003799 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003800 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003801 /*ImportLoc=*/Import.ImportLoc);
3802 PP.makeModuleVisible(Imported, Import.ImportLoc);
3803 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003804 }
3805 ImportedModules.clear();
3806}
3807
3808void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00003809 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00003810}
3811
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003812/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3813/// cursor into the start of the given block ID, returning false on success and
3814/// true on failure.
3815static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003816 while (1) {
3817 llvm::BitstreamEntry Entry = Cursor.advance();
3818 switch (Entry.Kind) {
3819 case llvm::BitstreamEntry::Error:
3820 case llvm::BitstreamEntry::EndBlock:
3821 return true;
3822
3823 case llvm::BitstreamEntry::Record:
3824 // Ignore top-level records.
3825 Cursor.skipRecord(Entry.ID);
3826 break;
3827
3828 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003829 if (Entry.ID == BlockID) {
3830 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003831 return true;
3832 // Found it!
3833 return false;
3834 }
3835
3836 if (Cursor.SkipBlock())
3837 return true;
3838 }
3839 }
3840}
3841
Ben Langmuir70a1b812015-03-24 04:43:52 +00003842/// \brief Reads and return the signature record from \p StreamFile's control
3843/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00003844static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
3845 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00003846 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00003847 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00003848
3849 // Scan for the CONTROL_BLOCK_ID block.
3850 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
3851 return 0;
3852
3853 // Scan for SIGNATURE inside the control block.
3854 ASTReader::RecordData Record;
3855 while (1) {
3856 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3857 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
3858 Entry.Kind != llvm::BitstreamEntry::Record)
3859 return 0;
3860
3861 Record.clear();
3862 StringRef Blob;
3863 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
3864 return Record[0];
3865 }
3866}
3867
Guy Benyei11169dd2012-12-18 14:30:41 +00003868/// \brief Retrieve the name of the original source file name
3869/// directly from the AST file, without actually loading the AST
3870/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003871std::string ASTReader::getOriginalSourceFile(
3872 const std::string &ASTFileName, FileManager &FileMgr,
3873 const PCHContainerOperations &PCHContainerOps, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003874 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00003875 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00003876 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00003877 Diags.Report(diag::err_fe_unable_to_read_pch_file)
3878 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00003879 return std::string();
3880 }
3881
3882 // Initialize the stream
3883 llvm::BitstreamReader StreamFile;
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003884 PCHContainerOps.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00003885 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003886
3887 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003888 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003889 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3890 return std::string();
3891 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003892
Chris Lattnere7b154b2013-01-19 21:39:22 +00003893 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003894 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003895 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3896 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003897 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003898
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003899 // Scan for ORIGINAL_FILE inside the control block.
3900 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003901 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003902 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003903 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3904 return std::string();
3905
3906 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3907 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3908 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003909 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003910
Guy Benyei11169dd2012-12-18 14:30:41 +00003911 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003912 StringRef Blob;
3913 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3914 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003915 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003916}
3917
3918namespace {
3919 class SimplePCHValidator : public ASTReaderListener {
3920 const LangOptions &ExistingLangOpts;
3921 const TargetOptions &ExistingTargetOpts;
3922 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003923 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00003924 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003925
Guy Benyei11169dd2012-12-18 14:30:41 +00003926 public:
3927 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3928 const TargetOptions &ExistingTargetOpts,
3929 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003930 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00003931 FileManager &FileMgr)
3932 : ExistingLangOpts(ExistingLangOpts),
3933 ExistingTargetOpts(ExistingTargetOpts),
3934 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003935 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00003936 FileMgr(FileMgr)
3937 {
3938 }
3939
Richard Smith1e2cf0d2014-10-31 02:28:58 +00003940 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
3941 bool AllowCompatibleDifferences) override {
3942 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
3943 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00003944 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00003945 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
3946 bool AllowCompatibleDifferences) override {
3947 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
3948 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00003949 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003950 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
3951 StringRef SpecificModuleCachePath,
3952 bool Complain) override {
3953 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
3954 ExistingModuleCachePath,
3955 nullptr, ExistingLangOpts);
3956 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003957 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3958 bool Complain,
3959 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00003960 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00003961 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00003962 }
3963 };
3964}
3965
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003966bool ASTReader::readASTFileControlBlock(
3967 StringRef Filename, FileManager &FileMgr,
3968 const PCHContainerOperations &PCHContainerOps,
3969 ASTReaderListener &Listener) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003970 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00003971 // FIXME: This allows use of the VFS; we do not allow use of the
3972 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00003973 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00003974 if (!Buffer) {
3975 return true;
3976 }
3977
3978 // Initialize the stream
3979 llvm::BitstreamReader StreamFile;
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003980 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
3981 (const unsigned char *)(*Buffer)->getBufferEnd());
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00003982 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003983
3984 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003985 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00003986 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003987
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003988 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003989 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003990 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003991
3992 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00003993 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00003994 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003995 BitstreamCursor InputFilesCursor;
3996 if (NeedsInputFiles) {
3997 InputFilesCursor = Stream;
3998 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
3999 return true;
4000
4001 // Read the abbreviations
4002 while (true) {
4003 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4004 unsigned Code = InputFilesCursor.ReadCode();
4005
4006 // We expect all abbrevs to be at the start of the block.
4007 if (Code != llvm::bitc::DEFINE_ABBREV) {
4008 InputFilesCursor.JumpToBit(Offset);
4009 break;
4010 }
4011 InputFilesCursor.ReadAbbrevRecord();
4012 }
4013 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004014
4015 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004016 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004017 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004018 while (1) {
4019 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4020 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4021 return false;
4022
4023 if (Entry.Kind != llvm::BitstreamEntry::Record)
4024 return true;
4025
Guy Benyei11169dd2012-12-18 14:30:41 +00004026 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004027 StringRef Blob;
4028 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004029 switch ((ControlRecordTypes)RecCode) {
4030 case METADATA: {
4031 if (Record[0] != VERSION_MAJOR)
4032 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004033
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004034 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004035 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004036
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004037 break;
4038 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004039 case MODULE_NAME:
4040 Listener.ReadModuleName(Blob);
4041 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004042 case MODULE_DIRECTORY:
4043 ModuleDir = Blob;
4044 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004045 case MODULE_MAP_FILE: {
4046 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004047 auto Path = ReadString(Record, Idx);
4048 ResolveImportedPath(Path, ModuleDir);
4049 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004050 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004051 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004052 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004053 if (ParseLanguageOptions(Record, false, Listener,
4054 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004055 return true;
4056 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004057
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004058 case TARGET_OPTIONS:
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004059 if (ParseTargetOptions(Record, false, Listener,
4060 /*AllowCompatibleConfigurationMismatch*/ false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004061 return true;
4062 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004063
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004064 case DIAGNOSTIC_OPTIONS:
4065 if (ParseDiagnosticOptions(Record, false, Listener))
4066 return true;
4067 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004068
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004069 case FILE_SYSTEM_OPTIONS:
4070 if (ParseFileSystemOptions(Record, false, Listener))
4071 return true;
4072 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004073
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004074 case HEADER_SEARCH_OPTIONS:
4075 if (ParseHeaderSearchOptions(Record, false, Listener))
4076 return true;
4077 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004078
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004079 case PREPROCESSOR_OPTIONS: {
4080 std::string IgnoredSuggestedPredefines;
4081 if (ParsePreprocessorOptions(Record, false, Listener,
4082 IgnoredSuggestedPredefines))
4083 return true;
4084 break;
4085 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004086
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004087 case INPUT_FILE_OFFSETS: {
4088 if (!NeedsInputFiles)
4089 break;
4090
4091 unsigned NumInputFiles = Record[0];
4092 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004093 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004094 for (unsigned I = 0; I != NumInputFiles; ++I) {
4095 // Go find this input file.
4096 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004097
4098 if (isSystemFile && !NeedsSystemInputFiles)
4099 break; // the rest are system input files
4100
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004101 BitstreamCursor &Cursor = InputFilesCursor;
4102 SavedStreamPosition SavedPosition(Cursor);
4103 Cursor.JumpToBit(InputFileOffs[I]);
4104
4105 unsigned Code = Cursor.ReadCode();
4106 RecordData Record;
4107 StringRef Blob;
4108 bool shouldContinue = false;
4109 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4110 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004111 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004112 std::string Filename = Blob;
4113 ResolveImportedPath(Filename, ModuleDir);
4114 shouldContinue =
4115 Listener.visitInputFile(Filename, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004116 break;
4117 }
4118 if (!shouldContinue)
4119 break;
4120 }
4121 break;
4122 }
4123
Richard Smithd4b230b2014-10-27 23:01:16 +00004124 case IMPORTS: {
4125 if (!NeedsImports)
4126 break;
4127
4128 unsigned Idx = 0, N = Record.size();
4129 while (Idx < N) {
4130 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004131 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004132 std::string Filename = ReadString(Record, Idx);
4133 ResolveImportedPath(Filename, ModuleDir);
4134 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004135 }
4136 break;
4137 }
4138
Richard Smith7f330cd2015-03-18 01:42:29 +00004139 case KNOWN_MODULE_FILES: {
4140 // Known-but-not-technically-used module files are treated as imports.
4141 if (!NeedsImports)
4142 break;
4143
4144 unsigned Idx = 0, N = Record.size();
4145 while (Idx < N) {
4146 std::string Filename = ReadString(Record, Idx);
4147 ResolveImportedPath(Filename, ModuleDir);
4148 Listener.visitImport(Filename);
4149 }
4150 break;
4151 }
4152
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004153 default:
4154 // No other validation to perform.
4155 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004156 }
4157 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004158}
4159
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004160bool ASTReader::isAcceptableASTFile(
4161 StringRef Filename, FileManager &FileMgr,
4162 const PCHContainerOperations &PCHContainerOps, const LangOptions &LangOpts,
4163 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4164 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004165 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4166 ExistingModuleCachePath, FileMgr);
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004167 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerOps,
4168 validator);
Guy Benyei11169dd2012-12-18 14:30:41 +00004169}
4170
Ben Langmuir2c9af442014-04-10 17:57:43 +00004171ASTReader::ASTReadResult
4172ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004173 // Enter the submodule block.
4174 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4175 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004176 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004177 }
4178
4179 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4180 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004181 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004182 RecordData Record;
4183 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004184 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4185
4186 switch (Entry.Kind) {
4187 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4188 case llvm::BitstreamEntry::Error:
4189 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004190 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004191 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004192 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004193 case llvm::BitstreamEntry::Record:
4194 // The interesting case.
4195 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004196 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004197
Guy Benyei11169dd2012-12-18 14:30:41 +00004198 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004199 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004200 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004201 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4202
4203 if ((Kind == SUBMODULE_METADATA) != First) {
4204 Error("submodule metadata record should be at beginning of block");
4205 return Failure;
4206 }
4207 First = false;
4208
4209 // Submodule information is only valid if we have a current module.
4210 // FIXME: Should we error on these cases?
4211 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4212 Kind != SUBMODULE_DEFINITION)
4213 continue;
4214
4215 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004216 default: // Default behavior: ignore.
4217 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004218
Richard Smith03478d92014-10-23 22:12:14 +00004219 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004220 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004221 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004222 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004223 }
Richard Smith03478d92014-10-23 22:12:14 +00004224
Chris Lattner0e6c9402013-01-20 02:38:54 +00004225 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004226 unsigned Idx = 0;
4227 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4228 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4229 bool IsFramework = Record[Idx++];
4230 bool IsExplicit = Record[Idx++];
4231 bool IsSystem = Record[Idx++];
4232 bool IsExternC = Record[Idx++];
4233 bool InferSubmodules = Record[Idx++];
4234 bool InferExplicitSubmodules = Record[Idx++];
4235 bool InferExportWildcard = Record[Idx++];
4236 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004237
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004238 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004239 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004240 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004241
Guy Benyei11169dd2012-12-18 14:30:41 +00004242 // Retrieve this (sub)module from the module map, creating it if
4243 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004244 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004245 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004246
4247 // FIXME: set the definition loc for CurrentModule, or call
4248 // ModMap.setInferredModuleAllowedBy()
4249
Guy Benyei11169dd2012-12-18 14:30:41 +00004250 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4251 if (GlobalIndex >= SubmodulesLoaded.size() ||
4252 SubmodulesLoaded[GlobalIndex]) {
4253 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004254 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004255 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004256
Douglas Gregor7029ce12013-03-19 00:28:20 +00004257 if (!ParentModule) {
4258 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4259 if (CurFile != F.File) {
4260 if (!Diags.isDiagnosticInFlight()) {
4261 Diag(diag::err_module_file_conflict)
4262 << CurrentModule->getTopLevelModuleName()
4263 << CurFile->getName()
4264 << F.File->getName();
4265 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004266 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004267 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004268 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004269
4270 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004271 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004272
Guy Benyei11169dd2012-12-18 14:30:41 +00004273 CurrentModule->IsFromModuleFile = true;
4274 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004275 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004276 CurrentModule->InferSubmodules = InferSubmodules;
4277 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4278 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004279 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004280 if (DeserializationListener)
4281 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4282
4283 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004284
Douglas Gregorfb912652013-03-20 21:10:35 +00004285 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004286 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004287 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004288 CurrentModule->UnresolvedConflicts.clear();
4289 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004290 break;
4291 }
4292
4293 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004294 std::string Filename = Blob;
4295 ResolveImportedPath(F, Filename);
4296 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004297 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004298 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4299 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004300 // This can be a spurious difference caused by changing the VFS to
4301 // point to a different copy of the file, and it is too late to
4302 // to rebuild safely.
4303 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4304 // after input file validation only real problems would remain and we
4305 // could just error. For now, assume it's okay.
4306 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004307 }
4308 }
4309 break;
4310 }
4311
Richard Smith202210b2014-10-24 20:23:01 +00004312 case SUBMODULE_HEADER:
4313 case SUBMODULE_EXCLUDED_HEADER:
4314 case SUBMODULE_PRIVATE_HEADER:
4315 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004316 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4317 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004318 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004319
Richard Smith202210b2014-10-24 20:23:01 +00004320 case SUBMODULE_TEXTUAL_HEADER:
4321 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4322 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4323 // them here.
4324 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004325
Guy Benyei11169dd2012-12-18 14:30:41 +00004326 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004327 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004328 break;
4329 }
4330
4331 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004332 std::string Dirname = Blob;
4333 ResolveImportedPath(F, Dirname);
4334 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004335 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004336 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4337 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004338 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4339 Error("mismatched umbrella directories in submodule");
4340 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004341 }
4342 }
4343 break;
4344 }
4345
4346 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004347 F.BaseSubmoduleID = getTotalNumSubmodules();
4348 F.LocalNumSubmodules = Record[0];
4349 unsigned LocalBaseSubmoduleID = Record[1];
4350 if (F.LocalNumSubmodules > 0) {
4351 // Introduce the global -> local mapping for submodules within this
4352 // module.
4353 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4354
4355 // Introduce the local -> global mapping for submodules within this
4356 // module.
4357 F.SubmoduleRemap.insertOrReplace(
4358 std::make_pair(LocalBaseSubmoduleID,
4359 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004360
Ben Langmuir52ca6782014-10-20 16:27:32 +00004361 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4362 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004363 break;
4364 }
4365
4366 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004367 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004368 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004369 Unresolved.File = &F;
4370 Unresolved.Mod = CurrentModule;
4371 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004372 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004373 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004374 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004375 }
4376 break;
4377 }
4378
4379 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004380 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004381 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004382 Unresolved.File = &F;
4383 Unresolved.Mod = CurrentModule;
4384 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004385 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004386 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004387 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004388 }
4389
4390 // Once we've loaded the set of exports, there's no reason to keep
4391 // the parsed, unresolved exports around.
4392 CurrentModule->UnresolvedExports.clear();
4393 break;
4394 }
4395 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004396 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004397 Context.getTargetInfo());
4398 break;
4399 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004400
4401 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004402 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004403 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004404 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004405
4406 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004407 CurrentModule->ConfigMacros.push_back(Blob.str());
4408 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004409
4410 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004411 UnresolvedModuleRef Unresolved;
4412 Unresolved.File = &F;
4413 Unresolved.Mod = CurrentModule;
4414 Unresolved.ID = Record[0];
4415 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4416 Unresolved.IsWildcard = false;
4417 Unresolved.String = Blob;
4418 UnresolvedModuleRefs.push_back(Unresolved);
4419 break;
4420 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004421 }
4422 }
4423}
4424
4425/// \brief Parse the record that corresponds to a LangOptions data
4426/// structure.
4427///
4428/// This routine parses the language options from the AST file and then gives
4429/// them to the AST listener if one is set.
4430///
4431/// \returns true if the listener deems the file unacceptable, false otherwise.
4432bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4433 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004434 ASTReaderListener &Listener,
4435 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004436 LangOptions LangOpts;
4437 unsigned Idx = 0;
4438#define LANGOPT(Name, Bits, Default, Description) \
4439 LangOpts.Name = Record[Idx++];
4440#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4441 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4442#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004443#define SANITIZER(NAME, ID) \
4444 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004445#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004446
4447 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4448 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4449 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4450
4451 unsigned Length = Record[Idx++];
4452 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4453 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004454
4455 Idx += Length;
4456
4457 // Comment options.
4458 for (unsigned N = Record[Idx++]; N; --N) {
4459 LangOpts.CommentOpts.BlockCommandNames.push_back(
4460 ReadString(Record, Idx));
4461 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004462 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004463
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004464 return Listener.ReadLanguageOptions(LangOpts, Complain,
4465 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004466}
4467
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004468bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4469 ASTReaderListener &Listener,
4470 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004471 unsigned Idx = 0;
4472 TargetOptions TargetOpts;
4473 TargetOpts.Triple = ReadString(Record, Idx);
4474 TargetOpts.CPU = ReadString(Record, Idx);
4475 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004476 for (unsigned N = Record[Idx++]; N; --N) {
4477 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4478 }
4479 for (unsigned N = Record[Idx++]; N; --N) {
4480 TargetOpts.Features.push_back(ReadString(Record, Idx));
4481 }
4482
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004483 return Listener.ReadTargetOptions(TargetOpts, Complain,
4484 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004485}
4486
4487bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4488 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004489 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004490 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004491#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004492#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004493 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004494#include "clang/Basic/DiagnosticOptions.def"
4495
Richard Smith3be1cb22014-08-07 00:24:21 +00004496 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004497 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004498 for (unsigned N = Record[Idx++]; N; --N)
4499 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004500
4501 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4502}
4503
4504bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4505 ASTReaderListener &Listener) {
4506 FileSystemOptions FSOpts;
4507 unsigned Idx = 0;
4508 FSOpts.WorkingDir = ReadString(Record, Idx);
4509 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4510}
4511
4512bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4513 bool Complain,
4514 ASTReaderListener &Listener) {
4515 HeaderSearchOptions HSOpts;
4516 unsigned Idx = 0;
4517 HSOpts.Sysroot = ReadString(Record, Idx);
4518
4519 // Include entries.
4520 for (unsigned N = Record[Idx++]; N; --N) {
4521 std::string Path = ReadString(Record, Idx);
4522 frontend::IncludeDirGroup Group
4523 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004524 bool IsFramework = Record[Idx++];
4525 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004526 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4527 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004528 }
4529
4530 // System header prefixes.
4531 for (unsigned N = Record[Idx++]; N; --N) {
4532 std::string Prefix = ReadString(Record, Idx);
4533 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004534 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004535 }
4536
4537 HSOpts.ResourceDir = ReadString(Record, Idx);
4538 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004539 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004540 HSOpts.DisableModuleHash = Record[Idx++];
4541 HSOpts.UseBuiltinIncludes = Record[Idx++];
4542 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4543 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4544 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004545 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004546
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004547 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4548 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004549}
4550
4551bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4552 bool Complain,
4553 ASTReaderListener &Listener,
4554 std::string &SuggestedPredefines) {
4555 PreprocessorOptions PPOpts;
4556 unsigned Idx = 0;
4557
4558 // Macro definitions/undefs
4559 for (unsigned N = Record[Idx++]; N; --N) {
4560 std::string Macro = ReadString(Record, Idx);
4561 bool IsUndef = Record[Idx++];
4562 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4563 }
4564
4565 // Includes
4566 for (unsigned N = Record[Idx++]; N; --N) {
4567 PPOpts.Includes.push_back(ReadString(Record, Idx));
4568 }
4569
4570 // Macro Includes
4571 for (unsigned N = Record[Idx++]; N; --N) {
4572 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4573 }
4574
4575 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004576 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004577 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4578 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4579 PPOpts.ObjCXXARCStandardLibrary =
4580 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4581 SuggestedPredefines.clear();
4582 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4583 SuggestedPredefines);
4584}
4585
4586std::pair<ModuleFile *, unsigned>
4587ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4588 GlobalPreprocessedEntityMapType::iterator
4589 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4590 assert(I != GlobalPreprocessedEntityMap.end() &&
4591 "Corrupted global preprocessed entity map");
4592 ModuleFile *M = I->second;
4593 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4594 return std::make_pair(M, LocalIndex);
4595}
4596
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004597llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004598ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4599 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4600 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4601 Mod.NumPreprocessedEntities);
4602
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004603 return llvm::make_range(PreprocessingRecord::iterator(),
4604 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004605}
4606
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004607llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004608ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004609 return llvm::make_range(
4610 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4611 ModuleDeclIterator(this, &Mod,
4612 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004613}
4614
4615PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4616 PreprocessedEntityID PPID = Index+1;
4617 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4618 ModuleFile &M = *PPInfo.first;
4619 unsigned LocalIndex = PPInfo.second;
4620 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4621
Guy Benyei11169dd2012-12-18 14:30:41 +00004622 if (!PP.getPreprocessingRecord()) {
4623 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004624 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004625 }
4626
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004627 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4628 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4629
4630 llvm::BitstreamEntry Entry =
4631 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4632 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004633 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004634
Guy Benyei11169dd2012-12-18 14:30:41 +00004635 // Read the record.
4636 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4637 ReadSourceLocation(M, PPOffs.End));
4638 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004639 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004640 RecordData Record;
4641 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004642 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4643 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004644 switch (RecType) {
4645 case PPD_MACRO_EXPANSION: {
4646 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004647 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004648 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004649 if (isBuiltin)
4650 Name = getLocalIdentifier(M, Record[1]);
4651 else {
Richard Smith66a81862015-05-04 02:25:31 +00004652 PreprocessedEntityID GlobalID =
4653 getGlobalPreprocessedEntityID(M, Record[1]);
4654 Def = cast<MacroDefinitionRecord>(
4655 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004656 }
4657
4658 MacroExpansion *ME;
4659 if (isBuiltin)
4660 ME = new (PPRec) MacroExpansion(Name, Range);
4661 else
4662 ME = new (PPRec) MacroExpansion(Def, Range);
4663
4664 return ME;
4665 }
4666
4667 case PPD_MACRO_DEFINITION: {
4668 // Decode the identifier info and then check again; if the macro is
4669 // still defined and associated with the identifier,
4670 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004671 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004672
4673 if (DeserializationListener)
4674 DeserializationListener->MacroDefinitionRead(PPID, MD);
4675
4676 return MD;
4677 }
4678
4679 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004680 const char *FullFileNameStart = Blob.data() + Record[0];
4681 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004682 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004683 if (!FullFileName.empty())
4684 File = PP.getFileManager().getFile(FullFileName);
4685
4686 // FIXME: Stable encoding
4687 InclusionDirective::InclusionKind Kind
4688 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4689 InclusionDirective *ID
4690 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004691 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004692 Record[1], Record[3],
4693 File,
4694 Range);
4695 return ID;
4696 }
4697 }
4698
4699 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4700}
4701
4702/// \brief \arg SLocMapI points at a chunk of a module that contains no
4703/// preprocessed entities or the entities it contains are not the ones we are
4704/// looking for. Find the next module that contains entities and return the ID
4705/// of the first entry.
4706PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4707 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4708 ++SLocMapI;
4709 for (GlobalSLocOffsetMapType::const_iterator
4710 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4711 ModuleFile &M = *SLocMapI->second;
4712 if (M.NumPreprocessedEntities)
4713 return M.BasePreprocessedEntityID;
4714 }
4715
4716 return getTotalNumPreprocessedEntities();
4717}
4718
4719namespace {
4720
4721template <unsigned PPEntityOffset::*PPLoc>
4722struct PPEntityComp {
4723 const ASTReader &Reader;
4724 ModuleFile &M;
4725
4726 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4727
4728 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4729 SourceLocation LHS = getLoc(L);
4730 SourceLocation RHS = getLoc(R);
4731 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4732 }
4733
4734 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4735 SourceLocation LHS = getLoc(L);
4736 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4737 }
4738
4739 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4740 SourceLocation RHS = getLoc(R);
4741 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4742 }
4743
4744 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4745 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4746 }
4747};
4748
4749}
4750
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004751PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4752 bool EndsAfter) const {
4753 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004754 return getTotalNumPreprocessedEntities();
4755
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004756 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4757 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004758 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4759 "Corrupted global sloc offset map");
4760
4761 if (SLocMapI->second->NumPreprocessedEntities == 0)
4762 return findNextPreprocessedEntity(SLocMapI);
4763
4764 ModuleFile &M = *SLocMapI->second;
4765 typedef const PPEntityOffset *pp_iterator;
4766 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4767 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4768
4769 size_t Count = M.NumPreprocessedEntities;
4770 size_t Half;
4771 pp_iterator First = pp_begin;
4772 pp_iterator PPI;
4773
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004774 if (EndsAfter) {
4775 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4776 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4777 } else {
4778 // Do a binary search manually instead of using std::lower_bound because
4779 // The end locations of entities may be unordered (when a macro expansion
4780 // is inside another macro argument), but for this case it is not important
4781 // whether we get the first macro expansion or its containing macro.
4782 while (Count > 0) {
4783 Half = Count / 2;
4784 PPI = First;
4785 std::advance(PPI, Half);
4786 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4787 Loc)) {
4788 First = PPI;
4789 ++First;
4790 Count = Count - Half - 1;
4791 } else
4792 Count = Half;
4793 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004794 }
4795
4796 if (PPI == pp_end)
4797 return findNextPreprocessedEntity(SLocMapI);
4798
4799 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4800}
4801
Guy Benyei11169dd2012-12-18 14:30:41 +00004802/// \brief Returns a pair of [Begin, End) indices of preallocated
4803/// preprocessed entities that \arg Range encompasses.
4804std::pair<unsigned, unsigned>
4805 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4806 if (Range.isInvalid())
4807 return std::make_pair(0,0);
4808 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4809
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004810 PreprocessedEntityID BeginID =
4811 findPreprocessedEntity(Range.getBegin(), false);
4812 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004813 return std::make_pair(BeginID, EndID);
4814}
4815
4816/// \brief Optionally returns true or false if the preallocated preprocessed
4817/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004818Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004819 FileID FID) {
4820 if (FID.isInvalid())
4821 return false;
4822
4823 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4824 ModuleFile &M = *PPInfo.first;
4825 unsigned LocalIndex = PPInfo.second;
4826 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4827
4828 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4829 if (Loc.isInvalid())
4830 return false;
4831
4832 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4833 return true;
4834 else
4835 return false;
4836}
4837
4838namespace {
4839 /// \brief Visitor used to search for information about a header file.
4840 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004841 const FileEntry *FE;
4842
David Blaikie05785d12013-02-20 22:23:23 +00004843 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004844
4845 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004846 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4847 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004848
4849 static bool visit(ModuleFile &M, void *UserData) {
4850 HeaderFileInfoVisitor *This
4851 = static_cast<HeaderFileInfoVisitor *>(UserData);
4852
Guy Benyei11169dd2012-12-18 14:30:41 +00004853 HeaderFileInfoLookupTable *Table
4854 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4855 if (!Table)
4856 return false;
4857
4858 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00004859 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004860 if (Pos == Table->end())
4861 return false;
4862
4863 This->HFI = *Pos;
4864 return true;
4865 }
4866
David Blaikie05785d12013-02-20 22:23:23 +00004867 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004868 };
4869}
4870
4871HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004872 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004873 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004874 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004875 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004876
4877 return HeaderFileInfo();
4878}
4879
4880void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4881 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004882 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004883 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4884 ModuleFile &F = *(*I);
4885 unsigned Idx = 0;
4886 DiagStates.clear();
4887 assert(!Diag.DiagStates.empty());
4888 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4889 while (Idx < F.PragmaDiagMappings.size()) {
4890 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4891 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4892 if (DiagStateID != 0) {
4893 Diag.DiagStatePoints.push_back(
4894 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4895 FullSourceLoc(Loc, SourceMgr)));
4896 continue;
4897 }
4898
4899 assert(DiagStateID == 0);
4900 // A new DiagState was created here.
4901 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4902 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4903 DiagStates.push_back(NewState);
4904 Diag.DiagStatePoints.push_back(
4905 DiagnosticsEngine::DiagStatePoint(NewState,
4906 FullSourceLoc(Loc, SourceMgr)));
4907 while (1) {
4908 assert(Idx < F.PragmaDiagMappings.size() &&
4909 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4910 if (Idx >= F.PragmaDiagMappings.size()) {
4911 break; // Something is messed up but at least avoid infinite loop in
4912 // release build.
4913 }
4914 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4915 if (DiagID == (unsigned)-1) {
4916 break; // no more diag/map pairs for this location.
4917 }
Alp Tokerc726c362014-06-10 09:31:37 +00004918 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
4919 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
4920 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00004921 }
4922 }
4923 }
4924}
4925
4926/// \brief Get the correct cursor and offset for loading a type.
4927ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4928 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4929 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4930 ModuleFile *M = I->second;
4931 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4932}
4933
4934/// \brief Read and return the type with the given index..
4935///
4936/// The index is the type ID, shifted and minus the number of predefs. This
4937/// routine actually reads the record corresponding to the type at the given
4938/// location. It is a helper routine for GetType, which deals with reading type
4939/// IDs.
4940QualType ASTReader::readTypeRecord(unsigned Index) {
4941 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004942 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00004943
4944 // Keep track of where we are in the stream, then jump back there
4945 // after reading this type.
4946 SavedStreamPosition SavedPosition(DeclsCursor);
4947
4948 ReadingKindTracker ReadingKind(Read_Type, *this);
4949
4950 // Note that we are loading a type record.
4951 Deserializing AType(this);
4952
4953 unsigned Idx = 0;
4954 DeclsCursor.JumpToBit(Loc.Offset);
4955 RecordData Record;
4956 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004957 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004958 case TYPE_EXT_QUAL: {
4959 if (Record.size() != 2) {
4960 Error("Incorrect encoding of extended qualifier type");
4961 return QualType();
4962 }
4963 QualType Base = readType(*Loc.F, Record, Idx);
4964 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4965 return Context.getQualifiedType(Base, Quals);
4966 }
4967
4968 case TYPE_COMPLEX: {
4969 if (Record.size() != 1) {
4970 Error("Incorrect encoding of complex type");
4971 return QualType();
4972 }
4973 QualType ElemType = readType(*Loc.F, Record, Idx);
4974 return Context.getComplexType(ElemType);
4975 }
4976
4977 case TYPE_POINTER: {
4978 if (Record.size() != 1) {
4979 Error("Incorrect encoding of pointer type");
4980 return QualType();
4981 }
4982 QualType PointeeType = readType(*Loc.F, Record, Idx);
4983 return Context.getPointerType(PointeeType);
4984 }
4985
Reid Kleckner8a365022013-06-24 17:51:48 +00004986 case TYPE_DECAYED: {
4987 if (Record.size() != 1) {
4988 Error("Incorrect encoding of decayed type");
4989 return QualType();
4990 }
4991 QualType OriginalType = readType(*Loc.F, Record, Idx);
4992 QualType DT = Context.getAdjustedParameterType(OriginalType);
4993 if (!isa<DecayedType>(DT))
4994 Error("Decayed type does not decay");
4995 return DT;
4996 }
4997
Reid Kleckner0503a872013-12-05 01:23:43 +00004998 case TYPE_ADJUSTED: {
4999 if (Record.size() != 2) {
5000 Error("Incorrect encoding of adjusted type");
5001 return QualType();
5002 }
5003 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5004 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5005 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5006 }
5007
Guy Benyei11169dd2012-12-18 14:30:41 +00005008 case TYPE_BLOCK_POINTER: {
5009 if (Record.size() != 1) {
5010 Error("Incorrect encoding of block pointer type");
5011 return QualType();
5012 }
5013 QualType PointeeType = readType(*Loc.F, Record, Idx);
5014 return Context.getBlockPointerType(PointeeType);
5015 }
5016
5017 case TYPE_LVALUE_REFERENCE: {
5018 if (Record.size() != 2) {
5019 Error("Incorrect encoding of lvalue reference type");
5020 return QualType();
5021 }
5022 QualType PointeeType = readType(*Loc.F, Record, Idx);
5023 return Context.getLValueReferenceType(PointeeType, Record[1]);
5024 }
5025
5026 case TYPE_RVALUE_REFERENCE: {
5027 if (Record.size() != 1) {
5028 Error("Incorrect encoding of rvalue reference type");
5029 return QualType();
5030 }
5031 QualType PointeeType = readType(*Loc.F, Record, Idx);
5032 return Context.getRValueReferenceType(PointeeType);
5033 }
5034
5035 case TYPE_MEMBER_POINTER: {
5036 if (Record.size() != 2) {
5037 Error("Incorrect encoding of member pointer type");
5038 return QualType();
5039 }
5040 QualType PointeeType = readType(*Loc.F, Record, Idx);
5041 QualType ClassType = readType(*Loc.F, Record, Idx);
5042 if (PointeeType.isNull() || ClassType.isNull())
5043 return QualType();
5044
5045 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5046 }
5047
5048 case TYPE_CONSTANT_ARRAY: {
5049 QualType ElementType = readType(*Loc.F, Record, Idx);
5050 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5051 unsigned IndexTypeQuals = Record[2];
5052 unsigned Idx = 3;
5053 llvm::APInt Size = ReadAPInt(Record, Idx);
5054 return Context.getConstantArrayType(ElementType, Size,
5055 ASM, IndexTypeQuals);
5056 }
5057
5058 case TYPE_INCOMPLETE_ARRAY: {
5059 QualType ElementType = readType(*Loc.F, Record, Idx);
5060 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5061 unsigned IndexTypeQuals = Record[2];
5062 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5063 }
5064
5065 case TYPE_VARIABLE_ARRAY: {
5066 QualType ElementType = readType(*Loc.F, Record, Idx);
5067 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5068 unsigned IndexTypeQuals = Record[2];
5069 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5070 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5071 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5072 ASM, IndexTypeQuals,
5073 SourceRange(LBLoc, RBLoc));
5074 }
5075
5076 case TYPE_VECTOR: {
5077 if (Record.size() != 3) {
5078 Error("incorrect encoding of vector type in AST file");
5079 return QualType();
5080 }
5081
5082 QualType ElementType = readType(*Loc.F, Record, Idx);
5083 unsigned NumElements = Record[1];
5084 unsigned VecKind = Record[2];
5085 return Context.getVectorType(ElementType, NumElements,
5086 (VectorType::VectorKind)VecKind);
5087 }
5088
5089 case TYPE_EXT_VECTOR: {
5090 if (Record.size() != 3) {
5091 Error("incorrect encoding of extended vector type in AST file");
5092 return QualType();
5093 }
5094
5095 QualType ElementType = readType(*Loc.F, Record, Idx);
5096 unsigned NumElements = Record[1];
5097 return Context.getExtVectorType(ElementType, NumElements);
5098 }
5099
5100 case TYPE_FUNCTION_NO_PROTO: {
5101 if (Record.size() != 6) {
5102 Error("incorrect encoding of no-proto function type");
5103 return QualType();
5104 }
5105 QualType ResultType = readType(*Loc.F, Record, Idx);
5106 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5107 (CallingConv)Record[4], Record[5]);
5108 return Context.getFunctionNoProtoType(ResultType, Info);
5109 }
5110
5111 case TYPE_FUNCTION_PROTO: {
5112 QualType ResultType = readType(*Loc.F, Record, Idx);
5113
5114 FunctionProtoType::ExtProtoInfo EPI;
5115 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5116 /*hasregparm*/ Record[2],
5117 /*regparm*/ Record[3],
5118 static_cast<CallingConv>(Record[4]),
5119 /*produces*/ Record[5]);
5120
5121 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005122
5123 EPI.Variadic = Record[Idx++];
5124 EPI.HasTrailingReturn = Record[Idx++];
5125 EPI.TypeQuals = Record[Idx++];
5126 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005127 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005128 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005129
5130 unsigned NumParams = Record[Idx++];
5131 SmallVector<QualType, 16> ParamTypes;
5132 for (unsigned I = 0; I != NumParams; ++I)
5133 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5134
Jordan Rose5c382722013-03-08 21:51:21 +00005135 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005136 }
5137
5138 case TYPE_UNRESOLVED_USING: {
5139 unsigned Idx = 0;
5140 return Context.getTypeDeclType(
5141 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5142 }
5143
5144 case TYPE_TYPEDEF: {
5145 if (Record.size() != 2) {
5146 Error("incorrect encoding of typedef type");
5147 return QualType();
5148 }
5149 unsigned Idx = 0;
5150 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5151 QualType Canonical = readType(*Loc.F, Record, Idx);
5152 if (!Canonical.isNull())
5153 Canonical = Context.getCanonicalType(Canonical);
5154 return Context.getTypedefType(Decl, Canonical);
5155 }
5156
5157 case TYPE_TYPEOF_EXPR:
5158 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5159
5160 case TYPE_TYPEOF: {
5161 if (Record.size() != 1) {
5162 Error("incorrect encoding of typeof(type) in AST file");
5163 return QualType();
5164 }
5165 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5166 return Context.getTypeOfType(UnderlyingType);
5167 }
5168
5169 case TYPE_DECLTYPE: {
5170 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5171 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5172 }
5173
5174 case TYPE_UNARY_TRANSFORM: {
5175 QualType BaseType = readType(*Loc.F, Record, Idx);
5176 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5177 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5178 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5179 }
5180
Richard Smith74aeef52013-04-26 16:15:35 +00005181 case TYPE_AUTO: {
5182 QualType Deduced = readType(*Loc.F, Record, Idx);
5183 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005184 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005185 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005186 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005187
5188 case TYPE_RECORD: {
5189 if (Record.size() != 2) {
5190 Error("incorrect encoding of record type");
5191 return QualType();
5192 }
5193 unsigned Idx = 0;
5194 bool IsDependent = Record[Idx++];
5195 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5196 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5197 QualType T = Context.getRecordType(RD);
5198 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5199 return T;
5200 }
5201
5202 case TYPE_ENUM: {
5203 if (Record.size() != 2) {
5204 Error("incorrect encoding of enum type");
5205 return QualType();
5206 }
5207 unsigned Idx = 0;
5208 bool IsDependent = Record[Idx++];
5209 QualType T
5210 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5211 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5212 return T;
5213 }
5214
5215 case TYPE_ATTRIBUTED: {
5216 if (Record.size() != 3) {
5217 Error("incorrect encoding of attributed type");
5218 return QualType();
5219 }
5220 QualType modifiedType = readType(*Loc.F, Record, Idx);
5221 QualType equivalentType = readType(*Loc.F, Record, Idx);
5222 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5223 return Context.getAttributedType(kind, modifiedType, equivalentType);
5224 }
5225
5226 case TYPE_PAREN: {
5227 if (Record.size() != 1) {
5228 Error("incorrect encoding of paren type");
5229 return QualType();
5230 }
5231 QualType InnerType = readType(*Loc.F, Record, Idx);
5232 return Context.getParenType(InnerType);
5233 }
5234
5235 case TYPE_PACK_EXPANSION: {
5236 if (Record.size() != 2) {
5237 Error("incorrect encoding of pack expansion type");
5238 return QualType();
5239 }
5240 QualType Pattern = readType(*Loc.F, Record, Idx);
5241 if (Pattern.isNull())
5242 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005243 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005244 if (Record[1])
5245 NumExpansions = Record[1] - 1;
5246 return Context.getPackExpansionType(Pattern, NumExpansions);
5247 }
5248
5249 case TYPE_ELABORATED: {
5250 unsigned Idx = 0;
5251 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5252 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5253 QualType NamedType = readType(*Loc.F, Record, Idx);
5254 return Context.getElaboratedType(Keyword, NNS, NamedType);
5255 }
5256
5257 case TYPE_OBJC_INTERFACE: {
5258 unsigned Idx = 0;
5259 ObjCInterfaceDecl *ItfD
5260 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5261 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5262 }
5263
5264 case TYPE_OBJC_OBJECT: {
5265 unsigned Idx = 0;
5266 QualType Base = readType(*Loc.F, Record, Idx);
5267 unsigned NumProtos = Record[Idx++];
5268 SmallVector<ObjCProtocolDecl*, 4> Protos;
5269 for (unsigned I = 0; I != NumProtos; ++I)
5270 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5271 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5272 }
5273
5274 case TYPE_OBJC_OBJECT_POINTER: {
5275 unsigned Idx = 0;
5276 QualType Pointee = readType(*Loc.F, Record, Idx);
5277 return Context.getObjCObjectPointerType(Pointee);
5278 }
5279
5280 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5281 unsigned Idx = 0;
5282 QualType Parm = readType(*Loc.F, Record, Idx);
5283 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005284 return Context.getSubstTemplateTypeParmType(
5285 cast<TemplateTypeParmType>(Parm),
5286 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005287 }
5288
5289 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5290 unsigned Idx = 0;
5291 QualType Parm = readType(*Loc.F, Record, Idx);
5292 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5293 return Context.getSubstTemplateTypeParmPackType(
5294 cast<TemplateTypeParmType>(Parm),
5295 ArgPack);
5296 }
5297
5298 case TYPE_INJECTED_CLASS_NAME: {
5299 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5300 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5301 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5302 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005303 const Type *T = nullptr;
5304 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5305 if (const Type *Existing = DI->getTypeForDecl()) {
5306 T = Existing;
5307 break;
5308 }
5309 }
5310 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005311 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005312 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5313 DI->setTypeForDecl(T);
5314 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005315 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005316 }
5317
5318 case TYPE_TEMPLATE_TYPE_PARM: {
5319 unsigned Idx = 0;
5320 unsigned Depth = Record[Idx++];
5321 unsigned Index = Record[Idx++];
5322 bool Pack = Record[Idx++];
5323 TemplateTypeParmDecl *D
5324 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5325 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5326 }
5327
5328 case TYPE_DEPENDENT_NAME: {
5329 unsigned Idx = 0;
5330 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5331 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5332 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5333 QualType Canon = readType(*Loc.F, Record, Idx);
5334 if (!Canon.isNull())
5335 Canon = Context.getCanonicalType(Canon);
5336 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5337 }
5338
5339 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5340 unsigned Idx = 0;
5341 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5342 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5343 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5344 unsigned NumArgs = Record[Idx++];
5345 SmallVector<TemplateArgument, 8> Args;
5346 Args.reserve(NumArgs);
5347 while (NumArgs--)
5348 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5349 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5350 Args.size(), Args.data());
5351 }
5352
5353 case TYPE_DEPENDENT_SIZED_ARRAY: {
5354 unsigned Idx = 0;
5355
5356 // ArrayType
5357 QualType ElementType = readType(*Loc.F, Record, Idx);
5358 ArrayType::ArraySizeModifier ASM
5359 = (ArrayType::ArraySizeModifier)Record[Idx++];
5360 unsigned IndexTypeQuals = Record[Idx++];
5361
5362 // DependentSizedArrayType
5363 Expr *NumElts = ReadExpr(*Loc.F);
5364 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5365
5366 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5367 IndexTypeQuals, Brackets);
5368 }
5369
5370 case TYPE_TEMPLATE_SPECIALIZATION: {
5371 unsigned Idx = 0;
5372 bool IsDependent = Record[Idx++];
5373 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5374 SmallVector<TemplateArgument, 8> Args;
5375 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5376 QualType Underlying = readType(*Loc.F, Record, Idx);
5377 QualType T;
5378 if (Underlying.isNull())
5379 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5380 Args.size());
5381 else
5382 T = Context.getTemplateSpecializationType(Name, Args.data(),
5383 Args.size(), Underlying);
5384 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5385 return T;
5386 }
5387
5388 case TYPE_ATOMIC: {
5389 if (Record.size() != 1) {
5390 Error("Incorrect encoding of atomic type");
5391 return QualType();
5392 }
5393 QualType ValueType = readType(*Loc.F, Record, Idx);
5394 return Context.getAtomicType(ValueType);
5395 }
5396 }
5397 llvm_unreachable("Invalid TypeCode!");
5398}
5399
Richard Smith564417a2014-03-20 21:47:22 +00005400void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5401 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005402 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005403 const RecordData &Record, unsigned &Idx) {
5404 ExceptionSpecificationType EST =
5405 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005406 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005407 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005408 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005409 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005410 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005411 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005412 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005413 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005414 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5415 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005416 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005417 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005418 }
5419}
5420
Guy Benyei11169dd2012-12-18 14:30:41 +00005421class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5422 ASTReader &Reader;
5423 ModuleFile &F;
5424 const ASTReader::RecordData &Record;
5425 unsigned &Idx;
5426
5427 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5428 unsigned &I) {
5429 return Reader.ReadSourceLocation(F, R, I);
5430 }
5431
5432 template<typename T>
5433 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5434 return Reader.ReadDeclAs<T>(F, Record, Idx);
5435 }
5436
5437public:
5438 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5439 const ASTReader::RecordData &Record, unsigned &Idx)
5440 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5441 { }
5442
5443 // We want compile-time assurance that we've enumerated all of
5444 // these, so unfortunately we have to declare them first, then
5445 // define them out-of-line.
5446#define ABSTRACT_TYPELOC(CLASS, PARENT)
5447#define TYPELOC(CLASS, PARENT) \
5448 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5449#include "clang/AST/TypeLocNodes.def"
5450
5451 void VisitFunctionTypeLoc(FunctionTypeLoc);
5452 void VisitArrayTypeLoc(ArrayTypeLoc);
5453};
5454
5455void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5456 // nothing to do
5457}
5458void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5459 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5460 if (TL.needsExtraLocalData()) {
5461 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5462 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5463 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5464 TL.setModeAttr(Record[Idx++]);
5465 }
5466}
5467void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5468 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5469}
5470void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5471 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5472}
Reid Kleckner8a365022013-06-24 17:51:48 +00005473void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5474 // nothing to do
5475}
Reid Kleckner0503a872013-12-05 01:23:43 +00005476void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5477 // nothing to do
5478}
Guy Benyei11169dd2012-12-18 14:30:41 +00005479void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5480 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5481}
5482void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5483 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5484}
5485void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5486 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5487}
5488void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5489 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5490 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5491}
5492void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5493 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5494 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5495 if (Record[Idx++])
5496 TL.setSizeExpr(Reader.ReadExpr(F));
5497 else
Craig Toppera13603a2014-05-22 05:54:18 +00005498 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005499}
5500void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5501 VisitArrayTypeLoc(TL);
5502}
5503void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5504 VisitArrayTypeLoc(TL);
5505}
5506void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5507 VisitArrayTypeLoc(TL);
5508}
5509void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5510 DependentSizedArrayTypeLoc TL) {
5511 VisitArrayTypeLoc(TL);
5512}
5513void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5514 DependentSizedExtVectorTypeLoc TL) {
5515 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5516}
5517void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5518 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5519}
5520void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5521 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5522}
5523void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5524 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5525 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5526 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5527 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005528 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5529 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005530 }
5531}
5532void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5533 VisitFunctionTypeLoc(TL);
5534}
5535void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5536 VisitFunctionTypeLoc(TL);
5537}
5538void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5539 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5540}
5541void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5542 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5543}
5544void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5545 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5546 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5547 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5548}
5549void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5550 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5551 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5552 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5553 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5554}
5555void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5556 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5557}
5558void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5559 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5560 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5561 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5562 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5563}
5564void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5565 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5566}
5567void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5568 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5569}
5570void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5571 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5572}
5573void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5574 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5575 if (TL.hasAttrOperand()) {
5576 SourceRange range;
5577 range.setBegin(ReadSourceLocation(Record, Idx));
5578 range.setEnd(ReadSourceLocation(Record, Idx));
5579 TL.setAttrOperandParensRange(range);
5580 }
5581 if (TL.hasAttrExprOperand()) {
5582 if (Record[Idx++])
5583 TL.setAttrExprOperand(Reader.ReadExpr(F));
5584 else
Craig Toppera13603a2014-05-22 05:54:18 +00005585 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005586 } else if (TL.hasAttrEnumOperand())
5587 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5588}
5589void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5590 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5591}
5592void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5593 SubstTemplateTypeParmTypeLoc TL) {
5594 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5595}
5596void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5597 SubstTemplateTypeParmPackTypeLoc TL) {
5598 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5599}
5600void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5601 TemplateSpecializationTypeLoc TL) {
5602 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5603 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5604 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5605 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5606 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5607 TL.setArgLocInfo(i,
5608 Reader.GetTemplateArgumentLocInfo(F,
5609 TL.getTypePtr()->getArg(i).getKind(),
5610 Record, Idx));
5611}
5612void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5613 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5614 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5615}
5616void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5617 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5618 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5619}
5620void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5621 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5622}
5623void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5624 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5625 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5626 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5627}
5628void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5629 DependentTemplateSpecializationTypeLoc TL) {
5630 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5631 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5632 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5633 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5634 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5635 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5636 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5637 TL.setArgLocInfo(I,
5638 Reader.GetTemplateArgumentLocInfo(F,
5639 TL.getTypePtr()->getArg(I).getKind(),
5640 Record, Idx));
5641}
5642void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5643 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5644}
5645void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5646 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5647}
5648void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5649 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5650 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5651 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5652 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5653 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5654}
5655void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5656 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5657}
5658void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5659 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5660 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5661 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5662}
5663
5664TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5665 const RecordData &Record,
5666 unsigned &Idx) {
5667 QualType InfoTy = readType(F, Record, Idx);
5668 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005669 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005670
5671 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5672 TypeLocReader TLR(*this, F, Record, Idx);
5673 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5674 TLR.Visit(TL);
5675 return TInfo;
5676}
5677
5678QualType ASTReader::GetType(TypeID ID) {
5679 unsigned FastQuals = ID & Qualifiers::FastMask;
5680 unsigned Index = ID >> Qualifiers::FastWidth;
5681
5682 if (Index < NUM_PREDEF_TYPE_IDS) {
5683 QualType T;
5684 switch ((PredefinedTypeIDs)Index) {
5685 case PREDEF_TYPE_NULL_ID: return QualType();
5686 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5687 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5688
5689 case PREDEF_TYPE_CHAR_U_ID:
5690 case PREDEF_TYPE_CHAR_S_ID:
5691 // FIXME: Check that the signedness of CharTy is correct!
5692 T = Context.CharTy;
5693 break;
5694
5695 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5696 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5697 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5698 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5699 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5700 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5701 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5702 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5703 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5704 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5705 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5706 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5707 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5708 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5709 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5710 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5711 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5712 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5713 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5714 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5715 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5716 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5717 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5718 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5719 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5720 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5721 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5722 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005723 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5724 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5725 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5726 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5727 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5728 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005729 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005730 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005731 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5732
5733 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5734 T = Context.getAutoRRefDeductType();
5735 break;
5736
5737 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5738 T = Context.ARCUnbridgedCastTy;
5739 break;
5740
5741 case PREDEF_TYPE_VA_LIST_TAG:
5742 T = Context.getVaListTagType();
5743 break;
5744
5745 case PREDEF_TYPE_BUILTIN_FN:
5746 T = Context.BuiltinFnTy;
5747 break;
5748 }
5749
5750 assert(!T.isNull() && "Unknown predefined type");
5751 return T.withFastQualifiers(FastQuals);
5752 }
5753
5754 Index -= NUM_PREDEF_TYPE_IDS;
5755 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5756 if (TypesLoaded[Index].isNull()) {
5757 TypesLoaded[Index] = readTypeRecord(Index);
5758 if (TypesLoaded[Index].isNull())
5759 return QualType();
5760
5761 TypesLoaded[Index]->setFromAST();
5762 if (DeserializationListener)
5763 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5764 TypesLoaded[Index]);
5765 }
5766
5767 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5768}
5769
5770QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5771 return GetType(getGlobalTypeID(F, LocalID));
5772}
5773
5774serialization::TypeID
5775ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5776 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5777 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5778
5779 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5780 return LocalID;
5781
5782 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5783 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5784 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5785
5786 unsigned GlobalIndex = LocalIndex + I->second;
5787 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5788}
5789
5790TemplateArgumentLocInfo
5791ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5792 TemplateArgument::ArgKind Kind,
5793 const RecordData &Record,
5794 unsigned &Index) {
5795 switch (Kind) {
5796 case TemplateArgument::Expression:
5797 return ReadExpr(F);
5798 case TemplateArgument::Type:
5799 return GetTypeSourceInfo(F, Record, Index);
5800 case TemplateArgument::Template: {
5801 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5802 Index);
5803 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5804 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5805 SourceLocation());
5806 }
5807 case TemplateArgument::TemplateExpansion: {
5808 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5809 Index);
5810 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5811 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5812 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5813 EllipsisLoc);
5814 }
5815 case TemplateArgument::Null:
5816 case TemplateArgument::Integral:
5817 case TemplateArgument::Declaration:
5818 case TemplateArgument::NullPtr:
5819 case TemplateArgument::Pack:
5820 // FIXME: Is this right?
5821 return TemplateArgumentLocInfo();
5822 }
5823 llvm_unreachable("unexpected template argument loc");
5824}
5825
5826TemplateArgumentLoc
5827ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5828 const RecordData &Record, unsigned &Index) {
5829 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5830
5831 if (Arg.getKind() == TemplateArgument::Expression) {
5832 if (Record[Index++]) // bool InfoHasSameExpr.
5833 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5834 }
5835 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5836 Record, Index));
5837}
5838
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005839const ASTTemplateArgumentListInfo*
5840ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5841 const RecordData &Record,
5842 unsigned &Index) {
5843 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5844 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5845 unsigned NumArgsAsWritten = Record[Index++];
5846 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5847 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5848 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5849 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5850}
5851
Guy Benyei11169dd2012-12-18 14:30:41 +00005852Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5853 return GetDecl(ID);
5854}
5855
Richard Smith50895422015-01-31 03:04:55 +00005856template<typename TemplateSpecializationDecl>
5857static void completeRedeclChainForTemplateSpecialization(Decl *D) {
5858 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
5859 TSD->getSpecializedTemplate()->LoadLazySpecializations();
5860}
5861
Richard Smith053f6c62014-05-16 23:01:30 +00005862void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005863 if (NumCurrentElementsDeserializing) {
5864 // We arrange to not care about the complete redeclaration chain while we're
5865 // deserializing. Just remember that the AST has marked this one as complete
5866 // but that it's not actually complete yet, so we know we still need to
5867 // complete it later.
5868 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5869 return;
5870 }
5871
Richard Smith053f6c62014-05-16 23:01:30 +00005872 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5873
Richard Smith053f6c62014-05-16 23:01:30 +00005874 // If this is a named declaration, complete it by looking it up
5875 // within its context.
5876 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00005877 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00005878 // all mergeable entities within it.
5879 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5880 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5881 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
5882 auto *II = Name.getAsIdentifierInfo();
5883 if (isa<TranslationUnitDecl>(DC) && II) {
5884 // Outside of C++, we don't have a lookup table for the TU, so update
5885 // the identifier instead. In C++, either way should work fine.
5886 if (II->isOutOfDate())
5887 updateOutOfDateIdentifier(*II);
5888 } else
5889 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00005890 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
5891 // FIXME: It'd be nice to do something a bit more targeted here.
5892 D->getDeclContext()->decls_begin();
Richard Smith053f6c62014-05-16 23:01:30 +00005893 }
5894 }
Richard Smith50895422015-01-31 03:04:55 +00005895
5896 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
5897 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
5898 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
5899 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
5900 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5901 if (auto *Template = FD->getPrimaryTemplate())
5902 Template->LoadLazySpecializations();
5903 }
Richard Smith053f6c62014-05-16 23:01:30 +00005904}
5905
Richard Smithc2bb8182015-03-24 06:36:48 +00005906uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
5907 const RecordData &Record,
5908 unsigned &Idx) {
5909 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
5910 Error("malformed AST file: missing C++ ctor initializers");
5911 return 0;
5912 }
5913
5914 unsigned LocalID = Record[Idx++];
5915 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
5916}
5917
5918CXXCtorInitializer **
5919ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
5920 RecordLocation Loc = getLocalBitOffset(Offset);
5921 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
5922 SavedStreamPosition SavedPosition(Cursor);
5923 Cursor.JumpToBit(Loc.Offset);
5924 ReadingKindTracker ReadingKind(Read_Decl, *this);
5925
5926 RecordData Record;
5927 unsigned Code = Cursor.ReadCode();
5928 unsigned RecCode = Cursor.readRecord(Code, Record);
5929 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
5930 Error("malformed AST file: missing C++ ctor initializers");
5931 return nullptr;
5932 }
5933
5934 unsigned Idx = 0;
5935 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
5936}
5937
Richard Smithcd45dbc2014-04-19 03:48:30 +00005938uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
5939 const RecordData &Record,
5940 unsigned &Idx) {
5941 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
5942 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005943 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00005944 }
5945
Guy Benyei11169dd2012-12-18 14:30:41 +00005946 unsigned LocalID = Record[Idx++];
5947 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5948}
5949
5950CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5951 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005952 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005953 SavedStreamPosition SavedPosition(Cursor);
5954 Cursor.JumpToBit(Loc.Offset);
5955 ReadingKindTracker ReadingKind(Read_Decl, *this);
5956 RecordData Record;
5957 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005958 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00005959 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005960 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00005961 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005962 }
5963
5964 unsigned Idx = 0;
5965 unsigned NumBases = Record[Idx++];
5966 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5967 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5968 for (unsigned I = 0; I != NumBases; ++I)
5969 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5970 return Bases;
5971}
5972
5973serialization::DeclID
5974ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5975 if (LocalID < NUM_PREDEF_DECL_IDS)
5976 return LocalID;
5977
5978 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5979 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5980 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5981
5982 return LocalID + I->second;
5983}
5984
5985bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5986 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00005987 // Predefined decls aren't from any module.
5988 if (ID < NUM_PREDEF_DECL_IDS)
5989 return false;
5990
Guy Benyei11169dd2012-12-18 14:30:41 +00005991 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5992 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5993 return &M == I->second;
5994}
5995
Douglas Gregor9f782892013-01-21 15:25:38 +00005996ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005997 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00005998 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005999 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6000 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6001 return I->second;
6002}
6003
6004SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6005 if (ID < NUM_PREDEF_DECL_IDS)
6006 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006007
Guy Benyei11169dd2012-12-18 14:30:41 +00006008 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6009
6010 if (Index > DeclsLoaded.size()) {
6011 Error("declaration ID out-of-range for AST file");
6012 return SourceLocation();
6013 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006014
Guy Benyei11169dd2012-12-18 14:30:41 +00006015 if (Decl *D = DeclsLoaded[Index])
6016 return D->getLocation();
6017
6018 unsigned RawLocation = 0;
6019 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6020 return ReadSourceLocation(*Rec.F, RawLocation);
6021}
6022
Richard Smithfe620d22015-03-05 23:24:12 +00006023static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6024 switch (ID) {
6025 case PREDEF_DECL_NULL_ID:
6026 return nullptr;
6027
6028 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6029 return Context.getTranslationUnitDecl();
6030
6031 case PREDEF_DECL_OBJC_ID_ID:
6032 return Context.getObjCIdDecl();
6033
6034 case PREDEF_DECL_OBJC_SEL_ID:
6035 return Context.getObjCSelDecl();
6036
6037 case PREDEF_DECL_OBJC_CLASS_ID:
6038 return Context.getObjCClassDecl();
6039
6040 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6041 return Context.getObjCProtocolDecl();
6042
6043 case PREDEF_DECL_INT_128_ID:
6044 return Context.getInt128Decl();
6045
6046 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6047 return Context.getUInt128Decl();
6048
6049 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6050 return Context.getObjCInstanceTypeDecl();
6051
6052 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6053 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006054
6055 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6056 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006057 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006058 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006059}
6060
Richard Smithcd45dbc2014-04-19 03:48:30 +00006061Decl *ASTReader::GetExistingDecl(DeclID ID) {
6062 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006063 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6064 if (D) {
6065 // Track that we have merged the declaration with ID \p ID into the
6066 // pre-existing predefined declaration \p D.
6067 auto &Merged = MergedDecls[D->getCanonicalDecl()];
6068 if (Merged.empty())
6069 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006070 }
Richard Smithfe620d22015-03-05 23:24:12 +00006071 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006072 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006073
Guy Benyei11169dd2012-12-18 14:30:41 +00006074 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6075
6076 if (Index >= DeclsLoaded.size()) {
6077 assert(0 && "declaration ID out-of-range for AST file");
6078 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006079 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006080 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006081
6082 return DeclsLoaded[Index];
6083}
6084
6085Decl *ASTReader::GetDecl(DeclID ID) {
6086 if (ID < NUM_PREDEF_DECL_IDS)
6087 return GetExistingDecl(ID);
6088
6089 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6090
6091 if (Index >= DeclsLoaded.size()) {
6092 assert(0 && "declaration ID out-of-range for AST file");
6093 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006094 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006095 }
6096
Guy Benyei11169dd2012-12-18 14:30:41 +00006097 if (!DeclsLoaded[Index]) {
6098 ReadDeclRecord(ID);
6099 if (DeserializationListener)
6100 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6101 }
6102
6103 return DeclsLoaded[Index];
6104}
6105
6106DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6107 DeclID GlobalID) {
6108 if (GlobalID < NUM_PREDEF_DECL_IDS)
6109 return GlobalID;
6110
6111 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6112 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6113 ModuleFile *Owner = I->second;
6114
6115 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6116 = M.GlobalToLocalDeclIDs.find(Owner);
6117 if (Pos == M.GlobalToLocalDeclIDs.end())
6118 return 0;
6119
6120 return GlobalID - Owner->BaseDeclID + Pos->second;
6121}
6122
6123serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6124 const RecordData &Record,
6125 unsigned &Idx) {
6126 if (Idx >= Record.size()) {
6127 Error("Corrupted AST file");
6128 return 0;
6129 }
6130
6131 return getGlobalDeclID(F, Record[Idx++]);
6132}
6133
6134/// \brief Resolve the offset of a statement into a statement.
6135///
6136/// This operation will read a new statement from the external
6137/// source each time it is called, and is meant to be used via a
6138/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6139Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6140 // Switch case IDs are per Decl.
6141 ClearSwitchCaseIDs();
6142
6143 // Offset here is a global offset across the entire chain.
6144 RecordLocation Loc = getLocalBitOffset(Offset);
6145 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6146 return ReadStmtFromStream(*Loc.F);
6147}
6148
6149namespace {
6150 class FindExternalLexicalDeclsVisitor {
6151 ASTReader &Reader;
6152 const DeclContext *DC;
6153 bool (*isKindWeWant)(Decl::Kind);
6154
6155 SmallVectorImpl<Decl*> &Decls;
6156 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6157
6158 public:
6159 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6160 bool (*isKindWeWant)(Decl::Kind),
6161 SmallVectorImpl<Decl*> &Decls)
6162 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6163 {
6164 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6165 PredefsVisited[I] = false;
6166 }
6167
Manuel Klimek9eff8b12015-05-20 10:29:23 +00006168 static bool visitPostorder(ModuleFile &M, void *UserData) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006169 FindExternalLexicalDeclsVisitor *This
6170 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6171
6172 ModuleFile::DeclContextInfosMap::iterator Info
6173 = M.DeclContextInfos.find(This->DC);
6174 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6175 return false;
6176
6177 // Load all of the declaration IDs
6178 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6179 *IDE = ID + Info->second.NumLexicalDecls;
6180 ID != IDE; ++ID) {
6181 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6182 continue;
6183
6184 // Don't add predefined declarations to the lexical context more
6185 // than once.
6186 if (ID->second < NUM_PREDEF_DECL_IDS) {
6187 if (This->PredefsVisited[ID->second])
6188 continue;
6189
6190 This->PredefsVisited[ID->second] = true;
6191 }
6192
6193 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6194 if (!This->DC->isDeclInLexicalTraversal(D))
6195 This->Decls.push_back(D);
6196 }
6197 }
6198
6199 return false;
6200 }
6201 };
6202}
6203
6204ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6205 bool (*isKindWeWant)(Decl::Kind),
6206 SmallVectorImpl<Decl*> &Decls) {
6207 // There might be lexical decls in multiple modules, for the TU at
6208 // least. Walk all of the modules in the order they were loaded.
6209 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
Manuel Klimek9eff8b12015-05-20 10:29:23 +00006210 ModuleMgr.visitDepthFirst(
6211 nullptr, &FindExternalLexicalDeclsVisitor::visitPostorder, &Visitor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006212 ++NumLexicalDeclContextsRead;
6213 return ELR_Success;
6214}
6215
6216namespace {
6217
6218class DeclIDComp {
6219 ASTReader &Reader;
6220 ModuleFile &Mod;
6221
6222public:
6223 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6224
6225 bool operator()(LocalDeclID L, LocalDeclID R) const {
6226 SourceLocation LHS = getLocation(L);
6227 SourceLocation RHS = getLocation(R);
6228 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6229 }
6230
6231 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6232 SourceLocation RHS = getLocation(R);
6233 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6234 }
6235
6236 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6237 SourceLocation LHS = getLocation(L);
6238 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6239 }
6240
6241 SourceLocation getLocation(LocalDeclID ID) const {
6242 return Reader.getSourceManager().getFileLoc(
6243 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6244 }
6245};
6246
6247}
6248
6249void ASTReader::FindFileRegionDecls(FileID File,
6250 unsigned Offset, unsigned Length,
6251 SmallVectorImpl<Decl *> &Decls) {
6252 SourceManager &SM = getSourceManager();
6253
6254 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6255 if (I == FileDeclIDs.end())
6256 return;
6257
6258 FileDeclsInfo &DInfo = I->second;
6259 if (DInfo.Decls.empty())
6260 return;
6261
6262 SourceLocation
6263 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6264 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6265
6266 DeclIDComp DIDComp(*this, *DInfo.Mod);
6267 ArrayRef<serialization::LocalDeclID>::iterator
6268 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6269 BeginLoc, DIDComp);
6270 if (BeginIt != DInfo.Decls.begin())
6271 --BeginIt;
6272
6273 // If we are pointing at a top-level decl inside an objc container, we need
6274 // to backtrack until we find it otherwise we will fail to report that the
6275 // region overlaps with an objc container.
6276 while (BeginIt != DInfo.Decls.begin() &&
6277 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6278 ->isTopLevelDeclInObjCContainer())
6279 --BeginIt;
6280
6281 ArrayRef<serialization::LocalDeclID>::iterator
6282 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6283 EndLoc, DIDComp);
6284 if (EndIt != DInfo.Decls.end())
6285 ++EndIt;
6286
6287 for (ArrayRef<serialization::LocalDeclID>::iterator
6288 DIt = BeginIt; DIt != EndIt; ++DIt)
6289 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6290}
6291
6292namespace {
6293 /// \brief ModuleFile visitor used to perform name lookup into a
6294 /// declaration context.
6295 class DeclContextNameLookupVisitor {
6296 ASTReader &Reader;
Richard Smith8c913ec2014-08-14 02:21:01 +00006297 ArrayRef<const DeclContext *> Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006298 DeclarationName Name;
6299 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006300 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006301
6302 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006303 DeclContextNameLookupVisitor(ASTReader &Reader,
6304 ArrayRef<const DeclContext *> Contexts,
Guy Benyei11169dd2012-12-18 14:30:41 +00006305 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006306 SmallVectorImpl<NamedDecl *> &Decls,
6307 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
6308 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls),
6309 DeclSet(DeclSet) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006310
6311 static bool visit(ModuleFile &M, void *UserData) {
6312 DeclContextNameLookupVisitor *This
6313 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6314
6315 // Check whether we have any visible declaration information for
6316 // this context in this module.
6317 ModuleFile::DeclContextInfosMap::iterator Info;
6318 bool FoundInfo = false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006319 for (auto *DC : This->Contexts) {
6320 Info = M.DeclContextInfos.find(DC);
6321 if (Info != M.DeclContextInfos.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006322 Info->second.NameLookupTableData) {
6323 FoundInfo = true;
6324 break;
6325 }
6326 }
6327
6328 if (!FoundInfo)
6329 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006330
Guy Benyei11169dd2012-12-18 14:30:41 +00006331 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006332 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006333 Info->second.NameLookupTableData;
6334 ASTDeclContextNameLookupTable::iterator Pos
6335 = LookupTable->find(This->Name);
6336 if (Pos == LookupTable->end())
6337 return false;
6338
6339 bool FoundAnything = false;
6340 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6341 for (; Data.first != Data.second; ++Data.first) {
6342 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6343 if (!ND)
6344 continue;
6345
6346 if (ND->getDeclName() != This->Name) {
6347 // A name might be null because the decl's redeclarable part is
6348 // currently read before reading its name. The lookup is triggered by
6349 // building that decl (likely indirectly), and so it is later in the
6350 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006351 // FIXME: This should not happen; deserializing declarations should
6352 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006353 continue;
6354 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006355
Guy Benyei11169dd2012-12-18 14:30:41 +00006356 // Record this declaration.
6357 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006358 if (This->DeclSet.insert(ND).second)
6359 This->Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006360 }
6361
6362 return FoundAnything;
6363 }
6364 };
6365}
6366
Douglas Gregor9f782892013-01-21 15:25:38 +00006367/// \brief Retrieve the "definitive" module file for the definition of the
6368/// given declaration context, if there is one.
6369///
6370/// The "definitive" module file is the only place where we need to look to
6371/// find information about the declarations within the given declaration
6372/// context. For example, C++ and Objective-C classes, C structs/unions, and
6373/// Objective-C protocols, categories, and extensions are all defined in a
6374/// single place in the source code, so they have definitive module files
6375/// associated with them. C++ namespaces, on the other hand, can have
6376/// definitions in multiple different module files.
6377///
6378/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6379/// NDEBUG checking.
6380static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6381 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006382 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6383 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006384
Craig Toppera13603a2014-05-22 05:54:18 +00006385 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006386}
6387
Richard Smith9ce12e32013-02-07 03:30:24 +00006388bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006389ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6390 DeclarationName Name) {
6391 assert(DC->hasExternalVisibleStorage() &&
6392 "DeclContext has no visible decls in storage");
6393 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006394 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006395
Richard Smith8c913ec2014-08-14 02:21:01 +00006396 Deserializing LookupResults(this);
6397
Guy Benyei11169dd2012-12-18 14:30:41 +00006398 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006399 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006400
Guy Benyei11169dd2012-12-18 14:30:41 +00006401 // Compute the declaration contexts we need to look into. Multiple such
6402 // declaration contexts occur when two declaration contexts from disjoint
6403 // modules get merged, e.g., when two namespaces with the same name are
6404 // independently defined in separate modules.
6405 SmallVector<const DeclContext *, 2> Contexts;
6406 Contexts.push_back(DC);
Richard Smith8c913ec2014-08-14 02:21:01 +00006407
Guy Benyei11169dd2012-12-18 14:30:41 +00006408 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006409 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006410 if (Merged != MergedDecls.end()) {
6411 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6412 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6413 }
6414 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006415
6416 auto LookUpInContexts = [&](ArrayRef<const DeclContext*> Contexts) {
Richard Smith52874ec2015-02-13 20:17:14 +00006417 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls, DeclSet);
Richard Smith8c913ec2014-08-14 02:21:01 +00006418
6419 // If we can definitively determine which module file to look into,
6420 // only look there. Otherwise, look in all module files.
6421 ModuleFile *Definitive;
6422 if (Contexts.size() == 1 &&
6423 (Definitive = getDefinitiveModuleFileFor(Contexts[0], *this))) {
6424 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6425 } else {
6426 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6427 }
6428 };
6429
6430 LookUpInContexts(Contexts);
6431
6432 // If this might be an implicit special member function, then also search
6433 // all merged definitions of the surrounding class. We need to search them
6434 // individually, because finding an entity in one of them doesn't imply that
6435 // we can't find a different entity in another one.
Richard Smithcd45dbc2014-04-19 03:48:30 +00006436 if (isa<CXXRecordDecl>(DC)) {
Richard Smith02793752015-03-27 21:16:39 +00006437 auto Merged = MergedLookups.find(DC);
6438 if (Merged != MergedLookups.end()) {
6439 for (unsigned I = 0; I != Merged->second.size(); ++I) {
6440 const DeclContext *Context = Merged->second[I];
6441 LookUpInContexts(Context);
6442 // We might have just added some more merged lookups. If so, our
6443 // iterator is now invalid, so grab a fresh one before continuing.
6444 Merged = MergedLookups.find(DC);
Richard Smithe0612472014-11-21 05:16:13 +00006445 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006446 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006447 }
6448
Guy Benyei11169dd2012-12-18 14:30:41 +00006449 ++NumVisibleDeclContextsRead;
6450 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006451 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006452}
6453
6454namespace {
6455 /// \brief ModuleFile visitor used to retrieve all visible names in a
6456 /// declaration context.
6457 class DeclContextAllNamesVisitor {
6458 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006459 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006460 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006461 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006462 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006463
6464 public:
6465 DeclContextAllNamesVisitor(ASTReader &Reader,
6466 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006467 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006468 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006469
6470 static bool visit(ModuleFile &M, void *UserData) {
6471 DeclContextAllNamesVisitor *This
6472 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6473
6474 // Check whether we have any visible declaration information for
6475 // this context in this module.
6476 ModuleFile::DeclContextInfosMap::iterator Info;
6477 bool FoundInfo = false;
6478 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6479 Info = M.DeclContextInfos.find(This->Contexts[I]);
6480 if (Info != M.DeclContextInfos.end() &&
6481 Info->second.NameLookupTableData) {
6482 FoundInfo = true;
6483 break;
6484 }
6485 }
6486
6487 if (!FoundInfo)
6488 return false;
6489
Richard Smith52e3fba2014-03-11 07:17:35 +00006490 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006491 Info->second.NameLookupTableData;
6492 bool FoundAnything = false;
6493 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006494 I = LookupTable->data_begin(), E = LookupTable->data_end();
6495 I != E;
6496 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006497 ASTDeclContextNameLookupTrait::data_type Data = *I;
6498 for (; Data.first != Data.second; ++Data.first) {
6499 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6500 *Data.first);
6501 if (!ND)
6502 continue;
6503
6504 // Record this declaration.
6505 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006506 if (This->DeclSet.insert(ND).second)
6507 This->Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006508 }
6509 }
6510
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006511 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006512 }
6513 };
6514}
6515
6516void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6517 if (!DC->hasExternalVisibleStorage())
6518 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006519 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006520
6521 // Compute the declaration contexts we need to look into. Multiple such
6522 // declaration contexts occur when two declaration contexts from disjoint
6523 // modules get merged, e.g., when two namespaces with the same name are
6524 // independently defined in separate modules.
6525 SmallVector<const DeclContext *, 2> Contexts;
6526 Contexts.push_back(DC);
6527
6528 if (DC->isNamespace()) {
6529 MergedDeclsMap::iterator Merged
6530 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6531 if (Merged != MergedDecls.end()) {
6532 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6533 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6534 }
6535 }
6536
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006537 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6538 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006539 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6540 ++NumVisibleDeclContextsRead;
6541
Craig Topper79be4cd2013-07-05 04:33:53 +00006542 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006543 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6544 }
6545 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6546}
6547
6548/// \brief Under non-PCH compilation the consumer receives the objc methods
6549/// before receiving the implementation, and codegen depends on this.
6550/// We simulate this by deserializing and passing to consumer the methods of the
6551/// implementation before passing the deserialized implementation decl.
6552static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6553 ASTConsumer *Consumer) {
6554 assert(ImplD && Consumer);
6555
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006556 for (auto *I : ImplD->methods())
6557 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006558
6559 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6560}
6561
6562void ASTReader::PassInterestingDeclsToConsumer() {
6563 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006564
6565 if (PassingDeclsToConsumer)
6566 return;
6567
6568 // Guard variable to avoid recursively redoing the process of passing
6569 // decls to consumer.
6570 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6571 true);
6572
Richard Smith9e2341d2015-03-23 03:25:59 +00006573 // Ensure that we've loaded all potentially-interesting declarations
6574 // that need to be eagerly loaded.
6575 for (auto ID : EagerlyDeserializedDecls)
6576 GetDecl(ID);
6577 EagerlyDeserializedDecls.clear();
6578
Guy Benyei11169dd2012-12-18 14:30:41 +00006579 while (!InterestingDecls.empty()) {
6580 Decl *D = InterestingDecls.front();
6581 InterestingDecls.pop_front();
6582
6583 PassInterestingDeclToConsumer(D);
6584 }
6585}
6586
6587void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6588 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6589 PassObjCImplDeclToConsumer(ImplD, Consumer);
6590 else
6591 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6592}
6593
6594void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6595 this->Consumer = Consumer;
6596
Richard Smith9e2341d2015-03-23 03:25:59 +00006597 if (Consumer)
6598 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006599
6600 if (DeserializationListener)
6601 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006602}
6603
6604void ASTReader::PrintStats() {
6605 std::fprintf(stderr, "*** AST File Statistics:\n");
6606
6607 unsigned NumTypesLoaded
6608 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6609 QualType());
6610 unsigned NumDeclsLoaded
6611 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006612 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006613 unsigned NumIdentifiersLoaded
6614 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6615 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006616 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006617 unsigned NumMacrosLoaded
6618 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6619 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006620 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006621 unsigned NumSelectorsLoaded
6622 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6623 SelectorsLoaded.end(),
6624 Selector());
6625
6626 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6627 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6628 NumSLocEntriesRead, TotalNumSLocEntries,
6629 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6630 if (!TypesLoaded.empty())
6631 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6632 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6633 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6634 if (!DeclsLoaded.empty())
6635 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6636 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6637 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6638 if (!IdentifiersLoaded.empty())
6639 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6640 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6641 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6642 if (!MacrosLoaded.empty())
6643 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6644 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6645 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6646 if (!SelectorsLoaded.empty())
6647 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6648 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6649 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6650 if (TotalNumStatements)
6651 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6652 NumStatementsRead, TotalNumStatements,
6653 ((float)NumStatementsRead/TotalNumStatements * 100));
6654 if (TotalNumMacros)
6655 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6656 NumMacrosRead, TotalNumMacros,
6657 ((float)NumMacrosRead/TotalNumMacros * 100));
6658 if (TotalLexicalDeclContexts)
6659 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6660 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6661 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6662 * 100));
6663 if (TotalVisibleDeclContexts)
6664 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6665 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6666 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6667 * 100));
6668 if (TotalNumMethodPoolEntries) {
6669 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6670 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6671 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6672 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006673 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006674 if (NumMethodPoolLookups) {
6675 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6676 NumMethodPoolHits, NumMethodPoolLookups,
6677 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6678 }
6679 if (NumMethodPoolTableLookups) {
6680 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6681 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6682 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6683 * 100.0));
6684 }
6685
Douglas Gregor00a50f72013-01-25 00:38:33 +00006686 if (NumIdentifierLookupHits) {
6687 std::fprintf(stderr,
6688 " %u / %u identifier table lookups succeeded (%f%%)\n",
6689 NumIdentifierLookupHits, NumIdentifierLookups,
6690 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6691 }
6692
Douglas Gregore060e572013-01-25 01:03:03 +00006693 if (GlobalIndex) {
6694 std::fprintf(stderr, "\n");
6695 GlobalIndex->printStats();
6696 }
6697
Guy Benyei11169dd2012-12-18 14:30:41 +00006698 std::fprintf(stderr, "\n");
6699 dump();
6700 std::fprintf(stderr, "\n");
6701}
6702
6703template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6704static void
6705dumpModuleIDMap(StringRef Name,
6706 const ContinuousRangeMap<Key, ModuleFile *,
6707 InitialCapacity> &Map) {
6708 if (Map.begin() == Map.end())
6709 return;
6710
6711 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6712 llvm::errs() << Name << ":\n";
6713 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6714 I != IEnd; ++I) {
6715 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6716 << "\n";
6717 }
6718}
6719
6720void ASTReader::dump() {
6721 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6722 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6723 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6724 dumpModuleIDMap("Global type map", GlobalTypeMap);
6725 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6726 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6727 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6728 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6729 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6730 dumpModuleIDMap("Global preprocessed entity map",
6731 GlobalPreprocessedEntityMap);
6732
6733 llvm::errs() << "\n*** PCH/Modules Loaded:";
6734 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6735 MEnd = ModuleMgr.end();
6736 M != MEnd; ++M)
6737 (*M)->dump();
6738}
6739
6740/// Return the amount of memory used by memory buffers, breaking down
6741/// by heap-backed versus mmap'ed memory.
6742void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6743 for (ModuleConstIterator I = ModuleMgr.begin(),
6744 E = ModuleMgr.end(); I != E; ++I) {
6745 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6746 size_t bytes = buf->getBufferSize();
6747 switch (buf->getBufferKind()) {
6748 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6749 sizes.malloc_bytes += bytes;
6750 break;
6751 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6752 sizes.mmap_bytes += bytes;
6753 break;
6754 }
6755 }
6756 }
6757}
6758
6759void ASTReader::InitializeSema(Sema &S) {
6760 SemaObj = &S;
6761 S.addExternalSource(this);
6762
6763 // Makes sure any declarations that were deserialized "too early"
6764 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006765 for (uint64_t ID : PreloadedDeclIDs) {
6766 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6767 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006768 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006769 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006770
Richard Smith3d8e97e2013-10-18 06:54:39 +00006771 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006772 if (!FPPragmaOptions.empty()) {
6773 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6774 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6775 }
6776
Richard Smith3d8e97e2013-10-18 06:54:39 +00006777 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006778 if (!OpenCLExtensions.empty()) {
6779 unsigned I = 0;
6780#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6781#include "clang/Basic/OpenCLExtensions.def"
6782
6783 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6784 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006785
6786 UpdateSema();
6787}
6788
6789void ASTReader::UpdateSema() {
6790 assert(SemaObj && "no Sema to update");
6791
6792 // Load the offsets of the declarations that Sema references.
6793 // They will be lazily deserialized when needed.
6794 if (!SemaDeclRefs.empty()) {
6795 assert(SemaDeclRefs.size() % 2 == 0);
6796 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6797 if (!SemaObj->StdNamespace)
6798 SemaObj->StdNamespace = SemaDeclRefs[I];
6799 if (!SemaObj->StdBadAlloc)
6800 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6801 }
6802 SemaDeclRefs.clear();
6803 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006804
6805 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6806 // encountered the pragma in the source.
6807 if(OptimizeOffPragmaLocation.isValid())
6808 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006809}
6810
6811IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6812 // Note that we are loading an identifier.
6813 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006814 StringRef Name(NameStart, NameEnd - NameStart);
6815
6816 // If there is a global index, look there first to determine which modules
6817 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006818 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00006819 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00006820 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006821 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6822 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006823 }
6824 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006825 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006826 NumIdentifierLookups,
6827 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006828 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006829 IdentifierInfo *II = Visitor.getIdentifierInfo();
6830 markIdentifierUpToDate(II);
6831 return II;
6832}
6833
6834namespace clang {
6835 /// \brief An identifier-lookup iterator that enumerates all of the
6836 /// identifiers stored within a set of AST files.
6837 class ASTIdentifierIterator : public IdentifierIterator {
6838 /// \brief The AST reader whose identifiers are being enumerated.
6839 const ASTReader &Reader;
6840
6841 /// \brief The current index into the chain of AST files stored in
6842 /// the AST reader.
6843 unsigned Index;
6844
6845 /// \brief The current position within the identifier lookup table
6846 /// of the current AST file.
6847 ASTIdentifierLookupTable::key_iterator Current;
6848
6849 /// \brief The end position within the identifier lookup table of
6850 /// the current AST file.
6851 ASTIdentifierLookupTable::key_iterator End;
6852
6853 public:
6854 explicit ASTIdentifierIterator(const ASTReader &Reader);
6855
Craig Topper3e89dfe2014-03-13 02:13:41 +00006856 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006857 };
6858}
6859
6860ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6861 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6862 ASTIdentifierLookupTable *IdTable
6863 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6864 Current = IdTable->key_begin();
6865 End = IdTable->key_end();
6866}
6867
6868StringRef ASTIdentifierIterator::Next() {
6869 while (Current == End) {
6870 // If we have exhausted all of our AST files, we're done.
6871 if (Index == 0)
6872 return StringRef();
6873
6874 --Index;
6875 ASTIdentifierLookupTable *IdTable
6876 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6877 IdentifierLookupTable;
6878 Current = IdTable->key_begin();
6879 End = IdTable->key_end();
6880 }
6881
6882 // We have any identifiers remaining in the current AST file; return
6883 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006884 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006885 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006886 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006887}
6888
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006889IdentifierIterator *ASTReader::getIdentifiers() {
6890 if (!loadGlobalIndex())
6891 return GlobalIndex->createIdentifierIterator();
6892
Guy Benyei11169dd2012-12-18 14:30:41 +00006893 return new ASTIdentifierIterator(*this);
6894}
6895
6896namespace clang { namespace serialization {
6897 class ReadMethodPoolVisitor {
6898 ASTReader &Reader;
6899 Selector Sel;
6900 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006901 unsigned InstanceBits;
6902 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006903 bool InstanceHasMoreThanOneDecl;
6904 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006905 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6906 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006907
6908 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00006909 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00006910 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00006911 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00006912 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
6913 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00006914
Guy Benyei11169dd2012-12-18 14:30:41 +00006915 static bool visit(ModuleFile &M, void *UserData) {
6916 ReadMethodPoolVisitor *This
6917 = static_cast<ReadMethodPoolVisitor *>(UserData);
6918
6919 if (!M.SelectorLookupTable)
6920 return false;
6921
6922 // If we've already searched this module file, skip it now.
6923 if (M.Generation <= This->PriorGeneration)
6924 return true;
6925
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006926 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006927 ASTSelectorLookupTable *PoolTable
6928 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6929 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6930 if (Pos == PoolTable->end())
6931 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006932
6933 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006934 ++This->Reader.NumSelectorsRead;
6935 // FIXME: Not quite happy with the statistics here. We probably should
6936 // disable this tracking when called via LoadSelector.
6937 // Also, should entries without methods count as misses?
6938 ++This->Reader.NumMethodPoolEntriesRead;
6939 ASTSelectorLookupTrait::data_type Data = *Pos;
6940 if (This->Reader.DeserializationListener)
6941 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6942 This->Sel);
6943
6944 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6945 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006946 This->InstanceBits = Data.InstanceBits;
6947 This->FactoryBits = Data.FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006948 This->InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
6949 This->FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00006950 return true;
6951 }
6952
6953 /// \brief Retrieve the instance methods found by this visitor.
6954 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6955 return InstanceMethods;
6956 }
6957
6958 /// \brief Retrieve the instance methods found by this visitor.
6959 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6960 return FactoryMethods;
6961 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006962
6963 unsigned getInstanceBits() const { return InstanceBits; }
6964 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00006965 bool instanceHasMoreThanOneDecl() const {
6966 return InstanceHasMoreThanOneDecl;
6967 }
6968 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006969 };
6970} } // end namespace clang::serialization
6971
6972/// \brief Add the given set of methods to the method list.
6973static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6974 ObjCMethodList &List) {
6975 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6976 S.addMethodToGlobalList(&List, Methods[I]);
6977 }
6978}
6979
6980void ASTReader::ReadMethodPool(Selector Sel) {
6981 // Get the selector generation and update it to the current generation.
6982 unsigned &Generation = SelectorGeneration[Sel];
6983 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00006984 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00006985
6986 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006987 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006988 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6989 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6990
6991 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006992 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00006993 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006994
6995 ++NumMethodPoolHits;
6996
Guy Benyei11169dd2012-12-18 14:30:41 +00006997 if (!getSema())
6998 return;
6999
7000 Sema &S = *getSema();
7001 Sema::GlobalMethodPool::iterator Pos
7002 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007003
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007004 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007005 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007006 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007007 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007008
7009 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7010 // when building a module we keep every method individually and may need to
7011 // update hasMoreThanOneDecl as we add the methods.
7012 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7013 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007014}
7015
7016void ASTReader::ReadKnownNamespaces(
7017 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7018 Namespaces.clear();
7019
7020 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7021 if (NamespaceDecl *Namespace
7022 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7023 Namespaces.push_back(Namespace);
7024 }
7025}
7026
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007027void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007028 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007029 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7030 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007031 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007032 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007033 Undefined.insert(std::make_pair(D, Loc));
7034 }
7035}
Nick Lewycky8334af82013-01-26 00:35:08 +00007036
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007037void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7038 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7039 Exprs) {
7040 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7041 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7042 uint64_t Count = DelayedDeleteExprs[Idx++];
7043 for (uint64_t C = 0; C < Count; ++C) {
7044 SourceLocation DeleteLoc =
7045 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7046 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7047 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7048 }
7049 }
7050}
7051
Guy Benyei11169dd2012-12-18 14:30:41 +00007052void ASTReader::ReadTentativeDefinitions(
7053 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7054 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7055 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7056 if (Var)
7057 TentativeDefs.push_back(Var);
7058 }
7059 TentativeDefinitions.clear();
7060}
7061
7062void ASTReader::ReadUnusedFileScopedDecls(
7063 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7064 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7065 DeclaratorDecl *D
7066 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7067 if (D)
7068 Decls.push_back(D);
7069 }
7070 UnusedFileScopedDecls.clear();
7071}
7072
7073void ASTReader::ReadDelegatingConstructors(
7074 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7075 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7076 CXXConstructorDecl *D
7077 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7078 if (D)
7079 Decls.push_back(D);
7080 }
7081 DelegatingCtorDecls.clear();
7082}
7083
7084void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7085 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7086 TypedefNameDecl *D
7087 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7088 if (D)
7089 Decls.push_back(D);
7090 }
7091 ExtVectorDecls.clear();
7092}
7093
Nico Weber72889432014-09-06 01:25:55 +00007094void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7095 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7096 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7097 ++I) {
7098 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7099 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7100 if (D)
7101 Decls.insert(D);
7102 }
7103 UnusedLocalTypedefNameCandidates.clear();
7104}
7105
Guy Benyei11169dd2012-12-18 14:30:41 +00007106void ASTReader::ReadReferencedSelectors(
7107 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7108 if (ReferencedSelectorsData.empty())
7109 return;
7110
7111 // If there are @selector references added them to its pool. This is for
7112 // implementation of -Wselector.
7113 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7114 unsigned I = 0;
7115 while (I < DataSize) {
7116 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7117 SourceLocation SelLoc
7118 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7119 Sels.push_back(std::make_pair(Sel, SelLoc));
7120 }
7121 ReferencedSelectorsData.clear();
7122}
7123
7124void ASTReader::ReadWeakUndeclaredIdentifiers(
7125 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7126 if (WeakUndeclaredIdentifiers.empty())
7127 return;
7128
7129 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7130 IdentifierInfo *WeakId
7131 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7132 IdentifierInfo *AliasId
7133 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7134 SourceLocation Loc
7135 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7136 bool Used = WeakUndeclaredIdentifiers[I++];
7137 WeakInfo WI(AliasId, Loc);
7138 WI.setUsed(Used);
7139 WeakIDs.push_back(std::make_pair(WeakId, WI));
7140 }
7141 WeakUndeclaredIdentifiers.clear();
7142}
7143
7144void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7145 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7146 ExternalVTableUse VT;
7147 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7148 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7149 VT.DefinitionRequired = VTableUses[Idx++];
7150 VTables.push_back(VT);
7151 }
7152
7153 VTableUses.clear();
7154}
7155
7156void ASTReader::ReadPendingInstantiations(
7157 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7158 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7159 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7160 SourceLocation Loc
7161 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7162
7163 Pending.push_back(std::make_pair(D, Loc));
7164 }
7165 PendingInstantiations.clear();
7166}
7167
Richard Smithe40f2ba2013-08-07 21:41:30 +00007168void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007169 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007170 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7171 /* In loop */) {
7172 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7173
7174 LateParsedTemplate *LT = new LateParsedTemplate;
7175 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7176
7177 ModuleFile *F = getOwningModuleFile(LT->D);
7178 assert(F && "No module");
7179
7180 unsigned TokN = LateParsedTemplates[Idx++];
7181 LT->Toks.reserve(TokN);
7182 for (unsigned T = 0; T < TokN; ++T)
7183 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7184
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007185 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007186 }
7187
7188 LateParsedTemplates.clear();
7189}
7190
Guy Benyei11169dd2012-12-18 14:30:41 +00007191void ASTReader::LoadSelector(Selector Sel) {
7192 // It would be complicated to avoid reading the methods anyway. So don't.
7193 ReadMethodPool(Sel);
7194}
7195
7196void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7197 assert(ID && "Non-zero identifier ID required");
7198 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7199 IdentifiersLoaded[ID - 1] = II;
7200 if (DeserializationListener)
7201 DeserializationListener->IdentifierRead(ID, II);
7202}
7203
7204/// \brief Set the globally-visible declarations associated with the given
7205/// identifier.
7206///
7207/// If the AST reader is currently in a state where the given declaration IDs
7208/// cannot safely be resolved, they are queued until it is safe to resolve
7209/// them.
7210///
7211/// \param II an IdentifierInfo that refers to one or more globally-visible
7212/// declarations.
7213///
7214/// \param DeclIDs the set of declaration IDs with the name @p II that are
7215/// visible at global scope.
7216///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007217/// \param Decls if non-null, this vector will be populated with the set of
7218/// deserialized declarations. These declarations will not be pushed into
7219/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007220void
7221ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7222 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007223 SmallVectorImpl<Decl *> *Decls) {
7224 if (NumCurrentElementsDeserializing && !Decls) {
7225 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007226 return;
7227 }
7228
7229 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007230 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007231 // Queue this declaration so that it will be added to the
7232 // translation unit scope and identifier's declaration chain
7233 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007234 PreloadedDeclIDs.push_back(DeclIDs[I]);
7235 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007236 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007237
7238 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7239
7240 // If we're simply supposed to record the declarations, do so now.
7241 if (Decls) {
7242 Decls->push_back(D);
7243 continue;
7244 }
7245
7246 // Introduce this declaration into the translation-unit scope
7247 // and add it to the declaration chain for this identifier, so
7248 // that (unqualified) name lookup will find it.
7249 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007250 }
7251}
7252
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007253IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007254 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007255 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007256
7257 if (IdentifiersLoaded.empty()) {
7258 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007259 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007260 }
7261
7262 ID -= 1;
7263 if (!IdentifiersLoaded[ID]) {
7264 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7265 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7266 ModuleFile *M = I->second;
7267 unsigned Index = ID - M->BaseIdentifierID;
7268 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7269
7270 // All of the strings in the AST file are preceded by a 16-bit length.
7271 // Extract that 16-bit length to avoid having to execute strlen().
7272 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7273 // unsigned integers. This is important to avoid integer overflow when
7274 // we cast them to 'unsigned'.
7275 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7276 unsigned StrLen = (((unsigned) StrLenPtr[0])
7277 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007278 IdentifiersLoaded[ID]
7279 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007280 if (DeserializationListener)
7281 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7282 }
7283
7284 return IdentifiersLoaded[ID];
7285}
7286
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007287IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7288 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007289}
7290
7291IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7292 if (LocalID < NUM_PREDEF_IDENT_IDS)
7293 return LocalID;
7294
7295 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7296 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7297 assert(I != M.IdentifierRemap.end()
7298 && "Invalid index into identifier index remap");
7299
7300 return LocalID + I->second;
7301}
7302
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007303MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007304 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007305 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007306
7307 if (MacrosLoaded.empty()) {
7308 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007309 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007310 }
7311
7312 ID -= NUM_PREDEF_MACRO_IDS;
7313 if (!MacrosLoaded[ID]) {
7314 GlobalMacroMapType::iterator I
7315 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7316 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7317 ModuleFile *M = I->second;
7318 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007319 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7320
7321 if (DeserializationListener)
7322 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7323 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007324 }
7325
7326 return MacrosLoaded[ID];
7327}
7328
7329MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7330 if (LocalID < NUM_PREDEF_MACRO_IDS)
7331 return LocalID;
7332
7333 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7334 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7335 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7336
7337 return LocalID + I->second;
7338}
7339
7340serialization::SubmoduleID
7341ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7342 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7343 return LocalID;
7344
7345 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7346 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7347 assert(I != M.SubmoduleRemap.end()
7348 && "Invalid index into submodule index remap");
7349
7350 return LocalID + I->second;
7351}
7352
7353Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7354 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7355 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007356 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007357 }
7358
7359 if (GlobalID > SubmodulesLoaded.size()) {
7360 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007361 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007362 }
7363
7364 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7365}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007366
7367Module *ASTReader::getModule(unsigned ID) {
7368 return getSubmodule(ID);
7369}
7370
Guy Benyei11169dd2012-12-18 14:30:41 +00007371Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7372 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7373}
7374
7375Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7376 if (ID == 0)
7377 return Selector();
7378
7379 if (ID > SelectorsLoaded.size()) {
7380 Error("selector ID out of range in AST file");
7381 return Selector();
7382 }
7383
Craig Toppera13603a2014-05-22 05:54:18 +00007384 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007385 // Load this selector from the selector table.
7386 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7387 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7388 ModuleFile &M = *I->second;
7389 ASTSelectorLookupTrait Trait(*this, M);
7390 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7391 SelectorsLoaded[ID - 1] =
7392 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7393 if (DeserializationListener)
7394 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7395 }
7396
7397 return SelectorsLoaded[ID - 1];
7398}
7399
7400Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7401 return DecodeSelector(ID);
7402}
7403
7404uint32_t ASTReader::GetNumExternalSelectors() {
7405 // ID 0 (the null selector) is considered an external selector.
7406 return getTotalNumSelectors() + 1;
7407}
7408
7409serialization::SelectorID
7410ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7411 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7412 return LocalID;
7413
7414 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7415 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7416 assert(I != M.SelectorRemap.end()
7417 && "Invalid index into selector index remap");
7418
7419 return LocalID + I->second;
7420}
7421
7422DeclarationName
7423ASTReader::ReadDeclarationName(ModuleFile &F,
7424 const RecordData &Record, unsigned &Idx) {
7425 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7426 switch (Kind) {
7427 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007428 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007429
7430 case DeclarationName::ObjCZeroArgSelector:
7431 case DeclarationName::ObjCOneArgSelector:
7432 case DeclarationName::ObjCMultiArgSelector:
7433 return DeclarationName(ReadSelector(F, Record, Idx));
7434
7435 case DeclarationName::CXXConstructorName:
7436 return Context.DeclarationNames.getCXXConstructorName(
7437 Context.getCanonicalType(readType(F, Record, Idx)));
7438
7439 case DeclarationName::CXXDestructorName:
7440 return Context.DeclarationNames.getCXXDestructorName(
7441 Context.getCanonicalType(readType(F, Record, Idx)));
7442
7443 case DeclarationName::CXXConversionFunctionName:
7444 return Context.DeclarationNames.getCXXConversionFunctionName(
7445 Context.getCanonicalType(readType(F, Record, Idx)));
7446
7447 case DeclarationName::CXXOperatorName:
7448 return Context.DeclarationNames.getCXXOperatorName(
7449 (OverloadedOperatorKind)Record[Idx++]);
7450
7451 case DeclarationName::CXXLiteralOperatorName:
7452 return Context.DeclarationNames.getCXXLiteralOperatorName(
7453 GetIdentifierInfo(F, Record, Idx));
7454
7455 case DeclarationName::CXXUsingDirective:
7456 return DeclarationName::getUsingDirectiveName();
7457 }
7458
7459 llvm_unreachable("Invalid NameKind!");
7460}
7461
7462void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7463 DeclarationNameLoc &DNLoc,
7464 DeclarationName Name,
7465 const RecordData &Record, unsigned &Idx) {
7466 switch (Name.getNameKind()) {
7467 case DeclarationName::CXXConstructorName:
7468 case DeclarationName::CXXDestructorName:
7469 case DeclarationName::CXXConversionFunctionName:
7470 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7471 break;
7472
7473 case DeclarationName::CXXOperatorName:
7474 DNLoc.CXXOperatorName.BeginOpNameLoc
7475 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7476 DNLoc.CXXOperatorName.EndOpNameLoc
7477 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7478 break;
7479
7480 case DeclarationName::CXXLiteralOperatorName:
7481 DNLoc.CXXLiteralOperatorName.OpNameLoc
7482 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7483 break;
7484
7485 case DeclarationName::Identifier:
7486 case DeclarationName::ObjCZeroArgSelector:
7487 case DeclarationName::ObjCOneArgSelector:
7488 case DeclarationName::ObjCMultiArgSelector:
7489 case DeclarationName::CXXUsingDirective:
7490 break;
7491 }
7492}
7493
7494void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7495 DeclarationNameInfo &NameInfo,
7496 const RecordData &Record, unsigned &Idx) {
7497 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7498 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7499 DeclarationNameLoc DNLoc;
7500 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7501 NameInfo.setInfo(DNLoc);
7502}
7503
7504void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7505 const RecordData &Record, unsigned &Idx) {
7506 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7507 unsigned NumTPLists = Record[Idx++];
7508 Info.NumTemplParamLists = NumTPLists;
7509 if (NumTPLists) {
7510 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7511 for (unsigned i=0; i != NumTPLists; ++i)
7512 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7513 }
7514}
7515
7516TemplateName
7517ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7518 unsigned &Idx) {
7519 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7520 switch (Kind) {
7521 case TemplateName::Template:
7522 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7523
7524 case TemplateName::OverloadedTemplate: {
7525 unsigned size = Record[Idx++];
7526 UnresolvedSet<8> Decls;
7527 while (size--)
7528 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7529
7530 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7531 }
7532
7533 case TemplateName::QualifiedTemplate: {
7534 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7535 bool hasTemplKeyword = Record[Idx++];
7536 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7537 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7538 }
7539
7540 case TemplateName::DependentTemplate: {
7541 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7542 if (Record[Idx++]) // isIdentifier
7543 return Context.getDependentTemplateName(NNS,
7544 GetIdentifierInfo(F, Record,
7545 Idx));
7546 return Context.getDependentTemplateName(NNS,
7547 (OverloadedOperatorKind)Record[Idx++]);
7548 }
7549
7550 case TemplateName::SubstTemplateTemplateParm: {
7551 TemplateTemplateParmDecl *param
7552 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7553 if (!param) return TemplateName();
7554 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7555 return Context.getSubstTemplateTemplateParm(param, replacement);
7556 }
7557
7558 case TemplateName::SubstTemplateTemplateParmPack: {
7559 TemplateTemplateParmDecl *Param
7560 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7561 if (!Param)
7562 return TemplateName();
7563
7564 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7565 if (ArgPack.getKind() != TemplateArgument::Pack)
7566 return TemplateName();
7567
7568 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7569 }
7570 }
7571
7572 llvm_unreachable("Unhandled template name kind!");
7573}
7574
7575TemplateArgument
7576ASTReader::ReadTemplateArgument(ModuleFile &F,
7577 const RecordData &Record, unsigned &Idx) {
7578 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7579 switch (Kind) {
7580 case TemplateArgument::Null:
7581 return TemplateArgument();
7582 case TemplateArgument::Type:
7583 return TemplateArgument(readType(F, Record, Idx));
7584 case TemplateArgument::Declaration: {
7585 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007586 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007587 }
7588 case TemplateArgument::NullPtr:
7589 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7590 case TemplateArgument::Integral: {
7591 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7592 QualType T = readType(F, Record, Idx);
7593 return TemplateArgument(Context, Value, T);
7594 }
7595 case TemplateArgument::Template:
7596 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7597 case TemplateArgument::TemplateExpansion: {
7598 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007599 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007600 if (unsigned NumExpansions = Record[Idx++])
7601 NumTemplateExpansions = NumExpansions - 1;
7602 return TemplateArgument(Name, NumTemplateExpansions);
7603 }
7604 case TemplateArgument::Expression:
7605 return TemplateArgument(ReadExpr(F));
7606 case TemplateArgument::Pack: {
7607 unsigned NumArgs = Record[Idx++];
7608 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7609 for (unsigned I = 0; I != NumArgs; ++I)
7610 Args[I] = ReadTemplateArgument(F, Record, Idx);
7611 return TemplateArgument(Args, NumArgs);
7612 }
7613 }
7614
7615 llvm_unreachable("Unhandled template argument kind!");
7616}
7617
7618TemplateParameterList *
7619ASTReader::ReadTemplateParameterList(ModuleFile &F,
7620 const RecordData &Record, unsigned &Idx) {
7621 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7622 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7623 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7624
7625 unsigned NumParams = Record[Idx++];
7626 SmallVector<NamedDecl *, 16> Params;
7627 Params.reserve(NumParams);
7628 while (NumParams--)
7629 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7630
7631 TemplateParameterList* TemplateParams =
7632 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7633 Params.data(), Params.size(), RAngleLoc);
7634 return TemplateParams;
7635}
7636
7637void
7638ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007639ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007640 ModuleFile &F, const RecordData &Record,
7641 unsigned &Idx) {
7642 unsigned NumTemplateArgs = Record[Idx++];
7643 TemplArgs.reserve(NumTemplateArgs);
7644 while (NumTemplateArgs--)
7645 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7646}
7647
7648/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007649void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007650 const RecordData &Record, unsigned &Idx) {
7651 unsigned NumDecls = Record[Idx++];
7652 Set.reserve(Context, NumDecls);
7653 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007654 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007655 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007656 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007657 }
7658}
7659
7660CXXBaseSpecifier
7661ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7662 const RecordData &Record, unsigned &Idx) {
7663 bool isVirtual = static_cast<bool>(Record[Idx++]);
7664 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7665 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7666 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7667 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7668 SourceRange Range = ReadSourceRange(F, Record, Idx);
7669 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7670 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7671 EllipsisLoc);
7672 Result.setInheritConstructors(inheritConstructors);
7673 return Result;
7674}
7675
Richard Smithc2bb8182015-03-24 06:36:48 +00007676CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007677ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7678 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007679 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007680 assert(NumInitializers && "wrote ctor initializers but have no inits");
7681 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7682 for (unsigned i = 0; i != NumInitializers; ++i) {
7683 TypeSourceInfo *TInfo = nullptr;
7684 bool IsBaseVirtual = false;
7685 FieldDecl *Member = nullptr;
7686 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007687
Richard Smithc2bb8182015-03-24 06:36:48 +00007688 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7689 switch (Type) {
7690 case CTOR_INITIALIZER_BASE:
7691 TInfo = GetTypeSourceInfo(F, Record, Idx);
7692 IsBaseVirtual = Record[Idx++];
7693 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007694
Richard Smithc2bb8182015-03-24 06:36:48 +00007695 case CTOR_INITIALIZER_DELEGATING:
7696 TInfo = GetTypeSourceInfo(F, Record, Idx);
7697 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007698
Richard Smithc2bb8182015-03-24 06:36:48 +00007699 case CTOR_INITIALIZER_MEMBER:
7700 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7701 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007702
Richard Smithc2bb8182015-03-24 06:36:48 +00007703 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7704 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7705 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007706 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007707
7708 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7709 Expr *Init = ReadExpr(F);
7710 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7711 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7712 bool IsWritten = Record[Idx++];
7713 unsigned SourceOrderOrNumArrayIndices;
7714 SmallVector<VarDecl *, 8> Indices;
7715 if (IsWritten) {
7716 SourceOrderOrNumArrayIndices = Record[Idx++];
7717 } else {
7718 SourceOrderOrNumArrayIndices = Record[Idx++];
7719 Indices.reserve(SourceOrderOrNumArrayIndices);
7720 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7721 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7722 }
7723
7724 CXXCtorInitializer *BOMInit;
7725 if (Type == CTOR_INITIALIZER_BASE) {
7726 BOMInit = new (Context)
7727 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7728 RParenLoc, MemberOrEllipsisLoc);
7729 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7730 BOMInit = new (Context)
7731 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7732 } else if (IsWritten) {
7733 if (Member)
7734 BOMInit = new (Context) CXXCtorInitializer(
7735 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7736 else
7737 BOMInit = new (Context)
7738 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7739 LParenLoc, Init, RParenLoc);
7740 } else {
7741 if (IndirectMember) {
7742 assert(Indices.empty() && "Indirect field improperly initialized");
7743 BOMInit = new (Context)
7744 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7745 LParenLoc, Init, RParenLoc);
7746 } else {
7747 BOMInit = CXXCtorInitializer::Create(
7748 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7749 Indices.data(), Indices.size());
7750 }
7751 }
7752
7753 if (IsWritten)
7754 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7755 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007756 }
7757
Richard Smithc2bb8182015-03-24 06:36:48 +00007758 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007759}
7760
7761NestedNameSpecifier *
7762ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7763 const RecordData &Record, unsigned &Idx) {
7764 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007765 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007766 for (unsigned I = 0; I != N; ++I) {
7767 NestedNameSpecifier::SpecifierKind Kind
7768 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7769 switch (Kind) {
7770 case NestedNameSpecifier::Identifier: {
7771 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7772 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7773 break;
7774 }
7775
7776 case NestedNameSpecifier::Namespace: {
7777 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7778 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7779 break;
7780 }
7781
7782 case NestedNameSpecifier::NamespaceAlias: {
7783 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7784 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7785 break;
7786 }
7787
7788 case NestedNameSpecifier::TypeSpec:
7789 case NestedNameSpecifier::TypeSpecWithTemplate: {
7790 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7791 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007792 return nullptr;
7793
Guy Benyei11169dd2012-12-18 14:30:41 +00007794 bool Template = Record[Idx++];
7795 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7796 break;
7797 }
7798
7799 case NestedNameSpecifier::Global: {
7800 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7801 // No associated value, and there can't be a prefix.
7802 break;
7803 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007804
7805 case NestedNameSpecifier::Super: {
7806 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7807 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7808 break;
7809 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007810 }
7811 Prev = NNS;
7812 }
7813 return NNS;
7814}
7815
7816NestedNameSpecifierLoc
7817ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7818 unsigned &Idx) {
7819 unsigned N = Record[Idx++];
7820 NestedNameSpecifierLocBuilder Builder;
7821 for (unsigned I = 0; I != N; ++I) {
7822 NestedNameSpecifier::SpecifierKind Kind
7823 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7824 switch (Kind) {
7825 case NestedNameSpecifier::Identifier: {
7826 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7827 SourceRange Range = ReadSourceRange(F, Record, Idx);
7828 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7829 break;
7830 }
7831
7832 case NestedNameSpecifier::Namespace: {
7833 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7834 SourceRange Range = ReadSourceRange(F, Record, Idx);
7835 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7836 break;
7837 }
7838
7839 case NestedNameSpecifier::NamespaceAlias: {
7840 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7841 SourceRange Range = ReadSourceRange(F, Record, Idx);
7842 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7843 break;
7844 }
7845
7846 case NestedNameSpecifier::TypeSpec:
7847 case NestedNameSpecifier::TypeSpecWithTemplate: {
7848 bool Template = Record[Idx++];
7849 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7850 if (!T)
7851 return NestedNameSpecifierLoc();
7852 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7853
7854 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7855 Builder.Extend(Context,
7856 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7857 T->getTypeLoc(), ColonColonLoc);
7858 break;
7859 }
7860
7861 case NestedNameSpecifier::Global: {
7862 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7863 Builder.MakeGlobal(Context, ColonColonLoc);
7864 break;
7865 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007866
7867 case NestedNameSpecifier::Super: {
7868 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7869 SourceRange Range = ReadSourceRange(F, Record, Idx);
7870 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
7871 break;
7872 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007873 }
7874 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007875
Guy Benyei11169dd2012-12-18 14:30:41 +00007876 return Builder.getWithLocInContext(Context);
7877}
7878
7879SourceRange
7880ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7881 unsigned &Idx) {
7882 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7883 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7884 return SourceRange(beg, end);
7885}
7886
7887/// \brief Read an integral value
7888llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7889 unsigned BitWidth = Record[Idx++];
7890 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7891 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7892 Idx += NumWords;
7893 return Result;
7894}
7895
7896/// \brief Read a signed integral value
7897llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7898 bool isUnsigned = Record[Idx++];
7899 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7900}
7901
7902/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007903llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7904 const llvm::fltSemantics &Sem,
7905 unsigned &Idx) {
7906 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007907}
7908
7909// \brief Read a string
7910std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7911 unsigned Len = Record[Idx++];
7912 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7913 Idx += Len;
7914 return Result;
7915}
7916
Richard Smith7ed1bc92014-12-05 22:42:13 +00007917std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
7918 unsigned &Idx) {
7919 std::string Filename = ReadString(Record, Idx);
7920 ResolveImportedPath(F, Filename);
7921 return Filename;
7922}
7923
Guy Benyei11169dd2012-12-18 14:30:41 +00007924VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7925 unsigned &Idx) {
7926 unsigned Major = Record[Idx++];
7927 unsigned Minor = Record[Idx++];
7928 unsigned Subminor = Record[Idx++];
7929 if (Minor == 0)
7930 return VersionTuple(Major);
7931 if (Subminor == 0)
7932 return VersionTuple(Major, Minor - 1);
7933 return VersionTuple(Major, Minor - 1, Subminor - 1);
7934}
7935
7936CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7937 const RecordData &Record,
7938 unsigned &Idx) {
7939 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7940 return CXXTemporary::Create(Context, Decl);
7941}
7942
7943DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007944 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007945}
7946
7947DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7948 return Diags.Report(Loc, DiagID);
7949}
7950
7951/// \brief Retrieve the identifier table associated with the
7952/// preprocessor.
7953IdentifierTable &ASTReader::getIdentifierTable() {
7954 return PP.getIdentifierTable();
7955}
7956
7957/// \brief Record that the given ID maps to the given switch-case
7958/// statement.
7959void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007960 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007961 "Already have a SwitchCase with this ID");
7962 (*CurrSwitchCaseStmts)[ID] = SC;
7963}
7964
7965/// \brief Retrieve the switch-case statement with the given ID.
7966SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007967 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00007968 return (*CurrSwitchCaseStmts)[ID];
7969}
7970
7971void ASTReader::ClearSwitchCaseIDs() {
7972 CurrSwitchCaseStmts->clear();
7973}
7974
7975void ASTReader::ReadComments() {
7976 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007977 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007978 serialization::ModuleFile *> >::iterator
7979 I = CommentsCursors.begin(),
7980 E = CommentsCursors.end();
7981 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007982 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007983 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007984 serialization::ModuleFile &F = *I->second;
7985 SavedStreamPosition SavedPosition(Cursor);
7986
7987 RecordData Record;
7988 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007989 llvm::BitstreamEntry Entry =
7990 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007991
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007992 switch (Entry.Kind) {
7993 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7994 case llvm::BitstreamEntry::Error:
7995 Error("malformed block record in AST file");
7996 return;
7997 case llvm::BitstreamEntry::EndBlock:
7998 goto NextCursor;
7999 case llvm::BitstreamEntry::Record:
8000 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008001 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008002 }
8003
8004 // Read a record.
8005 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008006 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008007 case COMMENTS_RAW_COMMENT: {
8008 unsigned Idx = 0;
8009 SourceRange SR = ReadSourceRange(F, Record, Idx);
8010 RawComment::CommentKind Kind =
8011 (RawComment::CommentKind) Record[Idx++];
8012 bool IsTrailingComment = Record[Idx++];
8013 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008014 Comments.push_back(new (Context) RawComment(
8015 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8016 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008017 break;
8018 }
8019 }
8020 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008021 NextCursor:
8022 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008023 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008024}
8025
Argyrios Kyrtzidis1bde1172014-11-18 05:24:18 +00008026void ASTReader::getInputFiles(ModuleFile &F,
8027 SmallVectorImpl<serialization::InputFile> &Files) {
8028 for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
8029 unsigned ID = I+1;
8030 Files.push_back(getInputFile(F, ID));
8031 }
8032}
8033
Richard Smithcd45dbc2014-04-19 03:48:30 +00008034std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8035 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008036 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008037 return M->getFullModuleName();
8038
8039 // Otherwise, use the name of the top-level module the decl is within.
8040 if (ModuleFile *M = getOwningModuleFile(D))
8041 return M->ModuleName;
8042
8043 // Not from a module.
8044 return "";
8045}
8046
Guy Benyei11169dd2012-12-18 14:30:41 +00008047void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008048 while (!PendingIdentifierInfos.empty() ||
8049 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008050 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008051 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008052 // If any identifiers with corresponding top-level declarations have
8053 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008054 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8055 TopLevelDeclsMap;
8056 TopLevelDeclsMap TopLevelDecls;
8057
Guy Benyei11169dd2012-12-18 14:30:41 +00008058 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008059 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008060 SmallVector<uint32_t, 4> DeclIDs =
8061 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008062 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008063
8064 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008065 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008066
Richard Smith851072e2014-05-19 20:59:20 +00008067 // For each decl chain that we wanted to complete while deserializing, mark
8068 // it as "still needs to be completed".
8069 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8070 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8071 }
8072 PendingIncompleteDeclChains.clear();
8073
Guy Benyei11169dd2012-12-18 14:30:41 +00008074 // Load pending declaration chains.
Richard Smithfe620d22015-03-05 23:24:12 +00008075 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
Richard Smithfe620d22015-03-05 23:24:12 +00008076 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
Richard Smithe687bf82015-03-16 20:54:07 +00008077 loadPendingDeclChain(PendingDeclChains[I]);
Richard Smithfe620d22015-03-05 23:24:12 +00008078 }
8079 assert(PendingDeclChainsKnown.empty());
Guy Benyei11169dd2012-12-18 14:30:41 +00008080 PendingDeclChains.clear();
8081
Douglas Gregor6168bd22013-02-18 15:53:43 +00008082 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008083 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8084 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008085 IdentifierInfo *II = TLD->first;
8086 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008087 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008088 }
8089 }
8090
Guy Benyei11169dd2012-12-18 14:30:41 +00008091 // Load any pending macro definitions.
8092 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008093 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8094 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8095 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8096 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008097 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008098 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008099 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008100 if (Info.M->Kind != MK_ImplicitModule &&
8101 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008102 resolvePendingMacro(II, Info);
8103 }
8104 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008105 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008106 ++IDIdx) {
8107 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008108 if (Info.M->Kind == MK_ImplicitModule ||
8109 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008110 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008111 }
8112 }
8113 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008114
8115 // Wire up the DeclContexts for Decls that we delayed setting until
8116 // recursive loading is completed.
8117 while (!PendingDeclContextInfos.empty()) {
8118 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8119 PendingDeclContextInfos.pop_front();
8120 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8121 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8122 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8123 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008124
Richard Smithd1c46742014-04-30 02:24:17 +00008125 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008126 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008127 auto Update = PendingUpdateRecords.pop_back_val();
8128 ReadingKindTracker ReadingKind(Read_Decl, *this);
8129 loadDeclUpdateRecords(Update.first, Update.second);
8130 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008131 }
Richard Smith8a639892015-01-24 01:07:20 +00008132
8133 // At this point, all update records for loaded decls are in place, so any
8134 // fake class definitions should have become real.
8135 assert(PendingFakeDefinitionData.empty() &&
8136 "faked up a class definition but never saw the real one");
8137
Guy Benyei11169dd2012-12-18 14:30:41 +00008138 // If we deserialized any C++ or Objective-C class definitions, any
8139 // Objective-C protocol definitions, or any redeclarable templates, make sure
8140 // that all redeclarations point to the definitions. Note that this can only
8141 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008142 for (Decl *D : PendingDefinitions) {
8143 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008144 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008145 // Make sure that the TagType points at the definition.
8146 const_cast<TagType*>(TagT)->decl = TD;
8147 }
Richard Smith8ce51082015-03-11 01:44:51 +00008148
Craig Topperc6914d02014-08-25 04:15:02 +00008149 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008150 for (auto *R = getMostRecentExistingDecl(RD); R;
8151 R = R->getPreviousDecl()) {
8152 assert((R == D) ==
8153 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008154 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008155 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008156 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008157 }
8158
8159 continue;
8160 }
Richard Smith8ce51082015-03-11 01:44:51 +00008161
Craig Topperc6914d02014-08-25 04:15:02 +00008162 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008163 // Make sure that the ObjCInterfaceType points at the definition.
8164 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8165 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008166
8167 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8168 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8169
Guy Benyei11169dd2012-12-18 14:30:41 +00008170 continue;
8171 }
Richard Smith8ce51082015-03-11 01:44:51 +00008172
Craig Topperc6914d02014-08-25 04:15:02 +00008173 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008174 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8175 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8176
Guy Benyei11169dd2012-12-18 14:30:41 +00008177 continue;
8178 }
Richard Smith8ce51082015-03-11 01:44:51 +00008179
Craig Topperc6914d02014-08-25 04:15:02 +00008180 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008181 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8182 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008183 }
8184 PendingDefinitions.clear();
8185
8186 // Load the bodies of any functions or methods we've encountered. We do
8187 // this now (delayed) so that we can be sure that the declaration chains
8188 // have been fully wired up.
Richard Smith8ce51082015-03-11 01:44:51 +00008189 // FIXME: There seems to be no point in delaying this, it does not depend
8190 // on the redecl chains having been wired up.
Guy Benyei11169dd2012-12-18 14:30:41 +00008191 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8192 PBEnd = PendingBodies.end();
8193 PB != PBEnd; ++PB) {
8194 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8195 // FIXME: Check for =delete/=default?
8196 // FIXME: Complain about ODR violations here?
8197 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8198 FD->setLazyBody(PB->second);
8199 continue;
8200 }
8201
8202 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8203 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8204 MD->setLazyBody(PB->second);
8205 }
8206 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008207
8208 // Do some cleanup.
8209 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8210 getContext().deduplicateMergedDefinitonsFor(ND);
8211 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008212}
8213
8214void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008215 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8216 return;
8217
Richard Smitha0ce9c42014-07-29 23:23:27 +00008218 // Trigger the import of the full definition of each class that had any
8219 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008220 // These updates may in turn find and diagnose some ODR failures, so take
8221 // ownership of the set first.
8222 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8223 PendingOdrMergeFailures.clear();
8224 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008225 Merge.first->buildLookup();
8226 Merge.first->decls_begin();
8227 Merge.first->bases_begin();
8228 Merge.first->vbases_begin();
8229 for (auto *RD : Merge.second) {
8230 RD->decls_begin();
8231 RD->bases_begin();
8232 RD->vbases_begin();
8233 }
8234 }
8235
8236 // For each declaration from a merged context, check that the canonical
8237 // definition of that context also contains a declaration of the same
8238 // entity.
8239 //
8240 // Caution: this loop does things that might invalidate iterators into
8241 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8242 while (!PendingOdrMergeChecks.empty()) {
8243 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8244
8245 // FIXME: Skip over implicit declarations for now. This matters for things
8246 // like implicitly-declared special member functions. This isn't entirely
8247 // correct; we can end up with multiple unmerged declarations of the same
8248 // implicit entity.
8249 if (D->isImplicit())
8250 continue;
8251
8252 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008253
8254 bool Found = false;
8255 const Decl *DCanon = D->getCanonicalDecl();
8256
Richard Smith01bdb7a2014-08-28 05:44:07 +00008257 for (auto RI : D->redecls()) {
8258 if (RI->getLexicalDeclContext() == CanonDef) {
8259 Found = true;
8260 break;
8261 }
8262 }
8263 if (Found)
8264 continue;
8265
Richard Smitha0ce9c42014-07-29 23:23:27 +00008266 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith01bdb7a2014-08-28 05:44:07 +00008267 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
Richard Smitha0ce9c42014-07-29 23:23:27 +00008268 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8269 !Found && I != E; ++I) {
8270 for (auto RI : (*I)->redecls()) {
8271 if (RI->getLexicalDeclContext() == CanonDef) {
8272 // This declaration is present in the canonical definition. If it's
8273 // in the same redecl chain, it's the one we're looking for.
8274 if (RI->getCanonicalDecl() == DCanon)
8275 Found = true;
8276 else
8277 Candidates.push_back(cast<NamedDecl>(RI));
8278 break;
8279 }
8280 }
8281 }
8282
8283 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008284 // The AST doesn't like TagDecls becoming invalid after they've been
8285 // completed. We only really need to mark FieldDecls as invalid here.
8286 if (!isa<TagDecl>(D))
8287 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008288
8289 // Ensure we don't accidentally recursively enter deserialization while
8290 // we're producing our diagnostic.
8291 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008292
8293 std::string CanonDefModule =
8294 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8295 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8296 << D << getOwningModuleNameForDiagnostic(D)
8297 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8298
8299 if (Candidates.empty())
8300 Diag(cast<Decl>(CanonDef)->getLocation(),
8301 diag::note_module_odr_violation_no_possible_decls) << D;
8302 else {
8303 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8304 Diag(Candidates[I]->getLocation(),
8305 diag::note_module_odr_violation_possible_decl)
8306 << Candidates[I];
8307 }
8308
8309 DiagnosedOdrMergeFailures.insert(CanonDef);
8310 }
8311 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008312
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008313 if (OdrMergeFailures.empty())
8314 return;
8315
8316 // Ensure we don't accidentally recursively enter deserialization while
8317 // we're producing our diagnostics.
8318 Deserializing RecursionGuard(this);
8319
Richard Smithcd45dbc2014-04-19 03:48:30 +00008320 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008321 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008322 // If we've already pointed out a specific problem with this class, don't
8323 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008324 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008325 continue;
8326
8327 bool Diagnosed = false;
8328 for (auto *RD : Merge.second) {
8329 // Multiple different declarations got merged together; tell the user
8330 // where they came from.
8331 if (Merge.first != RD) {
8332 // FIXME: Walk the definition, figure out what's different,
8333 // and diagnose that.
8334 if (!Diagnosed) {
8335 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8336 Diag(Merge.first->getLocation(),
8337 diag::err_module_odr_violation_different_definitions)
8338 << Merge.first << Module.empty() << Module;
8339 Diagnosed = true;
8340 }
8341
8342 Diag(RD->getLocation(),
8343 diag::note_module_odr_violation_different_definitions)
8344 << getOwningModuleNameForDiagnostic(RD);
8345 }
8346 }
8347
8348 if (!Diagnosed) {
8349 // All definitions are updates to the same declaration. This happens if a
8350 // module instantiates the declaration of a class template specialization
8351 // and two or more other modules instantiate its definition.
8352 //
8353 // FIXME: Indicate which modules had instantiations of this definition.
8354 // FIXME: How can this even happen?
8355 Diag(Merge.first->getLocation(),
8356 diag::err_module_odr_violation_different_instantiations)
8357 << Merge.first;
8358 }
8359 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008360}
8361
8362void ASTReader::FinishedDeserializing() {
8363 assert(NumCurrentElementsDeserializing &&
8364 "FinishedDeserializing not paired with StartedDeserializing");
8365 if (NumCurrentElementsDeserializing == 1) {
8366 // We decrease NumCurrentElementsDeserializing only after pending actions
8367 // are finished, to avoid recursively re-calling finishPendingActions().
8368 finishPendingActions();
8369 }
8370 --NumCurrentElementsDeserializing;
8371
Richard Smitha0ce9c42014-07-29 23:23:27 +00008372 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008373 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008374 while (!PendingExceptionSpecUpdates.empty()) {
8375 auto Updates = std::move(PendingExceptionSpecUpdates);
8376 PendingExceptionSpecUpdates.clear();
8377 for (auto Update : Updates) {
8378 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8379 SemaObj->UpdateExceptionSpec(Update.second,
8380 FPT->getExtProtoInfo().ExceptionSpec);
8381 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008382 }
8383
Richard Smitha0ce9c42014-07-29 23:23:27 +00008384 diagnoseOdrViolations();
8385
Richard Smith04d05b52014-03-23 00:27:18 +00008386 // We are not in recursive loading, so it's safe to pass the "interesting"
8387 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008388 if (Consumer)
8389 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008390 }
8391}
8392
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008393void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008394 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8395 // Remove any fake results before adding any real ones.
8396 auto It = PendingFakeLookupResults.find(II);
8397 if (It != PendingFakeLookupResults.end()) {
8398 for (auto *ND : PendingFakeLookupResults[II])
8399 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008400 // FIXME: this works around module+PCH performance issue.
8401 // Rather than erase the result from the map, which is O(n), just clear
8402 // the vector of NamedDecls.
8403 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008404 }
8405 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008406
8407 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8408 SemaObj->TUScope->AddDecl(D);
8409 } else if (SemaObj->TUScope) {
8410 // Adding the decl to IdResolver may have failed because it was already in
8411 // (even though it was not added in scope). If it is already in, make sure
8412 // it gets in the scope as well.
8413 if (std::find(SemaObj->IdResolver.begin(Name),
8414 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8415 SemaObj->TUScope->AddDecl(D);
8416 }
8417}
8418
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008419ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
8420 const PCHContainerOperations &PCHContainerOps,
8421 StringRef isysroot, bool DisableValidation,
8422 bool AllowASTWithCompilerErrors,
Nico Weber824285e2014-05-08 04:26:47 +00008423 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008424 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008425 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008426 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008427 FileMgr(PP.getFileManager()), PCHContainerOps(PCHContainerOps),
8428 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
8429 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerOps),
8430 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008431 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8432 AllowConfigurationMismatch(AllowConfigurationMismatch),
8433 ValidateSystemInputs(ValidateSystemInputs),
8434 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008435 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8436 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8437 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8438 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008439 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8440 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8441 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8442 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8443 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8444 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008445 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008446 SourceMgr.setExternalSLocEntrySource(this);
8447}
8448
8449ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008450 if (OwnsDeserializationListener)
8451 delete DeserializationListener;
8452
Guy Benyei11169dd2012-12-18 14:30:41 +00008453 for (DeclContextVisibleUpdatesPending::iterator
8454 I = PendingVisibleUpdates.begin(),
8455 E = PendingVisibleUpdates.end();
8456 I != E; ++I) {
8457 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8458 F = I->second.end();
8459 J != F; ++J)
8460 delete J->first;
8461 }
8462}